Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion csharp/events/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public void Search(string directory, string searchPattern, bool searchSubDirs =
{
directoryChanged?.Invoke(this,
new SearchDirectoryArgs(dir, totalDirs, completedDirs++));
// Recursively search this child directory:
// Search 'dir' and its subdirectories for files that match the search pattern:
SearchDirectory(dir, searchPattern);
}
// Include the Current Directory:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.ML" Version="0.11.0" />
<PackageReference Include="Microsoft.ML.Recommender" Version="0.11.0" />
<PackageReference Include="Microsoft.ML" Version="1.0.0-preview" />
<PackageReference Include="Microsoft.ML.Recommender" Version="0.12.0-preview" />
</ItemGroup>

<ItemGroup>
Expand Down
15 changes: 6 additions & 9 deletions machine-learning/tutorials/MovieRecommendation/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
using System.IO;
using Microsoft.ML;
using Microsoft.ML.Trainers;
using Microsoft.ML.Data;
using Microsoft.Data.DataView;
// </SnippetUsingStatements>

namespace MovieRecommendation
Expand Down Expand Up @@ -43,7 +41,7 @@ static void Main(string[] args)

// Save model
// <SnippetSaveModelMain>
SaveModel(mlContext, model);
SaveModel(mlContext, trainingDataView.Schema, model);
// </SnippetSaveModelMain>
}

