diff --git a/csharp/events/Program.cs b/csharp/events/Program.cs index a5cc3ddb071..aa543053885 100644 --- a/csharp/events/Program.cs +++ b/csharp/events/Program.cs @@ -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: diff --git a/machine-learning/tutorials/MovieRecommendation/MovieRecommendation.csproj b/machine-learning/tutorials/MovieRecommendation/MovieRecommendation.csproj index b36a9215122..f94715fcb43 100644 --- a/machine-learning/tutorials/MovieRecommendation/MovieRecommendation.csproj +++ b/machine-learning/tutorials/MovieRecommendation/MovieRecommendation.csproj @@ -6,8 +6,8 @@ - - + + diff --git a/machine-learning/tutorials/MovieRecommendation/Program.cs b/machine-learning/tutorials/MovieRecommendation/Program.cs index db881d1b706..85ec2fba969 100644 --- a/machine-learning/tutorials/MovieRecommendation/Program.cs +++ b/machine-learning/tutorials/MovieRecommendation/Program.cs @@ -3,8 +3,6 @@ using System.IO; using Microsoft.ML; using Microsoft.ML.Trainers; -using Microsoft.ML.Data; -using Microsoft.Data.DataView; // namespace MovieRecommendation @@ -43,7 +41,7 @@ static void Main(string[] args) // Save model // - SaveModel(mlContext, model); + SaveModel(mlContext, trainingDataView.Schema, model); // } @@ -103,11 +101,11 @@ public static void EvaluateModel(MLContext mlContext, IDataView testDataView, IT // // - var metrics = mlContext.Regression.Evaluate(prediction, label: DefaultColumnNames.Label, score: DefaultColumnNames.Score); + var metrics = mlContext.Regression.Evaluate(prediction, labelColumnName: "Label", scoreColumnName: "Score"); // // - Console.WriteLine("Rms: " + metrics.Rms.ToString()); + Console.WriteLine("Root Mean Squared Error : " + metrics.RootMeanSquaredError.ToString()); Console.WriteLine("RSquared: " + metrics.RSquared.ToString()); // } @@ -117,7 +115,7 @@ public static void UseModelForSinglePrediction(MLContext mlContext, ITransformer { // Console.WriteLine("=============== Making a prediction ==============="); - var predictionEngine = model.CreatePredictionEngine(mlContext); + var predictionEngine = mlContext.Model.CreatePredictionEngine(model); // // Create test input & make single prediction @@ -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 // 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); // } diff --git a/machine-learning/tutorials/TransferLearningTF/ImagePrediction.cs b/machine-learning/tutorials/TransferLearningTF/ImagePrediction.cs index 5e203f59e63..4c992de4921 100644 --- a/machine-learning/tutorials/TransferLearningTF/ImagePrediction.cs +++ b/machine-learning/tutorials/TransferLearningTF/ImagePrediction.cs @@ -3,7 +3,7 @@ namespace TransferLearningTF { // - public class ImagePrediction + public class ImagePrediction : ImageData { public float[] Score; diff --git a/machine-learning/tutorials/TransferLearningTF/Program.cs b/machine-learning/tutorials/TransferLearningTF/Program.cs index fee30153aae..e610c23772b 100644 --- a/machine-learning/tutorials/TransferLearningTF/Program.cs +++ b/machine-learning/tutorials/TransferLearningTF/Program.cs @@ -1,14 +1,13 @@ -// +// 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; // namespace TransferLearningTF @@ -26,7 +25,6 @@ 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); // @@ -34,19 +32,19 @@ static void Main(string[] args) { // Create MLContext to be shared across the model creation workflow objects // - MLContext mlContext = new MLContext(seed:1); + MLContext mlContext = new MLContext(seed: 1); // // - ReuseAndTuneInceptionModel(mlContext, _trainTagsTsv, _trainImagesFolder, _inceptionPb, _outputImageClassifierZip); + var model = ReuseAndTuneInceptionModel(mlContext, _trainTagsTsv, _trainImagesFolder, _inceptionPb, _outputImageClassifierZip); // // - ClassifyImages(mlContext, _predictImageListTsv, _predictImagesFolder, _outputImageClassifierZip); + ClassifyImages(mlContext, _predictImageListTsv, _predictImagesFolder, _outputImageClassifierZip, model); // // - ClassifySingleImage(mlContext, _predictSingleImage, _outputImageClassifierZip); + ClassifySingleImage(mlContext, _predictSingleImage, _outputImageClassifierZip, model); // } @@ -62,32 +60,34 @@ private struct InceptionSettings // // 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) { // - var data = mlContext.Data.ReadFromTextFile(path: dataLocation, hasHeader: false); + var data = mlContext.Data.LoadFromTextFile(path: dataLocation, hasHeader: false); // // - var estimator = mlContext.Transforms.Conversion.MapValueToKey(outputColumnName: LabelTokey, inputColumnName: DefaultColumnNames.Label) + var estimator = mlContext.Transforms.Conversion.MapValueToKey(outputColumnName: LabelTokey, inputColumnName: "Label") // // The image transforms transform the images into the model's expected format. // - .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)) // // The ScoreTensorFlowModel transform scores the TensorFlow model and allows communication // - .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)) // // - .Append(mlContext.MulticlassClassification.Trainers.LogisticRegression(labelColumn: LabelTokey, featureColumn: "softmax2_pre_activation")) + .Append(mlContext.MulticlassClassification.Trainers.LbfgsMaximumEntropy(labelColumnName: LabelTokey, featureColumnName: "softmax2_pre_activation")) // // - .Append(mlContext.Transforms.Conversion.MapKeyToValue((PredictedLabelValue, DefaultColumnNames.PredictedLabel))); - // + .Append(mlContext.Transforms.Conversion.MapKeyToValue(PredictedLabelValue, "PredictedLabel")) + .AppendCacheCheckpoint(mlContext); + // // Train the model Console.WriteLine("=============== Training classification model ==============="); @@ -105,22 +105,20 @@ public static void ReuseAndTuneInceptionModel(MLContext mlContext, string dataLo // Create enumerables for both the ImageData and ImagePrediction DataViews // for displaying results // - var imageData = mlContext.CreateEnumerable(data, false, true); - var imagePredictionData = mlContext.CreateEnumerable(predictions, false, true); + var imageData = mlContext.Data.CreateEnumerable(data, false, true); + var imagePredictionData = mlContext.Data.CreateEnumerable(predictions, false, true); // - // Read the tags.tsv file and add the filepath to the image file name - // before loading into ImageData - // - PairAndDisplayResults(imageData, imagePredictionData); - // + // + DisplayResults(imagePredictionData); + // // Get some performance metrics on the model using training data Console.WriteLine("=============== Classification metrics ==============="); // - 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"); // // @@ -128,69 +126,46 @@ public static void ReuseAndTuneInceptionModel(MLContext mlContext, string dataLo Console.WriteLine($"PerClassLogLoss is: {String.Join(" , ", metrics.PerClassLogLoss.Select(c => c.ToString()))}"); // - // Save the model to assets/outputs - Console.WriteLine("=============== Save model to local file ==============="); - - // - using (var fileStream = new FileStream(outputModelLocation, FileMode.Create)) - mlContext.Model.Save(model, fileStream); - // - - Console.WriteLine($"Model saved: {outputModelLocation}"); + // + return model; + // } - 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 - // - ITransformer loadedModel; - using (var fileStream = new FileStream(outputModelLocation, FileMode.Open)) - loadedModel = mlContext.Model.Load(fileStream); - // // Read the image_list.tsv file and add the filepath to the image file name // before loading into ImageData // var imageData = ReadFromTsv(dataLocation, imagesFolder); - var imageDataView = mlContext.Data.ReadFromEnumerable(imageData); + var imageDataView = mlContext.Data.LoadFromEnumerable(imageData); // - + // - var predictions = loadedModel.Transform(imageDataView); - var imagePredictionData = mlContext.CreateEnumerable(predictions, false,true); + var predictions = model.Transform(imageDataView); + var imagePredictionData = mlContext.Data.CreateEnumerable(predictions, false, true); // Console.WriteLine("=============== Making classifications ==============="); - // - PairAndDisplayResults(imageData, imagePredictionData); - // + // + DisplayResults(imagePredictionData); + // } - 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 - // - ITransformer loadedModel; - using (var fileStream = new FileStream(outputModelLocation, FileMode.Open)) - loadedModel = mlContext.Model.Load(fileStream); - // - // load the fully qualified image file name into ImageData // var imageData = new ImageData() { ImagePath = imagePath - }; + }; // // - // Make prediction function (input = ImageNetData, output = ImageNetPrediction) - var predictor = loadedModel.CreatePredictionEngine(mlContext); + // Make prediction function (input = ImageData, output = ImagePrediction) + var predictor = mlContext.Model.CreatePredictionEngine(model); var prediction = predictor.Predict(imageData); // @@ -201,17 +176,12 @@ public static void ClassifySingleImage(MLContext mlContext, string imagePath, st } - private static void PairAndDisplayResults(IEnumerable imageNetData, IEnumerable imageNetPredictionData) + private static void DisplayResults(IEnumerable imagePredictionData) { - // Builds pairs of (image, prediction) to sync up for display - // - IEnumerable<(ImageData image, ImagePrediction prediction)> imagesAndPredictions = imageNetData.Zip(imageNetPredictionData, (image, prediction) => (image, prediction)); - // - // - 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()} "); } // } diff --git a/machine-learning/tutorials/TransferLearningTF/TransferLearningTF.csproj b/machine-learning/tutorials/TransferLearningTF/TransferLearningTF.csproj index d8d996c13f7..c12525cd07e 100644 --- a/machine-learning/tutorials/TransferLearningTF/TransferLearningTF.csproj +++ b/machine-learning/tutorials/TransferLearningTF/TransferLearningTF.csproj @@ -1,4 +1,4 @@ - + Exe @@ -7,9 +7,9 @@ - - - + + + diff --git a/snippets/csharp/VS_Snippets_Winforms/Classic CheckedListBox Example/CS/source.cs b/snippets/csharp/VS_Snippets_Winforms/Classic CheckedListBox Example/CS/source.cs index a096aead92e..f013b46bbb9 100644 --- a/snippets/csharp/VS_Snippets_Winforms/Classic CheckedListBox Example/CS/source.cs +++ b/snippets/csharp/VS_Snippets_Winforms/Classic CheckedListBox Example/CS/source.cs @@ -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; } diff --git a/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.EventExamples/CS/EventExamples.cs b/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.EventExamples/CS/EventExamples.cs index 4d85e8ea57b..ec76debceaf 100644 --- a/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.EventExamples/CS/EventExamples.cs +++ b/snippets/csharp/VS_Snippets_Winforms/System.Windows.Forms.EventExamples/CS/EventExamples.cs @@ -928,11 +928,10 @@ private void BindingManagerBase1_CurrentItemChanged(Object sender, EventArgs e) // private void BindingManagerBase1_DataError(Object sender, BindingManagerDataErrorEventArgs e) { - -System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder(); -messageBoxCS.AppendFormat("{0} = {1}", "Exception", e.Exception ); -messageBoxCS.AppendLine(); -MessageBox.Show(messageBoxCS.ToString(), "DataError Event" ); + System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder(); + messageBoxCS.AppendFormat("{0} = {1}", "Exception", e.Exception); + messageBoxCS.AppendLine(); + MessageBox.Show(messageBoxCS.ToString(), "DataError Event"); } // diff --git a/snippets/csharp/how-to/strings/ParseStringsUsingSplit.cs b/snippets/csharp/how-to/strings/ParseStringsUsingSplit.cs index cf245b08e28..aafaba1a999 100644 --- a/snippets/csharp/how-to/strings/ParseStringsUsingSplit.cs +++ b/snippets/csharp/how-to/strings/ParseStringsUsingSplit.cs @@ -93,20 +93,19 @@ private static void SplitOnMultipleCharsWithGaps() private static void SplitUsingStrings() { // - string[] separatingChars = { "<<", "..." }; - - string text = "one< - } } -} \ No newline at end of file +} diff --git a/snippets/standard/buffers/memory-t/task-returning/task-returning.cs b/snippets/standard/buffers/memory-t/task-returning/task-returning.cs index f5023df4c10..91b57622d27 100644 --- a/snippets/standard/buffers/memory-t/task-returning/task-returning.cs +++ b/snippets/standard/buffers/memory-t/task-returning/task-returning.cs @@ -9,9 +9,9 @@ public class Example // An acceptable implementation. static void Log(ReadOnlyMemory message) { + string defensiveCopy = message.ToString(); // Run in the background so that we don't block the main thread while performing IO. Task.Run(() => { - string defensiveCopy = message.ToString(); StreamWriter sw = File.AppendText(@".\input-numbers.dat"); sw.WriteLine(defensiveCopy); sw.Flush();