@@ -4,13 +4,14 @@ import {
4
4
Graph ,
5
5
Session ,
6
6
SGDOptimizer ,
7
- NDArrayMathGPU ,
7
+ ENV ,
8
+ NDArrayMath ,
8
9
CostReduction ,
9
10
} from 'deeplearn' ;
10
11
11
- const math = new NDArrayMathGPU ( ) ;
12
-
13
12
class MnistModel {
13
+ math = ENV . math ;
14
+
14
15
session ;
15
16
16
17
initialLearningRate = 0.06 ;
@@ -42,32 +43,37 @@ class MnistModel {
42
43
this . predictionTensor = this . createFullyConnectedLayer ( graph , fullyConnectedLayer , 3 , 10 ) ;
43
44
this . costTensor = graph . meanSquaredCost ( this . targetTensor , this . predictionTensor ) ;
44
45
45
- this . session = new Session ( graph , math ) ;
46
+ this . session = new Session ( graph , this . math ) ;
46
47
47
48
this . prepareTrainingSet ( trainingSet ) ;
48
49
}
49
50
50
51
prepareTrainingSet ( trainingSet ) {
51
- math . scope ( ( ) => {
52
- const inputArray = trainingSet . map ( v => Array1D . new ( v . input ) ) ;
53
- const targetArray = trainingSet . map ( v => Array1D . new ( v . output ) ) ;
52
+ const oldMath = ENV . math ;
53
+ const safeMode = false ;
54
+ const math = new NDArrayMath ( 'cpu' , safeMode ) ;
55
+ ENV . setMath ( math ) ;
54
56
55
- const shuffledInputProviderBuilder = new InCPUMemoryShuffledInputProviderBuilder ( [ inputArray , targetArray ] ) ;
56
- const [ inputProvider , targetProvider ] = shuffledInputProviderBuilder . getInputProviders ( ) ;
57
+ const inputArray = trainingSet . map ( v => Array1D . new ( v . input ) ) ;
58
+ const targetArray = trainingSet . map ( v => Array1D . new ( v . output ) ) ;
57
59
58
- this . feedEntries = [
59
- { tensor : this . inputTensor , data : inputProvider } ,
60
- { tensor : this . targetTensor , data : targetProvider } ,
61
- ] ;
62
- } ) ;
60
+ const shuffledInputProviderBuilder = new InCPUMemoryShuffledInputProviderBuilder ( [ inputArray , targetArray ] ) ;
61
+ const [ inputProvider , targetProvider ] = shuffledInputProviderBuilder . getInputProviders ( ) ;
62
+
63
+ this . feedEntries = [
64
+ { tensor : this . inputTensor , data : inputProvider } ,
65
+ { tensor : this . targetTensor , data : targetProvider } ,
66
+ ] ;
67
+
68
+ ENV . setMath ( oldMath ) ;
63
69
}
64
70
65
71
train ( step , computeCost ) {
66
72
let learningRate = this . initialLearningRate * Math . pow ( 0.90 , Math . floor ( step / 50 ) ) ;
67
73
this . optimizer . setLearningRate ( learningRate ) ;
68
74
69
75
let costValue ;
70
- math . scope ( ( ) => {
76
+ this . math . scope ( ( ) => {
71
77
const cost = this . session . train (
72
78
this . costTensor ,
73
79
this . feedEntries ,
@@ -87,7 +93,7 @@ class MnistModel {
87
93
predict ( pixels ) {
88
94
let classifier = [ ] ;
89
95
90
- math . scope ( ( ) => {
96
+ this . math . scope ( ( ) => {
91
97
const mapping = [ {
92
98
tensor : this . inputTensor ,
93
99
data : Array1D . new ( pixels ) ,
0 commit comments