目录
介绍
背景
使用代码
兴趣点
介绍由于机器学习已变得非常流行,因此使用Keras和/或后端Tensorflow这样的开源SDK,Python语言也再次变得流行(与预测相反,Python将在未来五年内消失)。作为.NET环境的研究工程师,它给我带来了很多问题,我在那里使用Python,而我的主要重点是C#。当然,您可以以某种方式将Python代码嵌入到您的应用程序中(即,在.NET应用程序中运行Python脚本),但这并没有使它变得更好。
我认为,另一个解决方案是使用IronPython,这是一个可以直接运行Python代码的SDK,但是
- 它仍在使用Python 2.7(在2020年终止支持),并且对Python 3的支持发音类似于“请勿使用!”,好吧...
- 它不支持numpy之类的许多其他软件包,这对于进行机器学习是必不可少的
- 解决所有这些问题非常困难...只是不要将其用于此类目的。
因此,我开始研究新的解决方案,以及如何避免在.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 keras
pip 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();
}
}
}
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 epoch
int num_classes = 10; //We got 10 outputs since
//we can predict 10 different labels seen on the
//dataset: https://github.com/zalandoresearch/fashion-mnist#labels
int 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 dimensions
int img_rows = 28, img_cols = 28;
// the data, split between train and test sets
var ((x_train, y_train), (x_test, y_test)) =
FashionMNIST.LoadData(); // Load the datasets from
// fashion MNIST, Keras.Net implement this directly
x_train.reshape(-1, img_rows, img_cols).astype(np.float32); //ByteArray needs
//to be reshaped to fit the dimmensions of the y arrays
y_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 not
var 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 activationfunction
model.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 var
var 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=1
Console.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 them
var y_train_pred = model.Predict(X_train); //prediction on the train data
Console.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