From 91197110de6590873b8435e29c52ef182c190d22 Mon Sep 17 00:00:00 2001 From: Norbert Herman Date: Sun, 17 Dec 2023 11:43:16 +0200 Subject: [PATCH 1/4] initial work finished --- ImageClassifier/App.config | 6 + ImageClassifier/ImageClassifier.Designer.cs | 102 ++++++++++++++ ImageClassifier/ImageClassifier.cs | 79 +++++++++++ ImageClassifier/ImageClassifier.csproj | 98 +++++++++++++ ImageClassifier/ImageClassifier.resx | 120 ++++++++++++++++ ImageClassifier/NeuralNetwork.cs | 133 ++++++++++++++++++ ImageClassifier/Program.cs | 22 +++ ImageClassifier/Properties/AssemblyInfo.cs | 36 +++++ .../Properties/Resources.Designer.cs | 71 ++++++++++ ImageClassifier/Properties/Resources.resx | 117 +++++++++++++++ .../Properties/Settings.Designer.cs | 30 ++++ ImageClassifier/Properties/Settings.settings | 7 + ImageClassifier/packages.config | 5 + TensorFlow.NET.sln | 23 +++ 14 files changed, 849 insertions(+) create mode 100644 ImageClassifier/App.config create mode 100644 ImageClassifier/ImageClassifier.Designer.cs create mode 100644 ImageClassifier/ImageClassifier.cs create mode 100644 ImageClassifier/ImageClassifier.csproj create mode 100644 ImageClassifier/ImageClassifier.resx create mode 100644 ImageClassifier/NeuralNetwork.cs create mode 100644 ImageClassifier/Program.cs create mode 100644 ImageClassifier/Properties/AssemblyInfo.cs create mode 100644 ImageClassifier/Properties/Resources.Designer.cs create mode 100644 ImageClassifier/Properties/Resources.resx create mode 100644 ImageClassifier/Properties/Settings.Designer.cs create mode 100644 ImageClassifier/Properties/Settings.settings create mode 100644 ImageClassifier/packages.config diff --git a/ImageClassifier/App.config b/ImageClassifier/App.config new file mode 100644 index 000000000..193aecc67 --- /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 000000000..83bf4ab27 --- /dev/null +++ b/ImageClassifier/ImageClassifier.Designer.cs @@ -0,0 +1,102 @@ +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(); + ((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, 88); + 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, 54); + 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, 12); + 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); + // + // 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.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; + } +} + diff --git a/ImageClassifier/ImageClassifier.cs b/ImageClassifier/ImageClassifier.cs new file mode 100644 index 000000000..6323a4a4f --- /dev/null +++ b/ImageClassifier/ImageClassifier.cs @@ -0,0 +1,79 @@ +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.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Tensorflow; + +namespace ImageClassifier +{ + public partial class ImageClassifier : Form + { + string ImageFilePath; + public ImageClassifier() + { + InitializeComponent(); + } + + private void BtnAnalyzeEmotion_Click(object sender, EventArgs e) + { + } + + 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) + { + int inputSize = 28 * 28; + int hiddenSize = 128; + int outputSize = 10; + + var (xTrain, yTrain) = LoadAndPreprocessData("train.csv"); + var (xTest, yTest) = LoadAndPreprocessData("test.csv"); + var model = new NeuralNetwork(inputSize, hiddenSize, outputSize); + + int epochs = 5; + double learningRate = 0.001; + int batchSize = 1; + 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 = model.Train(xBatch, yBatch, learningRate); + Console.WriteLine($"Epoch {epoch + 1}, Loss : {loss}"); + } + } + + double testAccurcy = model.Evaluate(xTest, yTest); + Console.WriteLine($"Test Accuracy is {testAccurcy * 100}%"); + + } + + static (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; + + var xData = data.SubMatrix(0, data.RowCount, outputSize, inputSize); + var yData = data.SubMatrix(0, data.RowCount, 0, outputSize); + return (xData / 255.0, yData / 255.0); + } + } +} diff --git a/ImageClassifier/ImageClassifier.csproj b/ImageClassifier/ImageClassifier.csproj new file mode 100644 index 000000000..178ca58f5 --- /dev/null +++ b/ImageClassifier/ImageClassifier.csproj @@ -0,0 +1,98 @@ + + + + + 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 + + + + + + + + + + + + + + + + + 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 000000000..1af7de150 --- /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 000000000..f95d1229f --- /dev/null +++ b/ImageClassifier/NeuralNetwork.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using MathNet.Numerics.LinearAlgebra; + +namespace ImageClassifier +{ + public class NeuralNetwork + { + Matrix weightsInputHidden; + Matrix biasesHidden; + Matrix weightsOutputHidden; + Matrix biasesOutput; + + public NeuralNetwork(int inputSize, int hiddenSize, int outputSize) + { + weightsInputHidden = Matrix.Build.Random(inputSize, hiddenSize); + biasesHidden = Matrix.Build.Random(1, hiddenSize); + weightsOutputHidden = Matrix.Build.Random(hiddenSize, outputSize); + biasesOutput = Matrix.Build.Random(1, outputSize); + } + + public double Train(Matrix xBatch, Matrix yBatchNonOneHot, double learningRate) + { + // forward propagation + + 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; + } + + public Matrix OneHotEncoding(Matrix x, int newRowSize) + { + var retMat = Matrix.Build.Dense(newRowSize, 1); + retMat[(int)x[0, 0], 0] = 1; + return retMat.Transpose(); + } + + public double Evaluate(Matrix xTest, Matrix yTest) + { + var predictions = Predict(xTest); + var correct = 0; + for(int i = 0; i < yTest.RowCount; i++) + { + var actual = yTest.Row(i).MaximumIndex(); + 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; + } + 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(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 Exp(Matrix x) + { + return x.Map(Math.Exp); + } + + private Matrix Softmax(Matrix x) + { + // Exponentiate the logits + var expLogits = x.PointwiseExp(); + + // Calculate the sum of the exponentiated logits + var sumExpLogits = expLogits.RowSums()[0]; + + // Calculate the softmax probabilities + var softmaxProbabilities = expLogits / sumExpLogits; + + return softmaxProbabilities; + } + } +} diff --git a/ImageClassifier/Program.cs b/ImageClassifier/Program.cs new file mode 100644 index 000000000..40ee9a469 --- /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 000000000..bc69285ef --- /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 000000000..980cbfc93 --- /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 000000000..af7dbebba --- /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 000000000..0a6e19e79 --- /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 000000000..39645652a --- /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 000000000..4928da6ed --- /dev/null +++ b/ImageClassifier/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/TensorFlow.NET.sln b/TensorFlow.NET.sln index 87729e27d..d670365a1 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} From 8c09b5a65ec409a94fd0d0635e27aa9cf0dc96e3 Mon Sep 17 00:00:00 2001 From: Norbert Herman Date: Sun, 17 Dec 2023 18:32:25 +0200 Subject: [PATCH 2/4] bug fix --- ImageClassifier/ImageClassifier.Designer.cs | 12 ++++ ImageClassifier/ImageClassifier.cs | 71 +++++++++++++++++++-- ImageClassifier/NeuralNetwork.cs | 19 +++++- 3 files changed, 95 insertions(+), 7 deletions(-) diff --git a/ImageClassifier/ImageClassifier.Designer.cs b/ImageClassifier/ImageClassifier.Designer.cs index 83bf4ab27..ae5a77efa 100644 --- a/ImageClassifier/ImageClassifier.Designer.cs +++ b/ImageClassifier/ImageClassifier.Designer.cs @@ -32,6 +32,7 @@ private void InitializeComponent() 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(); ((System.ComponentModel.ISupportInitialize)(this.pbImage)).BeginInit(); this.SuspendLayout(); // @@ -75,11 +76,21 @@ private void InitializeComponent() 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 = ""; + // // 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.RtbLog); this.Controls.Add(this.BtnTrain); this.Controls.Add(this.BtnSelectImageFile); this.Controls.Add(this.BtnAnalyzeEmotion); @@ -97,6 +108,7 @@ private void InitializeComponent() private System.Windows.Forms.Button BtnAnalyzeEmotion; private System.Windows.Forms.Button BtnSelectImageFile; private System.Windows.Forms.Button BtnTrain; + private System.Windows.Forms.RichTextBox RtbLog; } } diff --git a/ImageClassifier/ImageClassifier.cs b/ImageClassifier/ImageClassifier.cs index 6323a4a4f..55fa383de 100644 --- a/ImageClassifier/ImageClassifier.cs +++ b/ImageClassifier/ImageClassifier.cs @@ -5,6 +5,7 @@ using System.ComponentModel; using System.Data; using System.Drawing; +using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -16,13 +17,73 @@ namespace ImageClassifier public partial class ImageClassifier : Form { string ImageFilePath; + NeuralNetwork NNModel; public ImageClassifier() { InitializeComponent(); } + 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; + } 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) @@ -43,9 +104,9 @@ private void BtnTrain_Click(object sender, EventArgs e) var (xTrain, yTrain) = LoadAndPreprocessData("train.csv"); var (xTest, yTest) = LoadAndPreprocessData("test.csv"); - var model = new NeuralNetwork(inputSize, hiddenSize, outputSize); + NNModel = new NeuralNetwork(inputSize, hiddenSize, outputSize); - int epochs = 5; + int epochs = 3; double learningRate = 0.001; int batchSize = 1; for (int epoch = 0; epoch < epochs; epoch++) @@ -55,12 +116,12 @@ private void BtnTrain_Click(object sender, EventArgs e) var xBatch = xTrain.SubMatrix(batchStart, batchSize, 0, inputSize); var yBatch = yTrain.SubMatrix(batchStart, batchSize, 0, 1); - var loss = model.Train(xBatch, yBatch, learningRate); + var loss = NNModel.Train(xBatch, yBatch, learningRate); Console.WriteLine($"Epoch {epoch + 1}, Loss : {loss}"); } } - double testAccurcy = model.Evaluate(xTest, yTest); + double testAccurcy = NNModel.Evaluate(xTest, yTest); Console.WriteLine($"Test Accuracy is {testAccurcy * 100}%"); } @@ -73,7 +134,7 @@ private void BtnTrain_Click(object sender, EventArgs e) var xData = data.SubMatrix(0, data.RowCount, outputSize, inputSize); var yData = data.SubMatrix(0, data.RowCount, 0, outputSize); - return (xData / 255.0, yData / 255.0); + return (xData / 255.0, yData); } } } diff --git a/ImageClassifier/NeuralNetwork.cs b/ImageClassifier/NeuralNetwork.cs index f95d1229f..d4cdbec50 100644 --- a/ImageClassifier/NeuralNetwork.cs +++ b/ImageClassifier/NeuralNetwork.cs @@ -22,10 +22,11 @@ public NeuralNetwork(int inputSize, int hiddenSize, int outputSize) biasesOutput = Matrix.Build.Random(1, outputSize); } + Matrix temp; public double Train(Matrix xBatch, Matrix yBatchNonOneHot, double learningRate) { // forward propagation - + temp = xBatch; var hiddenLayerInput = xBatch * weightsInputHidden + biasesHidden; var hiddenLayerOutput = Sigmoid(hiddenLayerInput); var outputLayerInput = hiddenLayerOutput * weightsOutputHidden + biasesOutput; @@ -62,7 +63,7 @@ public double Evaluate(Matrix xTest, Matrix yTest) var correct = 0; for(int i = 0; i < yTest.RowCount; i++) { - var actual = yTest.Row(i).MaximumIndex(); + int actual = Convert.ToInt32(yTest[i, 0]); var predicted = predictions.Row(i).MaximumIndex(); if(actual == predicted) @@ -85,6 +86,20 @@ public Matrix Predict(Matrix xTest) 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; From 0bb7bf9f5c4b6881582525763fdfede0e07f7474 Mon Sep 17 00:00:00 2001 From: Norbert Herman Date: Mon, 18 Dec 2023 09:49:56 +0200 Subject: [PATCH 3/4] model save/load function --- ImageClassifier/ImageClassifier.Designer.cs | 33 +++++- ImageClassifier/ImageClassifier.cs | 44 ++++++-- ImageClassifier/ImageClassifier.csproj | 3 + ImageClassifier/NeuralNetwork.cs | 107 ++++++++++++++++++-- ImageClassifier/packages.config | 1 + 5 files changed, 168 insertions(+), 20 deletions(-) diff --git a/ImageClassifier/ImageClassifier.Designer.cs b/ImageClassifier/ImageClassifier.Designer.cs index ae5a77efa..ba11077da 100644 --- a/ImageClassifier/ImageClassifier.Designer.cs +++ b/ImageClassifier/ImageClassifier.Designer.cs @@ -33,6 +33,8 @@ private void InitializeComponent() 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(); ((System.ComponentModel.ISupportInitialize)(this.pbImage)).BeginInit(); this.SuspendLayout(); // @@ -48,7 +50,7 @@ private void InitializeComponent() // // BtnAnalyzeEmotion // - this.BtnAnalyzeEmotion.Location = new System.Drawing.Point(425, 88); + this.BtnAnalyzeEmotion.Location = new System.Drawing.Point(425, 162); this.BtnAnalyzeEmotion.Name = "BtnAnalyzeEmotion"; this.BtnAnalyzeEmotion.Size = new System.Drawing.Size(95, 28); this.BtnAnalyzeEmotion.TabIndex = 1; @@ -58,7 +60,7 @@ private void InitializeComponent() // // BtnSelectImageFile // - this.BtnSelectImageFile.Location = new System.Drawing.Point(425, 54); + this.BtnSelectImageFile.Location = new System.Drawing.Point(425, 124); this.BtnSelectImageFile.Name = "BtnSelectImageFile"; this.BtnSelectImageFile.Size = new System.Drawing.Size(95, 28); this.BtnSelectImageFile.TabIndex = 2; @@ -68,7 +70,7 @@ private void InitializeComponent() // // BtnTrain // - this.BtnTrain.Location = new System.Drawing.Point(425, 12); + 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; @@ -84,12 +86,35 @@ private void InitializeComponent() 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, 85); + 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); // // 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.BtnLoadModel); + this.Controls.Add(this.BtnSaveModel); this.Controls.Add(this.RtbLog); this.Controls.Add(this.BtnTrain); this.Controls.Add(this.BtnSelectImageFile); @@ -109,6 +134,8 @@ private void InitializeComponent() 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; } } diff --git a/ImageClassifier/ImageClassifier.cs b/ImageClassifier/ImageClassifier.cs index 55fa383de..7b0e13471 100644 --- a/ImageClassifier/ImageClassifier.cs +++ b/ImageClassifier/ImageClassifier.cs @@ -16,11 +16,18 @@ 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; + public ImageClassifier() { InitializeComponent(); + + NNModel = new NeuralNetwork(inputSize, hiddenSize, outputSize); } static Matrix ImageToDoubleArray(string imagePath) { @@ -70,7 +77,7 @@ static void ResizeImage(string inputPath, string outputPath, int newWidth, int n public void Log(string str) { - RtbLog.Text += str; + RtbLog.Text += str + System.Environment.NewLine; } private void BtnAnalyzeEmotion_Click(object sender, EventArgs e) @@ -98,16 +105,11 @@ private void BtnSelectImageFile_Click(object sender, EventArgs e) private void BtnTrain_Click(object sender, EventArgs e) { - int inputSize = 28 * 28; - int hiddenSize = 128; - int outputSize = 10; - var (xTrain, yTrain) = LoadAndPreprocessData("train.csv"); var (xTest, yTest) = LoadAndPreprocessData("test.csv"); - NNModel = new NeuralNetwork(inputSize, hiddenSize, outputSize); - int epochs = 3; - double learningRate = 0.001; + int epochs = 5; + double learningRate = 0.01; int batchSize = 1; for (int epoch = 0; epoch < epochs; epoch++) { @@ -122,7 +124,8 @@ private void BtnTrain_Click(object sender, EventArgs e) } double testAccurcy = NNModel.Evaluate(xTest, yTest); - Console.WriteLine($"Test Accuracy is {testAccurcy * 100}%"); + Log($"Test Accuracy is {testAccurcy * 100}%"); + Log("model train is finished"); } @@ -136,5 +139,28 @@ private void BtnTrain_Click(object sender, EventArgs e) var yData = data.SubMatrix(0, data.RowCount, 0, outputSize); return (xData / 255.0, yData); } + + 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."); + } } } diff --git a/ImageClassifier/ImageClassifier.csproj b/ImageClassifier/ImageClassifier.csproj index 178ca58f5..9ca769687 100644 --- a/ImageClassifier/ImageClassifier.csproj +++ b/ImageClassifier/ImageClassifier.csproj @@ -39,6 +39,9 @@ ..\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 + diff --git a/ImageClassifier/NeuralNetwork.cs b/ImageClassifier/NeuralNetwork.cs index d4cdbec50..42bb718d1 100644 --- a/ImageClassifier/NeuralNetwork.cs +++ b/ImageClassifier/NeuralNetwork.cs @@ -1,9 +1,12 @@ 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 { @@ -22,11 +25,78 @@ public NeuralNetwork(int inputSize, int hiddenSize, int outputSize) biasesOutput = Matrix.Build.Random(1, outputSize); } - Matrix temp; - public double Train(Matrix xBatch, Matrix yBatchNonOneHot, double learningRate) + public void Save(string folderPath) + { + //Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); + //serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter()); + //serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; + //serializer.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto; + //serializer.Formatting = Newtonsoft.Json.Formatting.Indented; + + 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); + + //using (StreamWriter sw = new StreamWriter(wIHPath)) + //using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) + //{ + // serializer.Serialize(writer, weightsInputHidden, typeof(Matrix)); + //} + //using (StreamWriter sw = new StreamWriter(bIHPath)) + //using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) + //{ + // serializer.Serialize(writer, biasesHidden, typeof(Matrix)); + //} + //using (StreamWriter sw = new StreamWriter(wOHPath)) + //using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) + //{ + // serializer.Serialize(writer, weightsOutputHidden, typeof(Matrix)); + //} + //using (StreamWriter sw = new StreamWriter(bOHPath)) + //using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) + //{ + // serializer.Serialize(writer, biasesOutput, typeof(Matrix)); + //} + + 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) { - // forward propagation - temp = xBatch; var hiddenLayerInput = xBatch * weightsInputHidden + biasesHidden; var hiddenLayerOutput = Sigmoid(hiddenLayerInput); var outputLayerInput = hiddenLayerOutput * weightsOutputHidden + biasesOutput; @@ -40,7 +110,7 @@ public double Train(Matrix xBatch, Matrix yBatchNonOneHot, doubl var outputDelta = outputLayerOutput - yBatch; // a2 - y var tt = (outputDelta * weightsOutputHidden.Transpose()); - var hiddenDelta = tt.PointwiseMultiply(hiddenLayerOutput).PointwiseMultiply(1-hiddenLayerOutput); + var hiddenDelta = tt.PointwiseMultiply(hiddenLayerOutput).PointwiseMultiply(1 - hiddenLayerOutput); weightsOutputHidden -= hiddenLayerOutput.Transpose() * outputDelta * learningRate; biasesOutput -= outputDelta * learningRate; @@ -61,12 +131,12 @@ public double Evaluate(Matrix xTest, Matrix yTest) { var predictions = Predict(xTest); var correct = 0; - for(int i = 0; i < yTest.RowCount; i++) + for (int i = 0; i < yTest.RowCount; i++) { int actual = Convert.ToInt32(yTest[i, 0]); var predicted = predictions.Row(i).MaximumIndex(); - if(actual == predicted) + if (actual == predicted) correct++; } @@ -83,7 +153,7 @@ public Matrix Predict(Matrix xTest) var extendedBiasesOutput = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(biasesOutput.Row(0), xTest.RowCount)); var outputLayerInput = hiddenLayerOutput * weightsOutputHidden + extendedBiasesOutput; - var outputLayerOutput = Softmax(outputLayerInput); + var outputLayerOutput = Softmax(outputLayerInput); return outputLayerOutput; } @@ -145,4 +215,25 @@ private Matrix Softmax(Matrix x) 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/packages.config b/ImageClassifier/packages.config index 4928da6ed..8b8c63bab 100644 --- a/ImageClassifier/packages.config +++ b/ImageClassifier/packages.config @@ -2,4 +2,5 @@ + \ No newline at end of file From fde89f1611867f08112172c6b0a061e4bb2609ea Mon Sep 17 00:00:00 2001 From: Norbert Herman Date: Wed, 20 Dec 2023 03:07:27 +0200 Subject: [PATCH 4/4] some update --- ImageClassifier/ImageClassifier.Designer.cs | 19 ++- ImageClassifier/ImageClassifier.cs | 39 ++++-- ImageClassifier/NeuralNetwork.cs | 141 +++++++++----------- 3 files changed, 103 insertions(+), 96 deletions(-) diff --git a/ImageClassifier/ImageClassifier.Designer.cs b/ImageClassifier/ImageClassifier.Designer.cs index ba11077da..dd08b3a9a 100644 --- a/ImageClassifier/ImageClassifier.Designer.cs +++ b/ImageClassifier/ImageClassifier.Designer.cs @@ -35,6 +35,7 @@ private void InitializeComponent() 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(); // @@ -50,7 +51,7 @@ private void InitializeComponent() // // BtnAnalyzeEmotion // - this.BtnAnalyzeEmotion.Location = new System.Drawing.Point(425, 162); + 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; @@ -60,7 +61,7 @@ private void InitializeComponent() // // BtnSelectImageFile // - this.BtnSelectImageFile.Location = new System.Drawing.Point(425, 124); + 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; @@ -90,7 +91,7 @@ private void InitializeComponent() // // BtnSaveModel // - this.BtnSaveModel.Location = new System.Drawing.Point(425, 85); + 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; @@ -108,11 +109,22 @@ private void InitializeComponent() 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); @@ -136,6 +148,7 @@ private void InitializeComponent() 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 index 7b0e13471..65d91f7fe 100644 --- a/ImageClassifier/ImageClassifier.cs +++ b/ImageClassifier/ImageClassifier.cs @@ -8,6 +8,7 @@ using System.IO; using System.Linq; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using Tensorflow; @@ -16,18 +17,20 @@ namespace ImageClassifier { public partial class ImageClassifier : Form { - private string ModelFolderPath = Path.GetDirectoryName(Application.ExecutablePath) + "/model"; + 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); + NNModel = new NeuralNetwork(inputSize, hiddenSize, outputSize, batchSize); } static Matrix ImageToDoubleArray(string imagePath) { @@ -105,12 +108,8 @@ private void BtnSelectImageFile_Click(object sender, EventArgs e) private void BtnTrain_Click(object sender, EventArgs e) { - var (xTrain, yTrain) = LoadAndPreprocessData("train.csv"); - var (xTest, yTest) = LoadAndPreprocessData("test.csv"); + var (xTrain, yTrain, xTest, yTest) = LoadAndPreprocessData("train.csv"); - int epochs = 5; - double learningRate = 0.01; - int batchSize = 1; for (int epoch = 0; epoch < epochs; epoch++) { for (int batchStart = 0; batchStart < xTrain.RowCount; batchStart += batchSize) @@ -129,15 +128,21 @@ private void BtnTrain_Click(object sender, EventArgs e) } - static (Matrix, Matrix) LoadAndPreprocessData(string filePath) + 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; - var xData = data.SubMatrix(0, data.RowCount, outputSize, inputSize); - var yData = data.SubMatrix(0, data.RowCount, 0, outputSize); - return (xData / 255.0, yData); + 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) @@ -154,7 +159,7 @@ private void BtnSaveModel_Click(object sender, EventArgs e) private void BtnLoadModel_Click(object sender, EventArgs e) { - if(NNModel.Load(ModelFolderPath)) + if (NNModel.Load(ModelFolderPath)) { Log("load success."); return; @@ -162,5 +167,13 @@ private void BtnLoadModel_Click(object sender, EventArgs e) 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/NeuralNetwork.cs b/ImageClassifier/NeuralNetwork.cs index 42bb718d1..2136bff9a 100644 --- a/ImageClassifier/NeuralNetwork.cs +++ b/ImageClassifier/NeuralNetwork.cs @@ -12,27 +12,23 @@ namespace ImageClassifier { public class NeuralNetwork { - Matrix weightsInputHidden; - Matrix biasesHidden; - Matrix weightsOutputHidden; - Matrix biasesOutput; - - public NeuralNetwork(int inputSize, int hiddenSize, int outputSize) + 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(1, hiddenSize); - weightsOutputHidden = Matrix.Build.Random(hiddenSize, outputSize); - biasesOutput = Matrix.Build.Random(1, outputSize); + 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) { - //Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); - //serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter()); - //serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; - //serializer.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto; - //serializer.Formatting = Newtonsoft.Json.Formatting.Indented; - Directory.CreateDirectory(folderPath); string wIHPath = Path.Combine(folderPath, "wIH.bin"); string bIHPath = Path.Combine(folderPath, "bIH.bin"); @@ -44,31 +40,10 @@ public void Save(string folderPath) if (File.Exists(wOHPath)) File.Delete(wOHPath); if (File.Exists(bOHPath)) File.Delete(bOHPath); - //using (StreamWriter sw = new StreamWriter(wIHPath)) - //using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) - //{ - // serializer.Serialize(writer, weightsInputHidden, typeof(Matrix)); - //} - //using (StreamWriter sw = new StreamWriter(bIHPath)) - //using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) - //{ - // serializer.Serialize(writer, biasesHidden, typeof(Matrix)); - //} - //using (StreamWriter sw = new StreamWriter(wOHPath)) - //using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) - //{ - // serializer.Serialize(writer, weightsOutputHidden, typeof(Matrix)); - //} - //using (StreamWriter sw = new StreamWriter(bOHPath)) - //using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) - //{ - // serializer.Serialize(writer, biasesOutput, typeof(Matrix)); - //} - - 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())); + 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) @@ -87,44 +62,54 @@ public bool Load(string folderPath) 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); + 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) { - var hiddenLayerInput = xBatch * weightsInputHidden + biasesHidden; - var hiddenLayerOutput = Sigmoid(hiddenLayerInput); - var outputLayerInput = hiddenLayerOutput * weightsOutputHidden + biasesOutput; - var outputLayerOutput = Softmax(outputLayerInput); + try + { + var hiddenLayerInput = xBatch * WeightsInputHidden + BiasesHidden; + var hiddenLayerOutput = Sigmoid(hiddenLayerInput); - var yBatch = OneHotEncoding(yBatchNonOneHot, outputLayerInput.ColumnCount); + var outputLayerInput = hiddenLayerOutput * WeightsOutputHidden + BiasesOutput; + var outputLayerOutput = Softmax(outputLayerInput); - // backward propagation - var loss = CrossEntropyLoss(outputLayerOutput, yBatch); + var yBatch = OneHotEncoding(yBatchNonOneHot, outputLayerInput.ColumnCount); - var outputDelta = outputLayerOutput - yBatch; // a2 - y + // backward propagation + var loss = CrossEntropyLoss(outputLayerOutput, yBatch); - var tt = (outputDelta * weightsOutputHidden.Transpose()); - var hiddenDelta = tt.PointwiseMultiply(hiddenLayerOutput).PointwiseMultiply(1 - hiddenLayerOutput); + var outputDelta = outputLayerOutput - yBatch; // a2 - y - weightsOutputHidden -= hiddenLayerOutput.Transpose() * outputDelta * learningRate; - biasesOutput -= outputDelta * learningRate; - weightsInputHidden -= xBatch.Transpose() * hiddenDelta * learningRate; - biasesHidden -= hiddenDelta * learningRate; + var tt = (outputDelta * WeightsOutputHidden.Transpose()); + var hiddenDelta = tt.PointwiseMultiply(hiddenLayerOutput).PointwiseMultiply(1 - hiddenLayerOutput); - return loss; + 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(newRowSize, 1); - retMat[(int)x[0, 0], 0] = 1; - return retMat.Transpose(); + 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) @@ -145,28 +130,28 @@ public double Evaluate(Matrix xTest, Matrix yTest) public Matrix Predict(Matrix xTest) { - var extendedBiasesHidden = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(biasesHidden.Row(0), xTest.RowCount)); + var extendedBiasesHidden = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(BiasesHidden.Row(0), xTest.RowCount)); - var hiddenLayerInput = (xTest * weightsInputHidden) + extendedBiasesHidden; + var hiddenLayerInput = (xTest * WeightsInputHidden) + extendedBiasesHidden; var hiddenLayerOutput = Sigmoid(hiddenLayerInput); - var extendedBiasesOutput = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(biasesOutput.Row(0), xTest.RowCount)); + var extendedBiasesOutput = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(BiasesOutput.Row(0), xTest.RowCount)); - var outputLayerInput = hiddenLayerOutput * weightsOutputHidden + extendedBiasesOutput; + 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 extendedBiasesHidden = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(BiasesHidden.Row(0), xTest.RowCount)); - var hiddenLayerInput = (xTest * weightsInputHidden) + extendedBiasesHidden; + var hiddenLayerInput = (xTest * WeightsInputHidden) + extendedBiasesHidden; var hiddenLayerOutput = Sigmoid(hiddenLayerInput); - var extendedBiasesOutput = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(biasesOutput.Row(0), xTest.RowCount)); + var extendedBiasesOutput = Matrix.Build.DenseOfRowVectors(Enumerable.Repeat(BiasesOutput.Row(0), xTest.RowCount)); - var outputLayerInput = hiddenLayerOutput * weightsOutputHidden + extendedBiasesOutput; + var outputLayerInput = hiddenLayerOutput * WeightsOutputHidden + extendedBiasesOutput; return outputLayerInput.Row(0).MaximumIndex(); } @@ -181,7 +166,7 @@ private double CrossEntropyLoss(Matrix predicted, Matrix actual) { for (int j = 0; j < numClasses; j++) { - loss -= actual[i, j] * Math.Log(predicted[i, j] + 1e-15); // Add a small epsilon to prevent log(0) + loss -= actual[i, j] * Math.Log(Math.Min(1, predicted[i, j] + 1e-15)); // Add a small epsilon to prevent log(0) } } @@ -196,22 +181,18 @@ private Matrix Sigmoid(Matrix x) return 1 / (1 + (-x).PointwiseExp()); } - private Matrix Exp(Matrix x) - { - return x.Map(Math.Exp); - } - private Matrix Softmax(Matrix x) { // Exponentiate the logits var expLogits = x.PointwiseExp(); // Calculate the sum of the exponentiated logits - var sumExpLogits = expLogits.RowSums()[0]; + var sumExpLogits = expLogits.RowSums(); - // Calculate the softmax probabilities - var softmaxProbabilities = expLogits / sumExpLogits; + var sumExpMat = Matrix.Build.DenseOfColumnVectors(Enumerable.Repeat(sumExpLogits, expLogits.ColumnCount)); + // Calculate the softmax probabilities + var softmaxProbabilities = expLogits.PointwiseDivide(sumExpMat); return softmaxProbabilities; } }