目錄
介紹
背景
使用代碼
興趣點
由于機器學習已變得非常流行,因此使用Keras和/或后端Tensorflow這樣的開源SDK,Python語言也再次變得流行(與預測相反,Python將在未來五年內消失)。作為.NET環境的研究工程師,它給我帶來了很多問題,我在那里使用Python,而我的主要重點是C#。當然,您可以以某種方式將Python代碼嵌入到您的應用程序中(即,在.NET應用程序中運行Python腳本),但這并沒有使它變得更好。
我認為,另一個解決方案是使用IronPython,這是一個可以直接運行Python代碼的SDK,但是
因此,我開始研究新的解決方案,以及如何避免在.NET Core應用程序中使用其他Python環境(在應用程序啟動時必須額外使用這些環境),并了解Keras.NET(https://github.com/SciSharp/Keras.NET)。明確地說,我不在乎SDK是否使用Python嵌入式,但是我不想用Python編寫我的機器學習原型,所以這是改變游戲規則的地方。
Keras.NET的文檔非常簡短,如果您需要進一步的知識,可以將它們鏈接到原始Keras文檔。這對于理解此框架的工作方式非常有用。但是要弄清楚SDK如何在C#中工作是很痛苦的。
這里是文檔鏈接:https?:?//scisharp.github.io/Keras.NET/
請查看先決條件(在此前提下,您還必須安裝Python)。
在這里,您將找到API文檔:https?:?//scisharp.github.io/Keras.NET/api/index.html
要了解此處發生的情況,您需要了解Keras的工作方式、密集層、時代等的用途。
Arnaldo??P.Casta?o的文章啟發了我展示使用現有數據集的第二個示例以及如何使用Keras.NET進行訓練。因此,這是有關使用Keras.NET與使用Keras(在Python中)看到一些區別的信息,也許有人會發現這非常有用。
首先,您將需要Nuget Keras.NET。在Visual Studio中使用程序包管理器,它類似于:
PM> Install-Package Keras.NET -Version 3.8.4.4
除此之外,您將需要使用Windows CLI或Powershell中的pip安裝程序來安裝Keras和Tensorflow for Python:
pip install keraspip install tensorflow
它必須在Windows-CLI中看起來像:
C:\Users\YOURNAME>pip install keras
如果您對pip安裝程序有疑問,請檢查是否已將Python設置為系統環境。安裝屏幕底部有一個復選框,稱為“將Python添加到PATH”,這非常重要。
如果這樣做沒有幫助,則您可能必須自行設置路徑(互聯網上有“操作方法”,如何修復pip的提示音,一旦解決了此問題,就可以確定Python設置正確) 。
最后,您將需要訓練和測試集:https?:?//github.com/zalandoresearch/fashion-mnist#get-the-data。
首先,我將數據存儲在本地并解壓縮,因為我不想為解壓縮而創建其他功能(這實際上并不難實現,但我想在此重點關注)。這只是一個數據。使用下面的代碼(并調用該openDatas?函數,您將需要解壓縮該文件,否則該函數將無法讀取數據。請放置四個數據(2x圖像,2x標簽...訓練并測試)。
其次,我在API-Doc中指出,已經實現了直接加載數據的函數,請參見:https?:?//scisharp.github.io/Keras.NET/api/Keras.Datasets.FashionMNIST.html
所以我們開始:為了進一步的目的,運行模型的第一次訓練。
我的.NET-Core的入口點非常簡單。我為訓練做了一個類(KerasClass),只需從Main函數中調用它們即可:
using System;namespace Keras.net_and_fashion_mnist
{class Program{static void Main(string[] args){KerasClass keras = new KerasClass();keras.TrainModel();} }
}
java package用法。KerasClass是更加有趣的:
using Keras.Datasets;
using Keras.Layers;
using Keras.Models;
using Keras.Utils;
using Numpy;
using System;
using System.IO;
using System.Linq;namespace Keras.net_and_fashion_mnist
{class KerasClass{public void TrainModel(){int batch_size = 1000; //Size of the batches per epochint num_classes = 10; //We got 10 outputs since //we can predict 10 different labels seen on the //dataset: https://github.com/zalandoresearch/fashion-mnist#labelsint epochs = 30; //Amount on trainingperiods, //I figure it out that the maximum is something about //700 epochs, after this it won't increase the //accuracy siginificantly// input image dimensionsint img_rows = 28, img_cols = 28;// the data, split between train and test setsvar ((x_train, y_train), (x_test, y_test)) = FashionMNIST.LoadData(); // Load the datasets from // fashion MNIST, Keras.Net implement this directlyx_train.reshape(-1, img_rows, img_cols).astype(np.float32); //ByteArray needs //to be reshaped to fit the dimmensions of the y arraysy_train = Util.ToCategorical(y_train, num_classes); //here, you modify the //forecast data to 10 outputs//as we have 10 different //labels to predict (see the //Labels on the Dataset)y_test = Util.ToCategorical(y_test, num_classes); //same for the test data //[hint: you can change this //in example you want to //make just a binary //crossentropy as you just //want to figure, i.e., if //this is a angleboot or notvar model = new Sequential();model.Add(new Dense(100, 784, "sigmoid")); //hidden dense layer, with 100 neurons, //you have 28*28 pixel which make //784 'inputs', and sigmoid function //as activationfunctionmodel.Add(new Dense(10, null, "sigmoid")); //Ouputlayer with 10 outputs,...model.Compile(optimizer: "sgd", loss: "categorical_crossentropy", metrics: new string[] { "accuracy" }); //we have a crossentropy as prediction //and want to see as well the //accuracy metric.var X_train = x_train.reshape(60000, 784); //this is actually very important. //C# works with pointers, //so if you have to reshape (again) //the function for the correct //processing, you need to write this //to a different varvar X_test = x_test.reshape(10000, 784);model.Fit(X_train, y_train, batch_size, epochs, 1); //now, we set the data to //the model with all the //arguments (x and y data, //batch size...the '1' is //just verbose=1Console.WriteLine("---------------------");Console.WriteLine(X_train.shape);Console.WriteLine(X_test.shape);Console.WriteLine(y_train[0]);Console.WriteLine(y_train[1]); //some outputs...you can play with themvar y_train_pred = model.Predict(X_train); //prediction on the train dataConsole.WriteLine(y_train_pred);model.Evaluate(X_test.reshape(-1, 784), y_test); //-1 tells the code that //it can figure out the size of //the array by itself}private byte[] openDatas(string path, int skip) //just the open Data function. //As I mentioned, I did not work //with unzip stuff, you have //to unzip the data before //by yourself{var file = File.ReadAllBytes(path).Skip(skip).ToArray();return file;}//Hint: First, I was working by opening the data locally and //I wanted to figure it out how to present data to the arrays. //So you can use something like this and call this within the TrainModel() function://x_train = openDatas(@"PATH\OF\YOUR\DATAS\train-images-idx3-ubyte", 16);//y_train = openDatas(@"PATH\OF\YOUR\DATAS\train-labels-idx1-ubyte", 8);//x_test = openDatas(@"PATH\OF\YOUR\DATAS\t10k-images-idx3-ubyte", 16);//y_test = openDatas(@"PATH\OF\YOUR\DATAS\t10k-labels-idx1-ubyte", 8);}
}
使用此代碼將對您自己的模型進行首次培訓。對我來說,這是我進入Keras.NET的第一步,我想分享這一點,因為Keras.NET的例子并不多。也許您可以將其用于您的目的。
https://www.codeproject.com/Articles/5286497/Starting-with-Keras-NET-in-Csharp-Train-Your-First
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态