diff --git a/ImageClassifier/App.config b/ImageClassifier/App.config
new file mode 100644
index 00000000..193aecc6
--- /dev/null
+++ b/ImageClassifier/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ImageClassifier/ImageClassifier.Designer.cs b/ImageClassifier/ImageClassifier.Designer.cs
new file mode 100644
index 00000000..dd08b3a9
--- /dev/null
+++ b/ImageClassifier/ImageClassifier.Designer.cs
@@ -0,0 +1,154 @@
+namespace ImageClassifier
+{
+ partial class ImageClassifier
+ {
+ ///
+ /// Required designer variable.
+ ///
+ private System.ComponentModel.IContainer components = null;
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ /// true if managed resources should be disposed; otherwise, false.
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing && (components != null))
+ {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Windows Form Designer generated code
+
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ private void InitializeComponent()
+ {
+ this.pbImage = new System.Windows.Forms.PictureBox();
+ this.BtnAnalyzeEmotion = new System.Windows.Forms.Button();
+ this.BtnSelectImageFile = new System.Windows.Forms.Button();
+ this.BtnTrain = new System.Windows.Forms.Button();
+ this.RtbLog = new System.Windows.Forms.RichTextBox();
+ this.BtnSaveModel = new System.Windows.Forms.Button();
+ this.BtnLoadModel = new System.Windows.Forms.Button();
+ this.BtnEvalModel = new System.Windows.Forms.Button();
+ ((System.ComponentModel.ISupportInitialize)(this.pbImage)).BeginInit();
+ this.SuspendLayout();
+ //
+ // pbImage
+ //
+ this.pbImage.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
+ this.pbImage.Location = new System.Drawing.Point(0, 0);
+ this.pbImage.Name = "pbImage";
+ this.pbImage.Size = new System.Drawing.Size(404, 448);
+ this.pbImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
+ this.pbImage.TabIndex = 0;
+ this.pbImage.TabStop = false;
+ //
+ // BtnAnalyzeEmotion
+ //
+ this.BtnAnalyzeEmotion.Location = new System.Drawing.Point(425, 179);
+ this.BtnAnalyzeEmotion.Name = "BtnAnalyzeEmotion";
+ this.BtnAnalyzeEmotion.Size = new System.Drawing.Size(95, 28);
+ this.BtnAnalyzeEmotion.TabIndex = 1;
+ this.BtnAnalyzeEmotion.Text = "Emotion Detect";
+ this.BtnAnalyzeEmotion.UseVisualStyleBackColor = true;
+ this.BtnAnalyzeEmotion.Click += new System.EventHandler(this.BtnAnalyzeEmotion_Click);
+ //
+ // BtnSelectImageFile
+ //
+ this.BtnSelectImageFile.Location = new System.Drawing.Point(425, 145);
+ this.BtnSelectImageFile.Name = "BtnSelectImageFile";
+ this.BtnSelectImageFile.Size = new System.Drawing.Size(95, 28);
+ this.BtnSelectImageFile.TabIndex = 2;
+ this.BtnSelectImageFile.Text = "Select Image";
+ this.BtnSelectImageFile.UseVisualStyleBackColor = true;
+ this.BtnSelectImageFile.Click += new System.EventHandler(this.BtnSelectImageFile_Click);
+ //
+ // BtnTrain
+ //
+ this.BtnTrain.Location = new System.Drawing.Point(425, 48);
+ this.BtnTrain.Name = "BtnTrain";
+ this.BtnTrain.Size = new System.Drawing.Size(95, 28);
+ this.BtnTrain.TabIndex = 3;
+ this.BtnTrain.Text = "Train Model";
+ this.BtnTrain.UseVisualStyleBackColor = true;
+ this.BtnTrain.Click += new System.EventHandler(this.BtnTrain_Click);
+ //
+ // RtbLog
+ //
+ this.RtbLog.Location = new System.Drawing.Point(417, 219);
+ this.RtbLog.Name = "RtbLog";
+ this.RtbLog.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;
+ this.RtbLog.Size = new System.Drawing.Size(367, 218);
+ this.RtbLog.TabIndex = 4;
+ this.RtbLog.Text = "";
+ this.RtbLog.TextChanged += new System.EventHandler(this.RtbLog_TextChanged);
+ //
+ // BtnSaveModel
+ //
+ this.BtnSaveModel.Location = new System.Drawing.Point(425, 113);
+ this.BtnSaveModel.Name = "BtnSaveModel";
+ this.BtnSaveModel.Size = new System.Drawing.Size(95, 28);
+ this.BtnSaveModel.TabIndex = 5;
+ this.BtnSaveModel.Text = "Save Model";
+ this.BtnSaveModel.UseVisualStyleBackColor = true;
+ this.BtnSaveModel.Click += new System.EventHandler(this.BtnSaveModel_Click);
+ //
+ // BtnLoadModel
+ //
+ this.BtnLoadModel.Location = new System.Drawing.Point(425, 12);
+ this.BtnLoadModel.Name = "BtnLoadModel";
+ this.BtnLoadModel.Size = new System.Drawing.Size(95, 28);
+ this.BtnLoadModel.TabIndex = 6;
+ this.BtnLoadModel.Text = "Load Model";
+ this.BtnLoadModel.UseVisualStyleBackColor = true;
+ this.BtnLoadModel.Click += new System.EventHandler(this.BtnLoadModel_Click);
+ //
+ // BtnEvalModel
+ //
+ this.BtnEvalModel.Location = new System.Drawing.Point(425, 81);
+ this.BtnEvalModel.Name = "BtnEvalModel";
+ this.BtnEvalModel.Size = new System.Drawing.Size(95, 28);
+ this.BtnEvalModel.TabIndex = 7;
+ this.BtnEvalModel.Text = "Evaluate Model";
+ this.BtnEvalModel.UseVisualStyleBackColor = true;
+ this.BtnEvalModel.Click += new System.EventHandler(this.BtnEvalModel_Click);
+ //
+ // ImageClassifier
+ //
+ this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
+ this.ClientSize = new System.Drawing.Size(800, 450);
+ this.Controls.Add(this.BtnEvalModel);
+ this.Controls.Add(this.BtnLoadModel);
+ this.Controls.Add(this.BtnSaveModel);
+ this.Controls.Add(this.RtbLog);
+ this.Controls.Add(this.BtnTrain);
+ this.Controls.Add(this.BtnSelectImageFile);
+ this.Controls.Add(this.BtnAnalyzeEmotion);
+ this.Controls.Add(this.pbImage);
+ this.Name = "ImageClassifier";
+ this.Text = "ImageClassifier";
+ ((System.ComponentModel.ISupportInitialize)(this.pbImage)).EndInit();
+ this.ResumeLayout(false);
+
+ }
+
+ #endregion
+
+ private System.Windows.Forms.PictureBox pbImage;
+ private System.Windows.Forms.Button BtnAnalyzeEmotion;
+ private System.Windows.Forms.Button BtnSelectImageFile;
+ private System.Windows.Forms.Button BtnTrain;
+ private System.Windows.Forms.RichTextBox RtbLog;
+ private System.Windows.Forms.Button BtnSaveModel;
+ private System.Windows.Forms.Button BtnLoadModel;
+ private System.Windows.Forms.Button BtnEvalModel;
+ }
+}
+
diff --git a/ImageClassifier/ImageClassifier.cs b/ImageClassifier/ImageClassifier.cs
new file mode 100644
index 00000000..65d91f7f
--- /dev/null
+++ b/ImageClassifier/ImageClassifier.cs
@@ -0,0 +1,179 @@
+using MathNet.Numerics.Data.Text;
+using MathNet.Numerics.LinearAlgebra;
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Data;
+using System.Drawing;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+using Tensorflow;
+
+namespace ImageClassifier
+{
+ public partial class ImageClassifier : Form
+ {
+ private string ModelFolderPath = Path.GetDirectoryName(Application.ExecutablePath) + "/model";
+ string ImageFilePath;
+ NeuralNetwork NNModel;
+ int inputSize = 28 * 28;
+ int hiddenSize = 128;
+ int outputSize = 10;
+ int batchSize = 20;
+ double learningRate = 0.2;
+ int epochs = 20;
+ public ImageClassifier()
+ {
+ InitializeComponent();
+
+ NNModel = new NeuralNetwork(inputSize, hiddenSize, outputSize, batchSize);
+ }
+ static Matrix ImageToDoubleArray(string imagePath)
+ {
+ using (var bitmap = new Bitmap(imagePath))
+ {
+ int width = bitmap.Width;
+ int height = bitmap.Height;
+
+ double[,] pixelValues = new double[1, height * width];
+
+ for (int y = 0; y < height; y++)
+ {
+ for (int x = 0; x < width; x++)
+ {
+ System.Drawing.Color pixelColor = bitmap.GetPixel(x, y);
+
+ pixelValues[0, y * width + x] = pixelColor.B / 255.0;
+ }
+ }
+
+ var m = Matrix.Build.DenseOfArray(pixelValues);
+ return m;
+ }
+ }
+
+ static void ResizeImage(string inputPath, string outputPath, int newWidth, int newHeight)
+ {
+ using (var originalImage = Image.FromFile(inputPath))
+ {
+ using (var resizedImage = new Bitmap(newWidth, newHeight))
+ {
+ using (var graphics = Graphics.FromImage(resizedImage))
+ {
+ graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
+ graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
+ graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
+ graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
+
+ graphics.DrawImage(originalImage, 0, 0, newWidth, newHeight);
+ }
+
+ // Save the resized image
+ resizedImage.Save(outputPath, originalImage.RawFormat);
+ }
+ }
+ }
+
+ public void Log(string str)
+ {
+ RtbLog.Text += str + System.Environment.NewLine;
+ }
+
+ private void BtnAnalyzeEmotion_Click(object sender, EventArgs e)
+ {
+ string outImagePath = Path.Combine(Path.GetDirectoryName(ImageFilePath), Path.GetFileNameWithoutExtension(ImageFilePath) + "_28_28" + Path.GetExtension(ImageFilePath));
+ if (File.Exists(outImagePath))
+ File.Delete(outImagePath);
+
+ //ResizeImage(ImageFilePath, outImagePath, 28, 28);
+
+ var data = ImageToDoubleArray(ImageFilePath);
+ int result = NNModel.PredictNumber(data);
+ Log(result.ToString());
+ }
+
+ private void BtnSelectImageFile_Click(object sender, EventArgs e)
+ {
+ OpenFileDialog ofd = new OpenFileDialog();
+ ofd.Filter = "Image File (*.jpg, *.png) | *.jpg;*.png";
+ if (ofd.ShowDialog() != DialogResult.OK) return;
+
+ ImageFilePath = ofd.FileName;
+ pbImage.Load(ImageFilePath);
+ }
+
+ private void BtnTrain_Click(object sender, EventArgs e)
+ {
+ var (xTrain, yTrain, xTest, yTest) = LoadAndPreprocessData("train.csv");
+
+ for (int epoch = 0; epoch < epochs; epoch++)
+ {
+ for (int batchStart = 0; batchStart < xTrain.RowCount; batchStart += batchSize)
+ {
+ var xBatch = xTrain.SubMatrix(batchStart, batchSize, 0, inputSize);
+ var yBatch = yTrain.SubMatrix(batchStart, batchSize, 0, 1);
+
+ var loss = NNModel.Train(xBatch, yBatch, learningRate);
+ Console.WriteLine($"Epoch {epoch + 1}, Loss : {loss}");
+ }
+ }
+
+ double testAccurcy = NNModel.Evaluate(xTest, yTest);
+ Log($"Test Accuracy is {testAccurcy * 100}%");
+ Log("model train is finished");
+
+ }
+
+ static (Matrix, Matrix, Matrix, Matrix) LoadAndPreprocessData(string filePath)
+ {
+ var data = DelimitedReader.Read(filePath, false, ",", false, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
+ int inputSize = data.ColumnCount - 1;
+ int outputSize = 1;
+
+ double trainTestRatio = 0.8;
+ int trainDataRows = (int)((double)data.RowCount * trainTestRatio);
+ int testDataRows = data.RowCount - trainDataRows;
+ var xTrain = data.SubMatrix(0, trainDataRows, outputSize, inputSize);
+ var yTrain = data.SubMatrix(0, trainDataRows, 0, outputSize);
+ var xTest = data.SubMatrix(trainDataRows, testDataRows, outputSize, inputSize);
+ var yTest = data.SubMatrix(trainDataRows, testDataRows, 0, outputSize);
+
+ return (xTrain / 255.0, yTrain, xTest / 255.0, yTest);
+ }
+
+ private void RtbLog_TextChanged(object sender, EventArgs e)
+ {
+ RtbLog.SelectionStart = RtbLog.Text.Length;
+ RtbLog.ScrollToCaret();
+ }
+
+ private void BtnSaveModel_Click(object sender, EventArgs e)
+ {
+ NNModel.Save(ModelFolderPath);
+ Log("model save success.");
+ }
+
+ private void BtnLoadModel_Click(object sender, EventArgs e)
+ {
+ if (NNModel.Load(ModelFolderPath))
+ {
+ Log("load success.");
+ return;
+ }
+
+ Log("load failed.");
+ }
+
+ private void BtnEvalModel_Click(object sender, EventArgs e)
+ {
+ var (xTrain, yTrain, xTest, yTest) = LoadAndPreprocessData("train.csv");
+
+ double testAccurcy = NNModel.Evaluate(xTest, yTest);
+ Log($"Test Accuracy is {testAccurcy * 100}%");
+ }
+ }
+}
diff --git a/ImageClassifier/ImageClassifier.csproj b/ImageClassifier/ImageClassifier.csproj
new file mode 100644
index 00000000..9ca76968
--- /dev/null
+++ b/ImageClassifier/ImageClassifier.csproj
@@ -0,0 +1,101 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}
+ WinExe
+ ImageClassifier
+ ImageClassifier
+ v4.8
+ 512
+ true
+ true
+
+
+ AnyCPU
+ true
+ full
+ false
+ bin\Debug\
+ DEBUG;TRACE
+ prompt
+ 4
+
+
+ AnyCPU
+ pdbonly
+ true
+ bin\Release\
+ TRACE
+ prompt
+ 4
+
+
+
+ ..\packages\MathNet.Numerics.5.0.0\lib\net48\MathNet.Numerics.dll
+
+
+ ..\packages\MathNet.Numerics.Data.Text.5.0.0\lib\net48\MathNet.Numerics.Data.Text.dll
+
+
+ ..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Form
+
+
+ ImageClassifier.cs
+
+
+
+
+
+ ImageClassifier.cs
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+ Designer
+
+
+ True
+ Resources.resx
+
+
+
+ SettingsSingleFileGenerator
+ Settings.Designer.cs
+
+
+ True
+ Settings.settings
+ True
+
+
+
+
+
+
+
+ {FD682AC0-7B2D-45D3-8B0D-C6D678B04144}
+ Tensorflow.Binding
+
+
+
+
\ No newline at end of file
diff --git a/ImageClassifier/ImageClassifier.resx b/ImageClassifier/ImageClassifier.resx
new file mode 100644
index 00000000..1af7de15
--- /dev/null
+++ b/ImageClassifier/ImageClassifier.resx
@@ -0,0 +1,120 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/ImageClassifier/NeuralNetwork.cs b/ImageClassifier/NeuralNetwork.cs
new file mode 100644
index 00000000..2136bff9
--- /dev/null
+++ b/ImageClassifier/NeuralNetwork.cs
@@ -0,0 +1,220 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using MathNet.Numerics.LinearAlgebra;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+
+namespace ImageClassifier
+{
+ public class NeuralNetwork
+ {
+ public Matrix WeightsInputHidden;
+ public Matrix BiasesHidden;
+ public Matrix WeightsOutputHidden;
+ public Matrix BiasesOutput;
+ public int BatchSize = 1;
+ public NeuralNetwork(int inputSize, int hiddenSize, int outputSize, int batchsize)
+ {
+ WeightsInputHidden = Matrix.Build.Random(inputSize, hiddenSize);
+ BiasesHidden = Matrix.Build.Random(batchsize, hiddenSize);
+ WeightsOutputHidden = Matrix.Build.Random(hiddenSize, outputSize);
+ BiasesOutput = Matrix.Build.Random(batchsize, outputSize);
+
+ BatchSize = batchsize;
+ }
+
+ public void Save(string folderPath)
+ {
+ Directory.CreateDirectory(folderPath);
+ string wIHPath = Path.Combine(folderPath, "wIH.bin");
+ string bIHPath = Path.Combine(folderPath, "bIH.bin");
+ string wOHPath = Path.Combine(folderPath, "wOH.bin");
+ string bOHPath = Path.Combine(folderPath, "bOH.bin");
+
+ if (File.Exists(wIHPath)) File.Delete(wIHPath);
+ if (File.Exists(bIHPath)) File.Delete(bIHPath);
+ if (File.Exists(wOHPath)) File.Delete(wOHPath);
+ if (File.Exists(bOHPath)) File.Delete(bOHPath);
+
+ File.WriteAllText(wIHPath, JsonConvert.SerializeObject(WeightsInputHidden.ToArray()));
+ File.WriteAllText(bIHPath, JsonConvert.SerializeObject(BiasesHidden.ToArray()));
+ File.WriteAllText(wOHPath, JsonConvert.SerializeObject(WeightsOutputHidden.ToArray()));
+ File.WriteAllText(bOHPath, JsonConvert.SerializeObject(BiasesOutput.ToArray()));
+ }
+
+ public bool Load(string folderPath)
+ {
+ if (!Directory.Exists(folderPath))
+ return false;
+ var settings = new JsonSerializerSettings { Converters = new List { new MatrixJsonConverter() } };
+
+ string wIHPath = Path.Combine(folderPath, "wIH.bin");
+ string bIHPath = Path.Combine(folderPath, "bIH.bin");
+ string wOHPath = Path.Combine(folderPath, "wOH.bin");
+ string bOHPath = Path.Combine(folderPath, "bOH.bin");
+
+ if (!File.Exists(bIHPath)) return false;
+ if (!File.Exists(wOHPath)) return false;
+ if (!File.Exists(bOHPath)) return false;
+ if (!File.Exists(wIHPath)) return false;
+
+ WeightsInputHidden = JsonConvert.DeserializeObject>(File.ReadAllText(wIHPath), settings);
+ BiasesHidden = JsonConvert.DeserializeObject>(File.ReadAllText(bIHPath), settings);
+ WeightsOutputHidden = JsonConvert.DeserializeObject>(File.ReadAllText(wOHPath), settings);
+ BiasesOutput = JsonConvert.DeserializeObject>(File.ReadAllText(bOHPath), settings);
+
+ return true;
+ }
+
+ public double Train(Matrix xBatch, Matrix yBatchNonOneHot, double learningRate)
+ {
+ try
+ {
+ var hiddenLayerInput = xBatch * WeightsInputHidden + BiasesHidden;
+ var hiddenLayerOutput = Sigmoid(hiddenLayerInput);
+
+ var outputLayerInput = hiddenLayerOutput * WeightsOutputHidden + BiasesOutput;
+ var outputLayerOutput = Softmax(outputLayerInput);
+
+ var yBatch = OneHotEncoding(yBatchNonOneHot, outputLayerInput.ColumnCount);
+
+ // backward propagation
+ var loss = CrossEntropyLoss(outputLayerOutput, yBatch);
+
+ var outputDelta = outputLayerOutput - yBatch; // a2 - y
+
+ var tt = (outputDelta * WeightsOutputHidden.Transpose());
+ var hiddenDelta = tt.PointwiseMultiply(hiddenLayerOutput).PointwiseMultiply(1 - hiddenLayerOutput);
+
+ WeightsOutputHidden -= hiddenLayerOutput.Transpose() * outputDelta * learningRate;
+ BiasesOutput -= outputDelta * learningRate;
+ WeightsInputHidden -= xBatch.Transpose() * hiddenDelta * learningRate;
+ BiasesHidden -= hiddenDelta * learningRate;
+
+ return loss;
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine("!!!! Train Error : " + ex.Message);
+ return 0;
+ }
+ }
+
+ public Matrix OneHotEncoding(Matrix x, int newRowSize)
+ {
+ var retMat = Matrix.Build.Dense(x.RowCount, newRowSize);
+ for (int i = 0; i < x.RowCount; i++)
+ retMat[i, (int)x[i, 0]] = 1;
+ return retMat;
+ }
+
+ public double Evaluate(Matrix xTest, Matrix yTest)
+ {
+ var predictions = Predict(xTest);
+ var correct = 0;
+ for (int i = 0; i < yTest.RowCount; i++)
+ {
+ int actual = Convert.ToInt32(yTest[i, 0]);
+ var predicted = predictions.Row(i).MaximumIndex();
+
+ if (actual == predicted)
+ correct++;
+ }
+
+ return (double)correct / yTest.RowCount;
+ }
+
+ public Matrix Predict(Matrix xTest)
+ {
+ var extendedBiasesHidden = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(BiasesHidden.Row(0), xTest.RowCount));
+
+ var hiddenLayerInput = (xTest * WeightsInputHidden) + extendedBiasesHidden;
+ var hiddenLayerOutput = Sigmoid(hiddenLayerInput);
+
+ var extendedBiasesOutput = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(BiasesOutput.Row(0), xTest.RowCount));
+
+ var outputLayerInput = hiddenLayerOutput * WeightsOutputHidden + extendedBiasesOutput;
+ var outputLayerOutput = Softmax(outputLayerInput);
+ return outputLayerOutput;
+ }
+
+ public int PredictNumber(Matrix xTest)
+ {
+ var extendedBiasesHidden = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(BiasesHidden.Row(0), xTest.RowCount));
+
+ var hiddenLayerInput = (xTest * WeightsInputHidden) + extendedBiasesHidden;
+ var hiddenLayerOutput = Sigmoid(hiddenLayerInput);
+
+ var extendedBiasesOutput = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(BiasesOutput.Row(0), xTest.RowCount));
+
+ var outputLayerInput = hiddenLayerOutput * WeightsOutputHidden + extendedBiasesOutput;
+ return outputLayerInput.Row(0).MaximumIndex();
+ }
+
+ private double CrossEntropyLoss(Matrix predicted, Matrix actual)
+ {
+ int numRows = predicted.RowCount;
+ int numClasses = predicted.ColumnCount;
+
+ // Calculate the cross-entropy loss
+ double loss = 0.0;
+ for (int i = 0; i < numRows; i++)
+ {
+ for (int j = 0; j < numClasses; j++)
+ {
+ loss -= actual[i, j] * Math.Log(Math.Min(1, predicted[i, j] + 1e-15)); // Add a small epsilon to prevent log(0)
+ }
+ }
+
+ // Normalize the loss by the number of samples
+ loss /= numRows;
+
+ return loss;
+ }
+
+ private Matrix Sigmoid(Matrix x)
+ {
+ return 1 / (1 + (-x).PointwiseExp());
+ }
+
+ private Matrix Softmax(Matrix x)
+ {
+ // Exponentiate the logits
+ var expLogits = x.PointwiseExp();
+
+ // Calculate the sum of the exponentiated logits
+ var sumExpLogits = expLogits.RowSums();
+
+ var sumExpMat = Matrix.Build.DenseOfColumnVectors(Enumerable.Repeat(sumExpLogits, expLogits.ColumnCount));
+
+ // Calculate the softmax probabilities
+ var softmaxProbabilities = expLogits.PointwiseDivide(sumExpMat);
+ return softmaxProbabilities;
+ }
+ }
+
+ public class MatrixJsonConverter : JsonConverter where T : struct, IEquatable, IFormattable
+ {
+ public override bool CanConvert(Type objectType)
+ {
+ return typeof(Matrix).IsAssignableFrom(objectType);
+ }
+
+ public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ {
+ JArray array = JArray.Load(reader);
+ T[,] matrixData = array.ToObject();
+ return Matrix.Build.DenseOfArray(matrixData);
+ }
+
+ public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ {
+ var matrix = (Matrix)value;
+ serializer.Serialize(writer, matrix.ToArray());
+ }
+ }
+}
diff --git a/ImageClassifier/Program.cs b/ImageClassifier/Program.cs
new file mode 100644
index 00000000..40ee9a46
--- /dev/null
+++ b/ImageClassifier/Program.cs
@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Windows.Forms;
+
+namespace ImageClassifier
+{
+ internal static class Program
+ {
+ ///
+ /// The main entry point for the application.
+ ///
+ [STAThread]
+ static void Main()
+ {
+ Application.EnableVisualStyles();
+ Application.SetCompatibleTextRenderingDefault(false);
+ Application.Run(new ImageClassifier());
+ }
+ }
+}
diff --git a/ImageClassifier/Properties/AssemblyInfo.cs b/ImageClassifier/Properties/AssemblyInfo.cs
new file mode 100644
index 00000000..bc69285e
--- /dev/null
+++ b/ImageClassifier/Properties/AssemblyInfo.cs
@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("ImageClassifier")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("ImageClassifier")]
+[assembly: AssemblyCopyright("Copyright © 2023")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("636b8aa9-f6ac-438b-b653-4fdbe0dcf718")]
+
+// Version information for an assembly consists of the following four values:
+//
+// Major Version
+// Minor Version
+// Build Number
+// Revision
+//
+// You can specify all the values or you can default the Build and Revision Numbers
+// by using the '*' as shown below:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/ImageClassifier/Properties/Resources.Designer.cs b/ImageClassifier/Properties/Resources.Designer.cs
new file mode 100644
index 00000000..980cbfc9
--- /dev/null
+++ b/ImageClassifier/Properties/Resources.Designer.cs
@@ -0,0 +1,71 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+namespace ImageClassifier.Properties
+{
+
+
+ ///
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ ///
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources
+ {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources()
+ {
+ }
+
+ ///
+ /// Returns the cached ResourceManager instance used by this class.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager
+ {
+ get
+ {
+ if ((resourceMan == null))
+ {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ImageClassifier.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture
+ {
+ get
+ {
+ return resourceCulture;
+ }
+ set
+ {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/ImageClassifier/Properties/Resources.resx b/ImageClassifier/Properties/Resources.resx
new file mode 100644
index 00000000..af7dbebb
--- /dev/null
+++ b/ImageClassifier/Properties/Resources.resx
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/ImageClassifier/Properties/Settings.Designer.cs b/ImageClassifier/Properties/Settings.Designer.cs
new file mode 100644
index 00000000..0a6e19e7
--- /dev/null
+++ b/ImageClassifier/Properties/Settings.Designer.cs
@@ -0,0 +1,30 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+namespace ImageClassifier.Properties
+{
+
+
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+ {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default
+ {
+ get
+ {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/ImageClassifier/Properties/Settings.settings b/ImageClassifier/Properties/Settings.settings
new file mode 100644
index 00000000..39645652
--- /dev/null
+++ b/ImageClassifier/Properties/Settings.settings
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
diff --git a/ImageClassifier/packages.config b/ImageClassifier/packages.config
new file mode 100644
index 00000000..8b8c63ba
--- /dev/null
+++ b/ImageClassifier/packages.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/TensorFlow.NET.sln b/TensorFlow.NET.sln
index 87729e27..d670365a 100644
--- a/TensorFlow.NET.sln
+++ b/TensorFlow.NET.sln
@@ -39,6 +39,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tensorflow.Benchmark", "too
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tensorflow.Console", "tools\TensorFlowNET.Console\Tensorflow.Console.csproj", "{1DC32255-BA1F-4D6D-A9C9-5BD5ED71CAA0}"
EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "myapps", "myapps", "{4DEA00C6-022E-4E99-A544-DF1A0FD69DA3}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ImageClassifier", "ImageClassifier\ImageClassifier.csproj", "{636B8AA9-F6AC-438B-B653-4FDBE0DCF718}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -322,6 +326,24 @@ Global
{1DC32255-BA1F-4D6D-A9C9-5BD5ED71CAA0}.Release|x64.Build.0 = Release|x64
{1DC32255-BA1F-4D6D-A9C9-5BD5ED71CAA0}.Release|x86.ActiveCfg = Release|Any CPU
{1DC32255-BA1F-4D6D-A9C9-5BD5ED71CAA0}.Release|x86.Build.0 = Release|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Debug|x64.Build.0 = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Debug|x86.Build.0 = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.GPU|Any CPU.ActiveCfg = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.GPU|Any CPU.Build.0 = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.GPU|x64.ActiveCfg = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.GPU|x64.Build.0 = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.GPU|x86.ActiveCfg = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.GPU|x86.Build.0 = Debug|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Release|Any CPU.Build.0 = Release|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Release|x64.ActiveCfg = Release|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Release|x64.Build.0 = Release|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Release|x86.ActiveCfg = Release|Any CPU
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -342,6 +364,7 @@ Global
{D24FCAA5-548C-4251-B226-A1B6535D0845} = {E1A5D2B7-10AF-4876-85C0-7714EF274214}
{C23563DB-FE21-48E7-A411-87A109E4A899} = {E1A5D2B7-10AF-4876-85C0-7714EF274214}
{1DC32255-BA1F-4D6D-A9C9-5BD5ED71CAA0} = {E1A5D2B7-10AF-4876-85C0-7714EF274214}
+ {636B8AA9-F6AC-438B-B653-4FDBE0DCF718} = {4DEA00C6-022E-4E99-A544-DF1A0FD69DA3}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {2DEAD3CC-486B-4918-A607-50B0DE7B114A}