Skip to content

Commit 8624acc

Browse files
Youssef1313CESARDELATORRE
authored andcommitted
Follow coding conventions (dotnet#672)
1 parent fb3c165 commit 8624acc

File tree

18 files changed

+119
-118
lines changed

18 files changed

+119
-118
lines changed

samples/csharp/common/Compress.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ public static void ExtractGZip(string gzipFileName, string targetDir)
1717
// Use a 4K buffer. Any larger is a waste.
1818
byte[] dataBuffer = new byte[4096];
1919

20-
using (System.IO.Stream fs = new FileStream(gzipFileName, FileMode.Open, FileAccess.Read))
20+
using (Stream fs = new FileStream(gzipFileName, FileMode.Open, FileAccess.Read))
2121
{
22-
using (GZipInputStream gzipStream = new GZipInputStream(fs))
22+
using (var gzipStream = new GZipInputStream(fs))
2323
{
24-
// Change this to your needs
24+
// Change this to your needs.
2525
string fnOut = Path.Combine(targetDir, Path.GetFileNameWithoutExtension(gzipFileName));
2626

2727
using (FileStream fsOut = File.Create(fnOut))
@@ -37,7 +37,7 @@ public static void UnZip(String gzArchiveName, String destFolder)
3737
var flag = gzArchiveName.Split(Path.DirectorySeparatorChar).Last().Split('.').First() + ".bin";
3838
if (File.Exists(Path.Combine(destFolder, flag))) return;
3939

40-
Console.WriteLine($"Extracting.");
40+
Console.WriteLine("Extracting.");
4141
var task = Task.Run(() =>
4242
{
4343
ZipFile.ExtractToDirectory(gzArchiveName, destFolder);
@@ -59,7 +59,7 @@ public static void ExtractTGZ(String gzArchiveName, String destFolder)
5959
var flag = gzArchiveName.Split(Path.DirectorySeparatorChar).Last().Split('.').First() + ".bin";
6060
if (File.Exists(Path.Combine(destFolder, flag))) return;
6161

62-
Console.WriteLine($"Extracting.");
62+
Console.WriteLine("Extracting.");
6363
var task = Task.Run(() =>
6464
{
6565
using (var inStream = File.OpenRead(gzArchiveName))

samples/csharp/end-to-end-apps/AnomalyDetection-Sales/SpikeDetectionE2EApp/SpikeDetection.ModelTrainer/Program.cs

+23-23
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,21 @@ internal static class Program
2222
private static MLContext mlContext;
2323
static void Main()
2424
{
25-
// Create MLContext to be shared across the model creation workflow objects
25+
// Create MLContext to be shared across the model creation workflow objects.
2626
mlContext = new MLContext();
2727

28-
// Assign the Number of records in dataset file to constant variable
28+
// Assign the Number of records in dataset file to constant variable.
2929
const int size = 36;
3030

31-
//Load the data into IDataView.
32-
//This dataset is used for detecting spikes or changes not for training.
31+
// Load the data into IDataView.
32+
// This dataset is used for detecting spikes or changes not for training.
3333
IDataView dataView = mlContext.Data.LoadFromTextFile<ProductSalesData>(path: DatasetPath, hasHeader: true, separatorChar: ',');
3434

35-
// Detect temporary changes (spikes) in the pattern
35+
// Detect temporary changes (spikes) in the pattern.
3636
ITransformer trainedSpikeModel = DetectSpike(size, dataView);
3737

38-
// Detect persistent change in the pattern
39-
ITransformer trainedChangePointModel = DetectChangepoint(size, dataView);
38+
// Detect persistent change in the pattern.
39+
ITransformer trainedChangePointModel = DetectChangepoint(size, dataView);
4040

4141
SaveModel(mlContext, trainedSpikeModel, SpikeModelPath, dataView);
4242
SaveModel(mlContext, trainedChangePointModel, ChangePointModelPath, dataView);
@@ -49,17 +49,17 @@ private static ITransformer DetectSpike(int size, IDataView dataView)
4949
{
5050
Console.WriteLine("===============Detect temporary changes in pattern===============");
5151

52-
//STEP 1: Create Esimator
52+
// STEP 1: Create Esimator.
5353
var estimator = mlContext.Transforms.DetectIidSpike(outputColumnName: nameof(ProductSalesPrediction.Prediction), inputColumnName: nameof(ProductSalesData.numSales), confidence: 95, pvalueHistoryLength: size / 4);
5454

55-
//STEP 2:The Transformed Model.
56-
//In IID Spike detection, we don't need to do training, we just need to do transformation.
57-
//As you are not training the model, there is no need to load IDataView with real data, you just need schema of data.
58-
//So create empty data view and pass to Fit() method.
55+
// STEP 2:The Transformed Model.
56+
// In IID Spike detection, we don't need to do training, we just need to do transformation.
57+
// As you are not training the model, there is no need to load IDataView with real data, you just need schema of data.
58+
// So create empty data view and pass to Fit() method.
5959
ITransformer tansformedModel = estimator.Fit(CreateEmptyDataView());
6060

61-
//STEP 3: Use/test model
62-
//Apply data transformation to create predictions.
61+
// STEP 3: Use/test model.
62+
// Apply data transformation to create predictions.
6363
IDataView transformedData = tansformedModel.Transform(dataView);
6464
var predictions = mlContext.Data.CreateEnumerable<ProductSalesPrediction>(transformedData, reuseRowObject: false);
6565

@@ -82,17 +82,17 @@ private static ITransformer DetectChangepoint(int size, IDataView dataView)
8282
{
8383
Console.WriteLine("===============Detect Persistent changes in pattern===============");
8484

85-
//STEP 1: Setup transformations using DetectIidChangePoint
85+
// STEP 1: Setup transformations using DetectIidChangePoint.
8686
var estimator = mlContext.Transforms.DetectIidChangePoint(outputColumnName: nameof(ProductSalesPrediction.Prediction), inputColumnName: nameof(ProductSalesData.numSales), confidence: 95, changeHistoryLength: size / 4);
8787

88-
//STEP 2:The Transformed Model.
89-
//In IID Change point detection, we don't need need to do training, we just need to do transformation.
90-
//As you are not training the model, there is no need to load IDataView with real data, you just need schema of data.
91-
//So create empty data view and pass to Fit() method.
88+
// STEP 2:The Transformed Model.
89+
// In IID Change point detection, we don't need need to do training, we just need to do transformation.
90+
// As you are not training the model, there is no need to load IDataView with real data, you just need schema of data.
91+
// So create empty data view and pass to Fit() method.
9292
ITransformer tansformedModel = estimator.Fit(CreateEmptyDataView());
9393

94-
//STEP 3: Use/test model
95-
//Apply data transformation to create predictions.
94+
// STEP 3: Use/test model.
95+
// Apply data transformation to create predictions.
9696
IDataView transformedData = tansformedModel.Transform(dataView);
9797
var predictions = mlContext.Data.CreateEnumerable<ProductSalesPrediction>(transformedData, reuseRowObject: false);
9898

@@ -119,12 +119,12 @@ private static void SaveModel(MLContext mlcontext, ITransformer trainedModel, st
119119
Console.WriteLine("=============== Saving model ===============");
120120
mlcontext.Model.Save(trainedModel,dataView.Schema, modelPath);
121121

122-
Console.WriteLine("The model is saved to {0}", modelPath);
122+
Console.WriteLine($"The model is saved to {modelPath}");
123123
}
124124

125125
public static string GetAbsolutePath(string relativePath)
126126
{
127-
FileInfo _dataRoot = new FileInfo(typeof(Program).Assembly.Location);
127+
var _dataRoot = new FileInfo(typeof(Program).Assembly.Location);
128128
string assemblyFolderPath = _dataRoot.Directory.FullName;
129129

130130
string fullPath = Path.Combine(assemblyFolderPath, relativePath);

samples/csharp/end-to-end-apps/AnomalyDetection-Sales/SpikeDetectionE2EApp/SpikeDetection.WinForms/Form1.cs

+29-29
Original file line numberDiff line numberDiff line change
@@ -29,43 +29,43 @@ public Form1()
2929
InitializeComponent();
3030
}
3131

32-
// Find file button
32+
// Find file button.
3333
private void button1_Click(object sender, EventArgs e)
3434
{
35-
// Open File Explorer
35+
// Open File Explorer.
3636
DialogResult result = openFileExplorer.ShowDialog();
3737

38-
// Set text in file path textbox to file path from file explorer
38+
// Set text in file path textbox to file path from file explorer.
3939
if (result == DialogResult.OK)
4040
{
4141
filePathTextbox.Text = openFileExplorer.FileName;
4242
}
4343
}
4444

45-
// Go button
45+
// Go button.
4646
private void button2_Click(object sender, EventArgs e)
4747
{
48-
// Set filepath from text from filepath textbox
48+
// Set filepath from text from filepath textbox.
4949
filePath = filePathTextbox.Text;
5050

51-
// Checkk if file exists
51+
// Check if file exists.
5252
if (File.Exists(filePath))
5353
{
5454
dict = new Dictionary<int, Tuple<string, string>>();
5555

5656
if (filePath != "")
5757
{
58-
// Reset text in anomaly textbox
58+
// Reset text in anomaly textbox.
5959
anomalyText.Text = "";
6060

61-
// Display preview of dataset and graph
61+
// Display preview of dataset and graph.
6262
displayDataTableAndGraph();
6363

64-
// Load a trained model to detect anomalies and then mark them on the graph
64+
// Load a trained model to detect anomalies and then mark them on the graph.
6565
detectAnomalies();
6666

6767
}
68-
// If file path textbox is empty, prompt user to input file path
68+
// If file path textbox is empty, prompt user to input file path.
6969
else
7070
{
7171
MessageBox.Show("Please input file path.");
@@ -97,7 +97,7 @@ private void displayDataTableAndGraph()
9797

9898
foreach (string line in dataset.Skip(1))
9999
{
100-
// Add next row of data
100+
// Add next row of data.
101101
dataCol = commaSeparatedRadio.Checked ? line.Split(',') : line.Split('\t');
102102
dataTable.Rows.Add(dataCol);
103103

@@ -107,17 +107,17 @@ private void displayDataTableAndGraph()
107107
a++;
108108
}
109109

110-
// Set data view preview source
110+
// Set data view preview source.
111111
dataGridView1.DataSource = dataTable;
112112

113-
// Update y axis min and max values
114-
double yMax = Convert.ToDouble(dataTable.Compute("max([" + yAxis + "])", string.Empty));
115-
double yMin = Convert.ToDouble(dataTable.Compute("min([" + yAxis + "])", string.Empty));
113+
// Update y axis min and max values.
114+
double yMax = Convert.ToDouble(dataTable.Compute($"max([{yAxis}])", string.Empty));
115+
double yMin = Convert.ToDouble(dataTable.Compute($"min([{yAxis}])", string.Empty));
116116

117-
// Set graph source
117+
// Set graph source.
118118
graph.DataSource = dataTable;
119119

120-
// Set graph options
120+
// Set graph options.
121121
graph.Series["Series1"].ChartType = SeriesChartType.Line;
122122

123123
graph.Series["Series1"].XValueMember = xAxis;
@@ -139,14 +139,14 @@ private void displayDataTableAndGraph()
139139

140140
private void detectAnomalies()
141141
{
142-
// Create MLContext to be shared across the model creation workflow objects
142+
// Create MLContext to be shared across the model creation workflow objects.
143143
var mlcontext = new MLContext();
144144

145145
// STEP 1: Load the data into IDataView.
146146
IDataView dataView = mlcontext.Data.LoadFromTextFile<ProductSalesData>(path: filePath, hasHeader: true, separatorChar: commaSeparatedRadio.Checked ? ',' : '\t');
147147

148-
// Step 2: Load & use model
149-
// Note -- The model is trained with the product-sales dataset in a separate console app (see AnomalyDetectionConsoleApp)
148+
// Step 2: Load & use model.
149+
// Note -- The model is trained with the product-sales dataset in a separate console app (see AnomalyDetectionConsoleApp).
150150
if (spikeDet.Checked)
151151
{
152152
if (File.Exists(spikeModelPath))
@@ -174,7 +174,7 @@ private void detectAnomalies()
174174

175175
public static string GetAbsolutePath(string relativePath)
176176
{
177-
FileInfo _dataRoot = new FileInfo(typeof(Program).Assembly.Location);
177+
var _dataRoot = new FileInfo(typeof(Program).Assembly.Location);
178178
string assemblyFolderPath = _dataRoot.Directory.FullName;
179179

180180
string fullPath = Path.Combine(assemblyFolderPath, relativePath);
@@ -186,37 +186,37 @@ private void loadAndUseModel(MLContext mlcontext, IDataView dataView, String mod
186186
{
187187
ITransformer tansformedModel = mlcontext.Model.Load(modelPath, out var modelInputSchema);
188188

189-
// Step 3: Apply data transformation to create predictions
189+
// Step 3: Apply data transformation to create predictions.
190190
IDataView transformedData = tansformedModel.Transform(dataView);
191191
var predictions = mlcontext.Data.CreateEnumerable<ProductSalesPrediction>(transformedData, reuseRowObject: false);
192192

193-
// Index key for dictionary (date, sales)
193+
// Index key for dictionary (date, sales).
194194
int a = 0;
195195

196196
foreach (var prediction in predictions)
197197
{
198-
// Check if anomaly is predicted (indicated by an alert)
198+
// Check if anomaly is predicted (indicated by an alert).
199199
if (prediction.Prediction[0] == 1)
200200
{
201-
// Get the date (year-month) where spike is detected
201+
// Get the date (year-month) where spike is detected.
202202
var xAxisDate = dict[a].Item1;
203-
// Get the number of sales which was detected to be a spike
203+
// Get the number of sales which was detected to be a spike.
204204
var yAxisSalesNum = dict[a].Item2;
205205

206206
// Add anomaly points to graph
207-
// and set point/marker options
207+
// and set point/marker options.
208208
graph.Series["Series1"].Points[a].SetValueXY(a, yAxisSalesNum);
209209
graph.Series["Series1"].Points[a].MarkerStyle = MarkerStyle.Star4;
210210
graph.Series["Series1"].Points[a].MarkerSize = 10;
211211
graph.Series["Series1"].Points[a].MarkerColor = color;
212212

213213
// Print out anomalies as text for user &
214-
// change color of text accordingly
214+
// change color of text accordingly.
215215
string text = type + " detected in " + xAxisDate + ": " + yAxisSalesNum + "\n";
216216
anomalyText.SelectionColor = color;
217217
anomalyText.AppendText(text);
218218

219-
// Change row color in table where anomalies occur
219+
// Change row color in table where anomalies occur.
220220
DataGridViewRow row = dataGridView1.Rows[a];
221221
row.DefaultCellStyle.BackColor = color;
222222
row.DefaultCellStyle.ForeColor = Color.White;

samples/csharp/end-to-end-apps/DeepLearning_ImageClassification_TensorFlow/TensorFlowImageClassification/Controllers/ImageClassificationController.cs

+16-16
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,13 @@ public class ImageClassificationController : ControllerBase
2525

2626
public ImageClassificationController(PredictionEnginePool<ImageInputData, ImageLabelPredictions> predictionEnginePool, IConfiguration configuration, ILogger<ImageClassificationController> logger) //When using DI/IoC
2727
{
28-
// Get the ML Model Engine injected, for scoring
28+
// Get the ML Model Engine injected, for scoring.
2929
_predictionEnginePool = predictionEnginePool;
3030

3131
Configuration = configuration;
3232
_labelsFilePath = GetAbsolutePath(Configuration["MLModel:LabelsFilePath"]);
3333

34-
//Get other injected dependencies
34+
// Get other injected dependencies.
3535
_logger = logger;
3636
}
3737

@@ -44,37 +44,37 @@ public async Task<IActionResult> ClassifyImage(IFormFile imageFile)
4444
if (imageFile.Length == 0)
4545
return BadRequest();
4646

47-
MemoryStream imageMemoryStream = new MemoryStream();
47+
var imageMemoryStream = new MemoryStream();
4848
await imageFile.CopyToAsync(imageMemoryStream);
4949

50-
//Check that the image is valid
50+
// Check that the image is valid.
5151
byte[] imageData = imageMemoryStream.ToArray();
5252
if (!imageData.IsValidImage())
5353
return StatusCode(StatusCodes.Status415UnsupportedMediaType);
5454

55-
//Convert to Image
55+
// Convert to Image.
5656
Image image = Image.FromStream(imageMemoryStream);
5757

58-
//Convert to Bitmap
58+
// Convert to Bitmap.
5959
Bitmap bitmapImage = (Bitmap)image;
6060

61-
_logger.LogInformation($"Start processing image...");
61+
_logger.LogInformation("Start processing image...");
6262

63-
//Measure execution time
63+
// Measure execution time.
6464
var watch = System.Diagnostics.Stopwatch.StartNew();
6565

66-
//Set the specific image data into the ImageInputData type used in the DataView
67-
ImageInputData imageInputData = new ImageInputData { Image = bitmapImage };
66+
// Set the specific image data into the ImageInputData type used in the DataView.
67+
var imageInputData = new ImageInputData { Image = bitmapImage };
6868

69-
//Predict code for provided image
69+
// Predict code for provided image.
7070
ImageLabelPredictions imageLabelPredictions = _predictionEnginePool.Predict(imageInputData);
7171

72-
//Stop measuring time
72+
// Stop measuring time.
7373
watch.Stop();
7474
var elapsedMs = watch.ElapsedMilliseconds;
7575
_logger.LogInformation($"Image processed in {elapsedMs} miliseconds");
7676

77-
//Predict the image's label (The one with highest probability)
77+
// Predict the image's label (The one with highest probability).
7878
ImagePredictedLabelWithProbability imageBestLabelPrediction
7979
= FindBestLabelWithProbability(imageLabelPredictions, imageInputData);
8080

@@ -83,12 +83,12 @@ ImagePredictedLabelWithProbability imageBestLabelPrediction
8383

8484
private ImagePredictedLabelWithProbability FindBestLabelWithProbability(ImageLabelPredictions imageLabelPredictions, ImageInputData imageInputData)
8585
{
86-
//Read TF model's labels (labels.txt) to classify the image across those labels
86+
// Read TF model's labels (labels.txt) to classify the image across those labels.
8787
var labels = ReadLabels(_labelsFilePath);
8888

8989
float[] probabilities = imageLabelPredictions.PredictedLabels;
9090

91-
//Set a single label as predicted or even none if probabilities were lower than 70%
91+
// Set a single label as predicted or even none if probabilities were lower than 70%.
9292
var imageBestLabelPrediction = new ImagePredictedLabelWithProbability()
9393
{
9494
ImageId = imageInputData.GetHashCode().ToString(), //This ID is not really needed, it could come from the application itself, etc.
@@ -117,7 +117,7 @@ private string[] ReadLabels(string labelsLocation)
117117

118118
public static string GetAbsolutePath(string relativePath)
119119
{
120-
FileInfo _dataRoot = new FileInfo(typeof(Program).Assembly.Location);
120+
var _dataRoot = new FileInfo(typeof(Program).Assembly.Location);
121121
string assemblyFolderPath = _dataRoot.Directory.FullName;
122122

123123
string fullPath = Path.Combine(assemblyFolderPath, relativePath);

0 commit comments

Comments
 (0)