Skip to content

Commit 3c38284

Browse files
TensorFlow Featurizer sample updated InceptionV3 (dotnet#624)
1 parent 125d05a commit 3c38284

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+1375
-238
lines changed

samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Predict/ImageClassification.Predict.csproj

+6-4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@
66
<LangVersion>7.2</LangVersion>
77
</PropertyGroup>
88

9+
<ItemGroup>
10+
<Compile Remove="assets\outputs\**" />
11+
<EmbeddedResource Remove="assets\outputs\**" />
12+
<None Remove="assets\outputs\**" />
13+
</ItemGroup>
14+
915
<ItemGroup>
1016
<Compile Include="..\ImageClassification.Train\ImageData\ImagePrediction.cs" Link="ImageData\ImagePrediction.cs" />
1117
<Compile Include="..\ImageClassification.Train\Model\ConsoleHelpers.cs" Link="Model\ConsoleHelpers.cs" />
@@ -18,8 +24,4 @@
1824
<PackageReference Include="Microsoft.ML.TensorFlow" Version="$(MicrosoftMLVersion)" />
1925
</ItemGroup>
2026

21-
<ItemGroup>
22-
<Folder Include="assets\outputs\" />
23-
</ItemGroup>
24-
2527
</Project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using Microsoft.ML.Data;
2+
using System;
3+
using System.Collections.Generic;
4+
using System.IO;
5+
using System.Linq;
6+
7+
namespace ImageClassification.DataModels
8+
{
9+
public class ImageData
10+
{
11+
[LoadColumn(0)]
12+
public string ImagePath;
13+
14+
[LoadColumn(1)]
15+
public string Label;
16+
}
17+
18+
}

samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Predict/ImageData/ImageDataForScoring.cs

-28
This file was deleted.

samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Predict/Model/ModelScorer.cs

+76-18
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,19 @@
44
using System.IO;
55
using Microsoft.ML;
66
using static ImageClassification.Model.ConsoleHelpers;
7+
using System.Collections.Generic;
8+
using Microsoft.ML.Data;
79

810
namespace ImageClassification.Model
911
{
1012
public class ModelScorer
1113
{
12-
private readonly string dataLocation;
1314
private readonly string imagesFolder;
1415
private readonly string modelLocation;
1516
private readonly MLContext mlContext;
1617

17-
public ModelScorer(string dataLocation, string imagesFolder, string modelLocation)
18+
public ModelScorer(string imagesFolder, string modelLocation)
1819
{
19-
this.dataLocation = dataLocation;
2020
this.imagesFolder = imagesFolder;
2121
this.modelLocation = modelLocation;
2222
mlContext = new MLContext(seed: 1);
@@ -25,26 +25,84 @@ public ModelScorer(string dataLocation, string imagesFolder, string modelLocatio
2525
public void ClassifyImages()
2626
{
2727
ConsoleWriteHeader("Loading model");
28+
Console.WriteLine("");
2829
Console.WriteLine($"Model loaded: {modelLocation}");
2930

3031
// Load the model
3132
ITransformer loadedModel = mlContext.Model.Load(modelLocation,out var modelInputSchema);
3233

33-
// Make prediction function (input = ImageNetData, output = ImageNetPrediction)
34-
var predictor = mlContext.Model.CreatePredictionEngine<ImageDataForScoring, ImagePrediction>(loadedModel);
35-
// Read csv file into List<ImageNetData>
36-
var imageListToPredict = ImageDataForScoring.ReadFromCsv(dataLocation, imagesFolder).ToList();
37-
38-
ConsoleWriteHeader("Making classifications");
39-
// There is a bug (https://github.com/dotnet/machinelearning/issues/1138),
40-
// that always buffers the response from the predictor
41-
// so we have to make a copy-by-value op everytime we get a response
42-
// from the predictor
43-
imageListToPredict
44-
.Select(td => new { td, pred = predictor.Predict(td) })
45-
.Select(pr => (pr.td.ImageFileName, pr.pred.PredictedLabelValue, pr.pred.Score))
46-
.ToList()
47-
.ForEach(pr => ConsoleWriteImagePrediction(pr.ImageFileName, pr.PredictedLabelValue, pr.Score.Max()));
34+
// Make prediction engine (input = ImageDataForScoring, output = ImagePrediction)
35+
var predictionEngine = mlContext.Model.CreatePredictionEngine<ImageData, ImagePrediction>(loadedModel);
36+
37+
IEnumerable<ImageData> imagesToPredict = LoadImagesFromDirectory(imagesFolder, true);
38+
39+
ConsoleWriteHeader("Predicting classifications...");
40+
41+
//Predict the first image in the folder
42+
//
43+
ImageData imageToPredict = new ImageData
44+
{
45+
ImagePath = imagesToPredict.First().ImagePath
46+
};
47+
48+
var prediction = predictionEngine.Predict(imageToPredict);
49+
50+
Console.WriteLine("");
51+
Console.WriteLine($"ImageFile : [{Path.GetFileName(imageToPredict.ImagePath)}], " +
52+
$"Scores : [{string.Join(",", prediction.Score)}], " +
53+
$"Predicted Label : {prediction.PredictedLabelValue}");
54+
55+
//////
56+
57+
//Predict all images in the folder
58+
//
59+
Console.WriteLine("");
60+
Console.WriteLine("Predicting several images...");
61+
62+
foreach (ImageData currentImageToPredict in imagesToPredict)
63+
{
64+
var currentPrediction = predictionEngine.Predict(currentImageToPredict);
65+
Console.WriteLine("");
66+
Console.WriteLine($"ImageFile : [{Path.GetFileName(currentImageToPredict.ImagePath)}], " +
67+
$"Scores : [{string.Join(",", currentPrediction.Score)}], " +
68+
$"Predicted Label : {currentPrediction.PredictedLabelValue}");
69+
}
70+
//////
71+
72+
}
73+
74+
public static IEnumerable<ImageData> LoadImagesFromDirectory(string folder, bool useFolderNameasLabel = true)
75+
{
76+
var files = Directory.GetFiles(folder, "*",
77+
searchOption: SearchOption.AllDirectories);
78+
79+
foreach (var file in files)
80+
{
81+
if ((Path.GetExtension(file) != ".jpg") && (Path.GetExtension(file) != ".png"))
82+
continue;
83+
84+
var label = Path.GetFileName(file);
85+
if (useFolderNameasLabel)
86+
label = Directory.GetParent(file).Name;
87+
else
88+
{
89+
for (int index = 0; index < label.Length; index++)
90+
{
91+
if (!char.IsLetter(label[index]))
92+
{
93+
label = label.Substring(0, index);
94+
break;
95+
}
96+
}
97+
}
98+
99+
yield return new ImageData()
100+
{
101+
ImagePath = file,
102+
Label = label
103+
};
104+
105+
}
48106
}
49107
}
50108
}

samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Predict/Program.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,13 @@ static void Main(string[] args)
1313
string assetsRelativePath = @"../../../assets";
1414
string assetsPath = GetAbsolutePath(assetsRelativePath);
1515

16-
var tagsTsv = Path.Combine(assetsPath, "inputs", "data", "images_list.tsv");
17-
var imagesFolder = Path.Combine(assetsPath, "inputs", "data");
18-
var imageClassifierZip = Path.Combine(assetsPath, "inputs", "imageClassifier.zip");
16+
17+
var imagesFolder = Path.Combine(assetsPath, "inputs", "images-for-predictions");
18+
var imageClassifierZip = Path.Combine(assetsPath, "inputs", "MLNETModel", "imageClassifier.zip");
1919

2020
try
2121
{
22-
var modelScorer = new ModelScorer(tagsTsv, imagesFolder, imageClassifierZip);
22+
var modelScorer = new ModelScorer(imagesFolder, imageClassifierZip);
2323
modelScorer.ClassifyImages();
2424
}
2525
catch (Exception ex)

samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Predict/assets/inputs/data/images_list.tsv

-4
This file was deleted.

samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Predict/assets/inputs/data/wikimedia.md

-4
This file was deleted.

samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Train/ImageClassification.Train.csproj

+3
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,16 @@
88
</PropertyGroup>
99

1010
<ItemGroup>
11+
<Compile Include="..\..\..\common\Compress.cs" Link="Common\Compress.cs" />
1112
<Compile Include="..\..\..\common\ConsoleHelper.cs" Link="Common\ConsoleHelper.cs" />
13+
<Compile Include="..\..\..\common\Web.cs" Link="Common\Web.cs" />
1214
</ItemGroup>
1315

1416
<ItemGroup>
1517
<PackageReference Include="Microsoft.ML" Version="$(MicrosoftMLVersion)" />
1618
<PackageReference Include="Microsoft.ML.ImageAnalytics" Version="$(MicrosoftMLVersion)" />
1719
<PackageReference Include="Microsoft.ML.TensorFlow" Version="$(MicrosoftMLVersion)" />
20+
<PackageReference Include="SharpZipLib" Version="1.2.0" />
1821
</ItemGroup>
1922

2023
<ItemGroup>

samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Train/ImageData/ImageData.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ namespace ImageClassification.DataModels
99
public class ImageData
1010
{
1111
[LoadColumn(0)]
12-
public string ImageFileName;
12+
public string ImagePath;
1313

1414
[LoadColumn(1)]
1515
public string Label;

samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Train/ImageData/ImageDataProbability.cs

-30
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using Microsoft.ML.Data;
2+
using System;
3+
using System.Collections.Generic;
4+
using System.Text;
5+
6+
namespace ImageClassification.DataModels
7+
{
8+
public class ImagePredictionEx
9+
{
10+
public string ImagePath;
11+
public string Label;
12+
public string PredictedLabelValue;
13+
public float[] Score;
14+
15+
//[ColumnName("InceptionV3/Predictions/Reshape")]
16+
//public float[] ImageFeatures; //In Inception v1: "softmax2_pre_activation"
17+
}
18+
}

samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Train/ImageData/ImageWithPipelineFeatures.cs

-15
This file was deleted.

samples/csharp/getting-started/DeepLearning_TensorFlowEstimator/ImageClassification.Train/Model/ConsoleHelpers.cs

+5-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public static void ConsoleWriteException(params string[] lines)
4444
}
4545
}
4646

47-
public static void ConsoleWriteImagePrediction(string ImagePath, string PredictedLabel, float Probability)
47+
public static void ConsoleWriteImagePrediction(string ImagePath, string Label, string PredictedLabel, float Probability)
4848
{
4949
var defaultForeground = Console.ForegroundColor;
5050
var labelColor = ConsoleColor.Magenta;
@@ -54,6 +54,10 @@ public static void ConsoleWriteImagePrediction(string ImagePath, string Predicte
5454
Console.ForegroundColor = labelColor;
5555
Console.Write($"{Path.GetFileName(ImagePath)}");
5656
Console.ForegroundColor = defaultForeground;
57+
Console.Write(" original labeled as ");
58+
Console.ForegroundColor = labelColor;
59+
Console.Write(Label);
60+
Console.ForegroundColor = defaultForeground;
5761
Console.Write(" predicted as ");
5862
Console.ForegroundColor = labelColor;
5963
Console.Write(PredictedLabel);

0 commit comments

Comments
 (0)