Expand Down Expand Up @@ -103,11 +101,11 @@ public static void EvaluateModel(MLContext mlContext, IDataView testDataView, IT
// </SnippetTransform>

// <SnippetEvaluate>
var metrics = mlContext.Regression.Evaluate(prediction, label: DefaultColumnNames.Label, score: DefaultColumnNames.Score);
var metrics = mlContext.Regression.Evaluate(prediction, labelColumnName: "Label", scoreColumnName: "Score");
// </SnippetEvaluate>

// <SnippetPrintMetrics>
Console.WriteLine("Rms: " + metrics.Rms.ToString());
Console.WriteLine("Root Mean Squared Error : " + metrics.RootMeanSquaredError.ToString());
Console.WriteLine("RSquared: " + metrics.RSquared.ToString());
// </SnippetPrintMetrics>
}
Expand All @@ -117,7 +115,7 @@ public static void UseModelForSinglePrediction(MLContext mlContext, ITransformer
{
// <SnippetPredictionEngine>
Console.WriteLine("=============== Making a prediction ===============");
var predictionEngine = model.CreatePredictionEngine<MovieRating, MovieRatingPrediction>(mlContext);
var predictionEngine = mlContext.Model.CreatePredictionEngine<MovieRating, MovieRatingPrediction>(model);
// </SnippetPredictionEngine>

// Create test input & make single prediction
Expand All @@ -140,15 +138,14 @@ public static void UseModelForSinglePrediction(MLContext mlContext, ITransformer
}

//Save model
public static void SaveModel(MLContext mlContext, ITransformer model)
public static void SaveModel(MLContext mlContext, DataViewSchema trainingDataViewSchema, ITransformer model)
{
// Save the trained model to .zip file
// <SnippetSaveModel>
var modelPath = Path.Combine(Environment.CurrentDirectory, "Data", "MovieRecommenderModel.zip");

Console.WriteLine("=============== Saving the model to a file ===============");
using (var fs = new FileStream(modelPath, FileMode.Create, FileAccess.Write, FileShare.Write))
mlContext.Model.Save(model, fs);
mlContext.Model.Save(model, trainingDataViewSchema, modelPath);
// </SnippetSaveModel>
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace TransferLearningTF
{
// <SnippetDeclareTypes>
public class ImagePrediction
public class ImagePrediction : ImageData
{
public float[] Score;

Expand Down
118 changes: 44 additions & 74 deletions machine-learning/tutorials/TransferLearningTF/Program.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
// <SnippetAddUsings>
// <SnippetAddUsings>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Data.DataView;
using Microsoft.ML;
using Microsoft.ML.Core.Data;
using Microsoft.ML.Data;
using Microsoft.ML.ImageAnalytics;
using Microsoft.ML.Data.IO;
using Microsoft.ML.Trainers;
using Microsoft.ML.Transforms.Image;
// </SnippetAddUsings>

namespace TransferLearningTF
Expand All @@ -26,27 +25,26 @@ class Program
static readonly string _inputImageClassifierZip = Path.Combine(_assetsPath, "inputs-predict", "imageClassifier.zip");
static readonly string _outputImageClassifierZip = Path.Combine(_assetsPath, "outputs", "imageClassifier.zip");
private static string LabelTokey = nameof(LabelTokey);
private static string ImageReal = nameof(ImageReal);
private static string PredictedLabelValue = nameof(PredictedLabelValue);
// </SnippetDeclareGlobalVariables>

static void Main(string[] args)
{
// Create MLContext to be shared across the model creation workflow objects
// <SnippetCreateMLContext>
MLContext mlContext = new MLContext(seed:1);
MLContext mlContext = new MLContext(seed: 1);
// </SnippetCreateMLContext>

// <SnippetCallReuseAndTuneInceptionModel>
ReuseAndTuneInceptionModel(mlContext, _trainTagsTsv, _trainImagesFolder, _inceptionPb, _outputImageClassifierZip);
var model = ReuseAndTuneInceptionModel(mlContext, _trainTagsTsv, _trainImagesFolder, _inceptionPb, _outputImageClassifierZip);
// </SnippetCallReuseAndTuneInceptionModel>

// <SnippetCallClassifyImages>
ClassifyImages(mlContext, _predictImageListTsv, _predictImagesFolder, _outputImageClassifierZip);
ClassifyImages(mlContext, _predictImageListTsv, _predictImagesFolder, _outputImageClassifierZip, model);
// </SnippetCallClassifyImages>

// <SnippetCallClassifySingleImage>
ClassifySingleImage(mlContext, _predictSingleImage, _outputImageClassifierZip);
ClassifySingleImage(mlContext, _predictSingleImage, _outputImageClassifierZip, model);
// </SnippetCallClassifySingleImage>
}

Expand All @@ -62,32 +60,34 @@ private struct InceptionSettings
// </SnippetInceptionSettings>

// Build and train model
public static void ReuseAndTuneInceptionModel(MLContext mlContext, string dataLocation, string imagesFolder, string inputModelLocation, string outputModelLocation)
public static ITransformer ReuseAndTuneInceptionModel(MLContext mlContext, string dataLocation, string imagesFolder, string inputModelLocation, string outputModelLocation)
{

// <SnippetLoadData>
var data = mlContext.Data.ReadFromTextFile<ImageData>(path: dataLocation, hasHeader: false);
var data = mlContext.Data.LoadFromTextFile<ImageData>(path: dataLocation, hasHeader: false);
// </SnippetLoadData>

// <SnippetMapValueToKey1>
var estimator = mlContext.Transforms.Conversion.MapValueToKey(outputColumnName: LabelTokey, inputColumnName: DefaultColumnNames.Label)
var estimator = mlContext.Transforms.Conversion.MapValueToKey(outputColumnName: LabelTokey, inputColumnName: "Label")
// </SnippetMapValueToKey1>
// The image transforms transform the images into the model's expected format.
// <SnippetImageTransforms>
.Append(mlContext.Transforms.LoadImages(_trainImagesFolder, (ImageReal, nameof(ImageData.ImagePath))))
.Append(mlContext.Transforms.Resize(outputColumnName: ImageReal, imageWidth: InceptionSettings.ImageWidth, imageHeight: InceptionSettings.ImageHeight, inputColumnName: ImageReal))
.Append(mlContext.Transforms.ExtractPixels(new ImagePixelExtractorTransformer.ColumnInfo(name: "input", inputColumnName: ImageReal, interleave: InceptionSettings.ChannelsLast, offset: InceptionSettings.Mean)))
.Append(mlContext.Transforms.LoadImages(outputColumnName: "input", imageFolder: _trainImagesFolder, inputColumnName: nameof(ImageData.ImagePath)))
.Append(mlContext.Transforms.ResizeImages(outputColumnName: "input", imageWidth: InceptionSettings.ImageWidth, imageHeight: InceptionSettings.ImageHeight, inputColumnName: "input"))
.Append(mlContext.Transforms.ExtractPixels(outputColumnName: "input", interleavePixelColors: InceptionSettings.ChannelsLast, offsetImage: InceptionSettings.Mean))
// </SnippetImageTransforms>
// The ScoreTensorFlowModel transform scores the TensorFlow model and allows communication
// <SnippetScoreTensorFlowModel>
.Append(mlContext.Transforms.ScoreTensorFlowModel(modelLocation: inputModelLocation, outputColumnNames: new[] { "softmax2_pre_activation" }, inputColumnNames: new[] { "input" }))
.Append(mlContext.Model.LoadTensorFlowModel(inputModelLocation).
ScoreTensorFlowModel(outputColumnNames: new[] { "softmax2_pre_activation" }, inputColumnNames: new[] { "input" }, addBatchDimensionInput: true))
// </SnippetScoreTensorFlowModel>
// <SnippetAddTrainer>
.Append(mlContext.MulticlassClassification.Trainers.LogisticRegression(labelColumn: LabelTokey, featureColumn: "softmax2_pre_activation"))
.Append(mlContext.MulticlassClassification.Trainers.LbfgsMaximumEntropy(labelColumnName: LabelTokey, featureColumnName: "softmax2_pre_activation"))
// </SnippetAddTrainer>
// <SnippetMapValueToKey2>
.Append(mlContext.Transforms.Conversion.MapKeyToValue((PredictedLabelValue, DefaultColumnNames.PredictedLabel)));
// </SnippetMapValueToKey2>
.Append(mlContext.Transforms.Conversion.MapKeyToValue(PredictedLabelValue, "PredictedLabel"))
.AppendCacheCheckpoint(mlContext);
// </SnippetMapValueToKey2>

// Train the model
Console.WriteLine("=============== Training classification model ===============");
Expand All @@ -105,92 +105,67 @@ public static void ReuseAndTuneInceptionModel(MLContext mlContext, string dataLo
// Create enumerables for both the ImageData and ImagePrediction DataViews
// for displaying results
// <SnippetEnumerateDataViews>
var imageData = mlContext.CreateEnumerable<ImageData>(data, false, true);
var imagePredictionData = mlContext.CreateEnumerable<ImagePrediction>(predictions, false, true);
var imageData = mlContext.Data.CreateEnumerable<ImageData>(data, false, true);
var imagePredictionData = mlContext.Data.CreateEnumerable<ImagePrediction>(predictions, false, true);
// </SnippetEnumerateDataViews>

// Read the tags.tsv file and add the filepath to the image file name
// before loading into ImageData
// <SnippetCallPairAndDisplayResults1>
PairAndDisplayResults(imageData, imagePredictionData);
// </SnippetCallPairAndDisplayResults1>
// <SnippetCallDisplayResults1>
DisplayResults(imagePredictionData);
// </SnippetCallDisplayResults1>

// Get some performance metrics on the model using training data
Console.WriteLine("=============== Classification metrics ===============");

// <SnippetEvaluate>
var regressionContext = new MulticlassClassificationCatalog(mlContext);
var metrics = regressionContext.Evaluate(predictions, label: LabelTokey, predictedLabel: DefaultColumnNames.PredictedLabel);
var multiclassContext = mlContext.MulticlassClassification;
var metrics = multiclassContext.Evaluate(predictions, labelColumnName: LabelTokey, predictedLabelColumnName: "PredictedLabel");
// </SnippetEvaluate>

//<SnippetDisplayMetrics>
Console.WriteLine($"LogLoss is: {metrics.LogLoss}");
Console.WriteLine($"PerClassLogLoss is: {String.Join(" , ", metrics.PerClassLogLoss.Select(c => c.ToString()))}");
//</SnippetDisplayMetrics>

// Save the model to assets/outputs
Console.WriteLine("=============== Save model to local file ===============");

// <SnippetSaveModel>
using (var fileStream = new FileStream(outputModelLocation, FileMode.Create))
mlContext.Model.Save(model, fileStream);
// </SnippetSaveModel>

Console.WriteLine($"Model saved: {outputModelLocation}");
// <SnippetReturnModel>
return model;
// </SnippetReturnModel>
}

public static void ClassifyImages(MLContext mlContext, string dataLocation, string imagesFolder, string outputModelLocation)
public static void ClassifyImages(MLContext mlContext, string dataLocation, string imagesFolder, string outputModelLocation, ITransformer model)
{
Console.WriteLine($"=============== Loading model ===============");
Console.WriteLine($"Model loaded: {outputModelLocation}");
// Load the model
// <SnippetLoadModel>
ITransformer loadedModel;
using (var fileStream = new FileStream(outputModelLocation, FileMode.Open))
loadedModel = mlContext.Model.Load(fileStream);
// </SnippetLoadModel>

// Read the image_list.tsv file and add the filepath to the image file name
// before loading into ImageData
// <SnippetReadFromTSV>
var imageData = ReadFromTsv(dataLocation, imagesFolder);
var imageDataView = mlContext.Data.ReadFromEnumerable<ImageData>(imageData);
var imageDataView = mlContext.Data.LoadFromEnumerable<ImageData>(imageData);
// </SnippetReadFromTSV>

// <SnippetPredict>
var predictions = loadedModel.Transform(imageDataView);
var imagePredictionData = mlContext.CreateEnumerable<ImagePrediction>(predictions, false,true);
var predictions = model.Transform(imageDataView);
var imagePredictionData = mlContext.Data.CreateEnumerable<ImagePrediction>(predictions, false, true);
// </SnippetPredict>

Console.WriteLine("=============== Making classifications ===============");
// <SnippetCallPairAndDisplayResults2>
PairAndDisplayResults(imageData, imagePredictionData);
// </SnippetCallPairAndDisplayResults2>

// <SnippetCallDisplayResults2>
DisplayResults(imagePredictionData);
// </SnippetCallDisplayResults2>
}

public static void ClassifySingleImage(MLContext mlContext, string imagePath, string outputModelLocation)
public static void ClassifySingleImage(MLContext mlContext, string imagePath, string outputModelLocation, ITransformer model)
{
Console.WriteLine($"=============== Loading model ===============");
Console.WriteLine($"Model loaded: {outputModelLocation}");
// Load the model
// <SnippetLoadModel2>
ITransformer loadedModel;
using (var fileStream = new FileStream(outputModelLocation, FileMode.Open))
loadedModel = mlContext.Model.Load(fileStream);
// </SnippetLoadModel2>

// load the fully qualified image file name into ImageData
// <SnippetLoadImageData>
var imageData = new ImageData()
{
ImagePath = imagePath
};
};
// </SnippetLoadImageData>

// <SnippetPredictSingle>
// Make prediction function (input = ImageNetData, output = ImageNetPrediction)
var predictor = loadedModel.CreatePredictionEngine<ImageData, ImagePrediction>(mlContext);
// Make prediction function (input = ImageData, output = ImagePrediction)
var predictor = mlContext.Model.CreatePredictionEngine<ImageData, ImagePrediction>(model);
var prediction = predictor.Predict(imageData);
// </SnippetPredictSingle>

Expand All @@ -201,17 +176,12 @@ public static void ClassifySingleImage(MLContext mlContext, string imagePath, st

}

private static void PairAndDisplayResults(IEnumerable<ImageData> imageNetData, IEnumerable<ImagePrediction> imageNetPredictionData)
private static void DisplayResults(IEnumerable<ImagePrediction> imagePredictionData)
{
// Builds pairs of (image, prediction) to sync up for display
// <SnippetBuildImagePredictionPairs>
IEnumerable<(ImageData image, ImagePrediction prediction)> imagesAndPredictions = imageNetData.Zip(imageNetPredictionData, (image, prediction) => (image, prediction));
// </SnippetBuildImagePredictionPairs>

// <SnippetDisplayPredictions>
foreach ((ImageData image, ImagePrediction prediction) item in imagesAndPredictions)
foreach (ImagePrediction prediction in imagePredictionData)
{
Console.WriteLine($"Image: {Path.GetFileName(item.image.ImagePath)} predicted as: {item.prediction.PredictedLabelValue} with score: {item.prediction.Score.Max()} ");
Console.WriteLine($"Image: {Path.GetFileName(prediction.ImagePath)} predicted as: {prediction.PredictedLabelValue} with score: {prediction.Score.Max()} ");
}
// </SnippetDisplayPredictions>
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
Expand All @@ -7,9 +7,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.ML" Version="0.10.0" />
<PackageReference Include="Microsoft.ML.ImageAnalytics" Version="0.10.0" />
<PackageReference Include="Microsoft.ML.TensorFlow" Version="0.10.0" />
<PackageReference Include="Microsoft.ML" Version="1.0.0-preview" />
<PackageReference Include="Microsoft.ML.ImageAnalytics" Version="1.0.0-preview" />
<PackageReference Include="Microsoft.ML.TensorFlow" Version="0.12.0-preview" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ public class Form1 : System.Windows.Forms.Form
private System.Windows.Forms.Button button2;
private System.Windows.Forms.ListBox listBox1;
private System.Windows.Forms.Button button3;
private System.ComponentModel.Container components;
private System.ComponentModel.Container components;

public Form1()
{
InitializeComponent();
InitializeComponent();

// Sets up the initial objects in the CheckedListBox.
string[] myFruit = {"Apples", "Oranges","Tomato"};
string[] myFruit = {"Apples", "Oranges","Tomato"};
checkedListBox1.Items.AddRange(myFruit);

// Changes the selection mode from double-click to single click.
// Changes the selection mode from double-click to single click.
checkedListBox1.CheckOnClick = true;
}

Expand Down
Loading