-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathLearningRateSchedulingCifarResnetTransferLearning.cs
More file actions
390 lines (322 loc) · 14.8 KB
/
LearningRateSchedulingCifarResnetTransferLearning.cs
File metadata and controls
390 lines (322 loc) · 14.8 KB
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.Trainers;
using Microsoft.ML.Vision;
namespace Samples.Dynamic
{
public class LearningRateSchedulingCifarResnetTransferLearning
{
public static void Example()
{
// Set the path for input images.
string assetsRelativePath = @"../../../assets";
string assetsPath = GetAbsolutePath(assetsRelativePath);
string imagesDownloadFolderPath = Path.Combine(assetsPath, "inputs",
"images");
// Download Cifar Dataset and set train and test dataset
// paths.
string finalImagesFolderName = DownloadImageSet(
imagesDownloadFolderPath);
string finalImagesFolderNameTrain = "cifar\\train";
string fullImagesetFolderPathTrain = Path.Combine(
imagesDownloadFolderPath, finalImagesFolderNameTrain);
string finalImagesFolderNameTest = "cifar\\test";
string fullImagesetFolderPathTest = Path.Combine(
imagesDownloadFolderPath, finalImagesFolderNameTest);
MLContext mlContext = new MLContext(seed: 1);
//Load all the original train images info.
IEnumerable<ImageData> train_images = LoadImagesFromDirectory(
folder: fullImagesetFolderPathTrain, useFolderNameAsLabel: true);
IDataView trainDataset = mlContext.Data.
LoadFromEnumerable(train_images);
// Apply transforms to the input dataset:
// MapValueToKey : map 'string' type labels to keys
// LoadImages : load raw images to "Image" column
trainDataset = mlContext.Transforms.Conversion
.MapValueToKey("Label", keyOrdinality: Microsoft.ML.Transforms
.ValueToKeyMappingEstimator.KeyOrdinality.ByValue)
.Append(mlContext.Transforms.LoadRawImageBytes("Image",
fullImagesetFolderPathTrain, "ImagePath"))
.Fit(trainDataset)
.Transform(trainDataset);
// Load all the original test images info and apply
// the same transforms as above.
IEnumerable<ImageData> test_images = LoadImagesFromDirectory(
folder: fullImagesetFolderPathTest, useFolderNameAsLabel: true);
IDataView testDataset = mlContext.Data.
LoadFromEnumerable(test_images);
testDataset = mlContext.Transforms.Conversion
.MapValueToKey("Label", keyOrdinality: Microsoft.ML.Transforms
.ValueToKeyMappingEstimator.KeyOrdinality.ByValue)
.Append(mlContext.Transforms.LoadRawImageBytes("Image",
fullImagesetFolderPathTest, "ImagePath"))
.Fit(testDataset)
.Transform(testDataset);
// Set the options for ImageClassification.
var options = new ImageClassificationTrainer.Options()
{
FeatureColumnName = "Image",
LabelColumnName = "Label",
// Just by changing/selecting InceptionV3/MobilenetV2
// here instead of
// ResnetV2101 you can try a different architecture/
// pre-trained model.
Arch = ImageClassificationTrainer.Architecture.ResnetV2101,
Epoch = 182,
BatchSize = 128,
LearningRate = 0.01f,
MetricsCallback = (metrics) => Console.WriteLine(metrics),
ValidationSet = testDataset,
ReuseValidationSetBottleneckCachedValues = false,
ReuseTrainSetBottleneckCachedValues = false,
// Use linear scaling rule and Learning rate decay as an option
// This is known to do well for Cifar dataset and Resnet models
// You can also try other types of Learning rate scheduling
// methods available in LearningRateScheduler.cs
LearningRateScheduler = new LsrDecay()
};
// Create the ImageClassification pipeline.
var pipeline = mlContext.MulticlassClassification.Trainers.
ImageClassification(options)
.Append(mlContext.Transforms.Conversion.MapKeyToValue(
outputColumnName: "PredictedLabel",
inputColumnName: "PredictedLabel"));
Console.WriteLine("*** Training the image classification model " +
"with DNN Transfer Learning on top of the selected " +
"pre-trained model/architecture ***");
// Train the model.
// This involves calculating the bottleneck values, and then
// training the final layer. Sample output is:
// Phase: Bottleneck Computation, Dataset used: Train, Image Index: 1
// Phase: Bottleneck Computation, Dataset used: Train, Image Index: 2
// ...
// Phase: Training, Dataset used: Train, Batch Processed Count: 18, Learning Rate: 0.01 Epoch: 0, Accuracy: 0.9166667,Cross-Entropy: 0.4866541
// ...
var trainedModel = pipeline.Fit(trainDataset);
Console.WriteLine("Training with transfer learning finished.");
// Save the trained model.
mlContext.Model.Save(trainedModel, testDataset.Schema,
"model.zip");
// Load the trained and saved model for prediction.
ITransformer loadedModel;
DataViewSchema schema;
using (var file = File.OpenRead("model.zip"))
loadedModel = mlContext.Model.Load(file, out schema);
// Evaluate the model on the test dataset.
// Sample output:
// Making bulk predictions and evaluating model's quality...
// Micro - accuracy: ...,macro - accuracy = ...
EvaluateModel(mlContext, testDataset, loadedModel);
// Predict image class using a single in-memory image.
TrySinglePrediction(fullImagesetFolderPathTest, mlContext,
loadedModel);
Console.WriteLine("Prediction on a single image finished.");
Console.WriteLine("Press any key to finish");
Console.ReadKey();
}
// Predict on a single image.
private static void TrySinglePrediction(string imagesForPredictions,
MLContext mlContext, ITransformer trainedModel)
{
// Create prediction function to try one prediction.
var predictionEngine = mlContext.Model
.CreatePredictionEngine<InMemoryImageData,
ImagePrediction>(trainedModel);
// Load test images.
IEnumerable<InMemoryImageData> testImages =
LoadInMemoryImagesFromDirectory(imagesForPredictions, false);
// Create an in-memory image object from the first image in the test data.
InMemoryImageData imageToPredict = new InMemoryImageData
{
Image = testImages.First().Image
};
// Predict on the single image.
var prediction = predictionEngine.Predict(imageToPredict);
Console.WriteLine($"Scores : [{string.Join(",", prediction.Score)}], " +
$"Predicted Label : {prediction.PredictedLabel}");
}
// Evaluate the trained model on the passed test dataset.
private static void EvaluateModel(MLContext mlContext,
IDataView testDataset, ITransformer trainedModel)
{
Console.WriteLine("Making bulk predictions and evaluating model's " +
"quality...");
// Evaluate the model on the test data and get the evaluation metrics.
IDataView predictions = trainedModel.Transform(testDataset);
var metrics = mlContext.MulticlassClassification.Evaluate(predictions);
Console.WriteLine($"Micro-accuracy: {metrics.MicroAccuracy}," +
$"macro-accuracy = {metrics.MacroAccuracy}");
Console.WriteLine("Predicting and Evaluation complete.");
}
//Load the Image Data from input directory.
public static IEnumerable<ImageData> LoadImagesFromDirectory(string folder,
bool useFolderNameAsLabel = true)
{
var files = Directory.GetFiles(folder, "*",
searchOption: SearchOption.AllDirectories);
foreach (var file in files)
{
if (Path.GetExtension(file) != ".jpg" &&
Path.GetExtension(file) != ".JPEG" &&
Path.GetExtension(file) != ".png")
continue;
var label = Path.GetFileName(file);
if (useFolderNameAsLabel)
label = Directory.GetParent(file).Name;
else
{
for (int index = 0; index < label.Length; index++)
{
if (!char.IsLetter(label[index]))
{
label = label.Substring(0, index);
break;
}
}
}
yield return new ImageData()
{
ImagePath = file,
Label = label
};
}
}
// Load In memory raw images from directory.
public static IEnumerable<InMemoryImageData>
LoadInMemoryImagesFromDirectory(string folder,
bool useFolderNameAsLabel = true)
{
var files = Directory.GetFiles(folder, "*",
searchOption: SearchOption.AllDirectories);
foreach (var file in files)
{
if (Path.GetExtension(file) != ".jpg" &&
Path.GetExtension(file) != ".JPEG" &&
Path.GetExtension(file) != ".png")
continue;
var label = Path.GetFileName(file);
if (useFolderNameAsLabel)
label = Directory.GetParent(file).Name;
else
{
for (int index = 0; index < label.Length; index++)
{
if (!char.IsLetter(label[index]))
{
label = label.Substring(0, index);
break;
}
}
}
yield return new InMemoryImageData()
{
Image = File.ReadAllBytes(file),
Label = label
};
}
}
// Download and unzip the image dataset.
public static string DownloadImageSet(string imagesDownloadFolder)
{
// get a set of images to teach the network about the new classes
// CIFAR dataset ( 50000 train images and 10000 test images )
string fileName = "cifar10.zip";
// https://github.com/YoongiKim/CIFAR-10-images
string url = $"https://github.com/YoongiKim/CIFAR-10-images/archive/refs/heads/master.zip";
Download(url, imagesDownloadFolder, fileName).Wait();
UnZip(Path.Combine(imagesDownloadFolder, fileName),
imagesDownloadFolder);
return Path.GetFileNameWithoutExtension(fileName);
}
// Download file to destination directory from input URL.
public static async Task<bool> Download(string url, string destDir, string destFileName)
{
if (destFileName == null)
destFileName = url.Split(Path.DirectorySeparatorChar).Last();
Directory.CreateDirectory(destDir);
string relativeFilePath = Path.Combine(destDir, destFileName);
if (File.Exists(relativeFilePath))
{
Console.WriteLine($"{relativeFilePath} already exists.");
return false;
}
Console.WriteLine($"Downloading {relativeFilePath}");
using (HttpClient client = new HttpClient())
{
var response = await client.GetStreamAsync(new Uri($"{url}")).ConfigureAwait(false);
using (var fs = new FileStream(relativeFilePath, FileMode.CreateNew))
{
await response.CopyToAsync(fs);
}
}
Console.WriteLine("");
Console.WriteLine($"Downloaded {relativeFilePath}");
return true;
}
// Unzip the file to destination folder.
public static void UnZip(String gzArchiveName, String destFolder)
{
var flag = gzArchiveName.Split(Path.DirectorySeparatorChar)
.Last()
.Split('.')
.First() + ".bin";
if (File.Exists(Path.Combine(destFolder, flag))) return;
Console.WriteLine($"Extracting.");
var task = Task.Run(() =>
{
ZipFile.ExtractToDirectory(gzArchiveName, destFolder);
});
while (!task.IsCompleted)
{
Thread.Sleep(200);
Console.Write(".");
}
File.Create(Path.Combine(destFolder, flag));
Console.WriteLine("");
Console.WriteLine("Extracting is completed.");
}
// Get absolute path from relative path.
public static string GetAbsolutePath(string relativePath)
{
FileInfo _dataRoot = new FileInfo(typeof(
LearningRateSchedulingCifarResnetTransferLearning).Assembly.Location);
string assemblyFolderPath = _dataRoot.Directory.FullName;
string fullPath = Path.Combine(assemblyFolderPath, relativePath);
return fullPath;
}
// InMemoryImageData class holding the raw image byte array and label.
public class InMemoryImageData
{
[LoadColumn(0)]
public byte[] Image;
[LoadColumn(1)]
public string Label;
}
// ImageData class holding the imagepath and label.
public class ImageData
{
[LoadColumn(0)]
public string ImagePath;
[LoadColumn(1)]
public string Label;
}
// ImagePrediction class holding the score and predicted label metrics.
public class ImagePrediction
{
[ColumnName("Score")]
public float[] Score;
[ColumnName("PredictedLabel")]
public string PredictedLabel;
}
}
}