-
Notifications
You must be signed in to change notification settings - Fork 9
/
MNIST-CNN.fsx
306 lines (241 loc) · 9.29 KB
/
MNIST-CNN.fsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
(*
F# port of the original C# example from the CNTK docs:
https://github.com/Microsoft/CNTK/blob/master/Examples/TrainingCSharp/Common/MNISTClassifier.cs
*)
// Use the CNTK.fsx file to load the dependencies.
#load "../CNTK.fsx"
open CNTK
open System
open System.IO
open System.Collections.Generic
// Conversion of the original C# code to an F# script
let FullyConnectedLinearLayer(
input:VarOrFun,
outputDim:int,
name:string,
device:DeviceDescriptor) =
let inputDim = input.Variable.Shape.[0]
let timesParam =
new Parameter(
shape [outputDim; inputDim],
DataType.Float,
CNTKLib.GlorotUniformInitializer(
float CNTKLib.DefaultParamInitScale,
CNTKLib.SentinelValueForInferParamInitRank,
CNTKLib.SentinelValueForInferParamInitRank,
uint32 1),
device,
"timesParam")
let timesFunction =
new Variable(CNTKLib.Times(timesParam, input.Variable, "times"))
let plusParam = new Parameter(shape [ outputDim ], 0.0f, device, "plusParam")
CNTKLib.Plus(plusParam, timesFunction, name) |> Fun
let dense
(device:DeviceDescriptor)
(outputDim:int)
// this should not be necessary but setting the name of the function separately
// is causing some grief when re-opening the model!?
(name:string)
(input:VarOrFun) =
let input =
if (input.Variable.Shape.Rank <> 1)
then
let newDim = input.Variable.Shape.Dimensions |> Seq.reduce(*)
new Variable(CNTKLib.Reshape(input.Variable, shape [ newDim ]))
|> Var
else input
FullyConnectedLinearLayer(input, outputDim, name, device)
// definition / configuration of the network
let featureStreamName = "features"
let labelsStreamName = "labels"
let classifierName = "classifierOutput"
let imageSize = 28 * 28
let numClasses = 10
let modelFile = Path.Combine(__SOURCE_DIRECTORY__,"MNISTConvolution.model")
let input = CNTKLib.InputVariable(shape [ 28; 28; 1 ], DataType.Float, featureStreamName)
let hiddenLayerDim = 200
let scalingFactor = float32 (1./255.)
let device = DeviceDescriptor.CPUDevice
let scale<'T> (device:DeviceDescriptor) (scalar:'T) (input:VarOrFun) =
CNTKLib.ElementTimes(
Constant.Scalar<'T>(scalar, device),
input.Variable
)
|> Fun
let ReLU (x:VarOrFun) = CNTKLib.ReLU (x.Variable) |> Fun
let funcToVar (f:Function) = new Variable(f)
let classifierOutput =
Var input
|> scale device scalingFactor
// 28x28x1 -> 14x14x4
|> Conv2D.convolution
device
{
Kernel = { Width = 3; Height = 3 }
InputChannels = 1
OutputFeatureMap = 4
}
|> ReLU
|> Conv2D.pooling
{
PoolingType = PoolingType.Max
Window = { Width = 3; Height = 3 }
Stride = { Horizontal = 2; Vertical = 2 }
}
// 14x14x4 -> 7x7x8
|> Conv2D.convolution
device
{
Kernel = { Width = 3; Height = 3 }
InputChannels = 4 // same as OutputFeatureMap previous conv
OutputFeatureMap = 8
}
|> ReLU
|> Conv2D.pooling
{
PoolingType = PoolingType.Max
Window = { Width = 3; Height = 3 }
Stride = { Horizontal = 2; Vertical = 2 }
}
// dense final layer
|> dense device numClasses classifierName
let labels = CNTKLib.InputVariable(shape [ numClasses ], DataType.Float, labelsStreamName)
let trainingLoss = CNTKLib.CrossEntropyWithSoftmax(classifierOutput.Variable, labels, "lossFunction")
let prediction = CNTKLib.ClassificationError(classifierOutput.Variable, labels, "classificationError")
// set per sample learning rate
let learningRatePerSample : CNTK.TrainingParameterScheduleDouble =
new CNTK.TrainingParameterScheduleDouble(0.003125, uint32 1)
let parameterLearners =
ResizeArray<Learner>(
[
Learner.SGDLearner(classifierOutput.Function.Parameters(), learningRatePerSample)
]
)
let trainer = Trainer.CreateTrainer(classifierOutput.Function, trainingLoss, prediction, parameterLearners)
let streamConfigurations =
ResizeArray<StreamConfiguration>(
[
new StreamConfiguration(featureStreamName, imageSize)
new StreamConfiguration(labelsStreamName, numClasses)
]
)
let ImageDataFolder = Path.Combine(__SOURCE_DIRECTORY__, "../data/")
let minibatchSource =
MinibatchSource.TextFormatMinibatchSource(
Path.Combine(ImageDataFolder, "Train_cntk_text.txt"),
streamConfigurations,
MinibatchSource.InfinitelyRepeat)
let featureStreamInfo = minibatchSource.StreamInfo(featureStreamName)
let labelStreamInfo = minibatchSource.StreamInfo(labelsStreamName)
let minibatchSize = uint32 64
let outputFrequencyInMinibatches = 20
let learn epochs =
let report = progress (trainer, outputFrequencyInMinibatches)
let rec learnEpoch (step,epoch) =
if epoch <= 0
// we are done
then ignore ()
else
let step = step + 1
let minibatchData = minibatchSource.GetNextMinibatch(minibatchSize, device)
let arguments : IDictionary<Variable, MinibatchData> =
[
input, minibatchData.[featureStreamInfo]
labels, minibatchData.[labelStreamInfo]
]
|> dict
trainer.TrainMinibatch(arguments, device) |> ignore
report step |> printer
// MinibatchSource is created with MinibatchSource.InfinitelyRepeat.
// Batching will not end. Each time minibatchSource completes an sweep (epoch),
// the last minibatch data will be marked as end of a sweep. We use this flag
// to count number of epochs.
let epoch =
if (MiniBatchDataIsSweepEnd(minibatchData.Values))
then epoch - 1
else epoch
learnEpoch (step,epoch)
learnEpoch (0,epochs)
let epochs = 10
learn epochs
classifierOutput.Function.Save(modelFile)
// validate the model
let minibatchSourceNewModel =
MinibatchSource.TextFormatMinibatchSource(
Path.Combine(ImageDataFolder, "Test_cntk_text.txt"),
streamConfigurations,
MinibatchSource.FullDataSweep)
let ValidateModelWithMinibatchSource(
modelFile:string,
testMinibatchSource:MinibatchSource,
imageDim:int[],
numClasses:int,
featureInputName:string,
labelInputName:string,
outputName:string,
device:DeviceDescriptor,
maxCount:int
) =
let model : Function = Function.Load(modelFile, device)
let imageInput = model.Arguments.[0]
let labelOutput =
model.Outputs
|> Seq.filter (fun o -> o.Name = outputName)
|> Seq.exactlyOne
let featureStreamInfo = testMinibatchSource.StreamInfo(featureInputName)
let labelStreamInfo = testMinibatchSource.StreamInfo(labelInputName)
let batchSize = 50
let rec countErrors (total,errors) =
printfn "Total: %i; Errors: %i" total errors
let minibatchData = testMinibatchSource.GetNextMinibatch((uint32)batchSize, device)
if (minibatchData = null || minibatchData.Count = 0)
then (total,errors)
else
let total = total + minibatchData.[featureStreamInfo].numberOfSamples
// find the index of the largest label value
let labelData = minibatchData.[labelStreamInfo].data.GetDenseData<float32>(labelOutput)
let expectedLabels =
labelData
|> Seq.map (fun l ->
let largest = l |> Seq.max
l.IndexOf largest
)
let inputDataMap =
[
imageInput, minibatchData.[featureStreamInfo].data
]
|> dataMap
let outputDataMap =
[
labelOutput, null
]
|> dataMap
model.Evaluate(inputDataMap, outputDataMap, device)
let outputData = outputDataMap.[labelOutput].GetDenseData<float32>(labelOutput)
let actualLabels =
outputData
|> Seq.map (fun l ->
let largest = l |> Seq.max
l.IndexOf largest
)
let misMatches =
(actualLabels,expectedLabels)
||> Seq.zip
|> Seq.sumBy (fun (a, b) -> if a = b then 0 else 1)
let errors = errors + misMatches
if (int total > maxCount)
then (total,errors)
else countErrors (total,errors)
countErrors (uint32 0,0)
let total,errors =
ValidateModelWithMinibatchSource(
modelFile,
minibatchSourceNewModel,
[|imageSize|],
numClasses,
featureStreamName,
labelsStreamName,
classifierName,
device,
1000)
printfn "Total: %i / Errors: %i" total errors