0.写在前面:
作者基于tensorflow 2.X,利用自在的keras接口完成了神经网络的训练,现在想把模型跑在c#端,但使用TensorFlowsharp好像还是tensorflow 1.X的语言风格,改动起来较为困难。所以想寻找c#接口的keras。经过一番搜索,找到两个资源,分别为keras-sharp(https://github.com/tcmxx/keras-sharp)和Keras.NET(https://github.com/SciSharp/Keras.NET/),keras-sharp看起来还久没有维护和更新了,所以放弃,尝试使用Keras.NET。
1.依赖项的安装:
- Python 2.7 - 3.7, Link: https://www.python.org/downloads/
- Install keras, numpy and one of the backend (Tensorflow/CNTK/Theano). Please see on how to configure: https://keras.io/backend/
我是安装的python3.7.0(别忘了点击添加到环境变量),

python3.7.0安装完毕之后使用pip命令依次安装numpy,tensorflow,keras即可。这里注意:安装之后最好升级一下pip,
python -m pip install --upgrade pip
然后我是安装的tensorflow2.1 cpu版本,使用:
pip install tensorflow-cpu==2.1.0 -i https://mirrors.aliyun.com/pypi/simple
2.Keras.NET的安装
2.1 通过Nuget命令行安装
Install-Package Keras.NET
2.2 通过Nuget界面安装
安装完成之后自动添加了Keras,Numpy.Bare,Python.Runtime等
3.测试
拿着官方的minist例程测试一下,代码如下:
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 Keras.Datasets;
using System;
using System.Collections.Generic;
using System.Text;
using Numpy;
using K = Keras.Backend;
using Keras;
using Keras.Models;
using Keras.Layers;
using Keras.Utils;
using Keras.Optimizers;
using System.IO;
namespace keras.net
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void test()
{
int batch_size = 200;
int num_classes = 10;
int epochs = 10;
// input image dimensions
int img_rows = 28, img_cols = 28;
Shape input_shape = null;
// the data, split between train and test sets
var ((x_train, y_train), (x_test, y_test)) = MNIST.LoadData();
if (K.ImageDataFormat() == "channels_first")
{
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols);
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols);
input_shape = (1, img_rows, img_cols);
}
else
{
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1);
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1);
input_shape = (img_rows, img_cols, 1);
}
x_train = x_train.astype(np.float32);
x_test = x_test.astype(np.float32);
x_train /= 255;
x_test /= 255;
Console.WriteLine("x_train shape: " + x_train.shape);
Console.WriteLine(x_train.shape[0] + " train samples");
Console.WriteLine(x_test.shape[0] + " test samples");
// convert class vectors to binary class matrices
y_train = Util.ToCategorical(y_train, num_classes);
y_test = Util.ToCategorical(y_test, num_classes);
// Build CNN model
var model = new Sequential();
model.Add(new Conv2D(32, kernel_size: (3, 3).ToTuple(),
activation: "relu",
input_shape: input_shape));
model.Add(new Conv2D(64, (3, 3).ToTuple(), activation: "relu"));
model.Add(new MaxPooling2D(pool_size: (2, 2).ToTuple()));
model.Add(new Dropout(0.25));
model.Add(new Flatten());
model.Add(new Dense(128, activation: "relu"));
model.Add(new Dropout(0.5));
model.Add(new Dense(num_classes, activation: "softmax"));
model.Compile(loss: "categorical_crossentropy",
optimizer: new Adadelta(), metrics: new string[] { "accuracy" });
model.Fit(x_train, y_train,
batch_size: batch_size,
epochs: epochs,
verbose: 1,
validation_data: new NDarray[] { x_test, y_test });
model.Save("model.h5");
model.SaveTensorflowJSFormat("./");
var score = model.Evaluate(x_test, y_test, verbose: 0);
Console.WriteLine("Test loss:" + score[0]);
Console.WriteLine("Test accuracy:" + score[1]);
}
private void button1_Click(object sender, EventArgs e)
{
test();
}
}
}
程序会下载mnist数据集,非常慢又经常失败,从控制台的输出信息可以找到下载原网址如下:
https://s3.amazonaws.com/img-datasets/mnist.npz
我们可以随便从网上找一个用于keras的mnist数据集下载即可,我是用的这个https://download.csdn.net/download/lsldd/11502401
下载完成之后将mnist.npz文件放到keras数据集路径下(我的电脑是C:\Users\Administrator\.keras\datasets)
10个epoch之后损失和准确率如下:
注意:出现错误时,可以先试试解决方案平台改成X64,还不行的话删除所有依赖(删干净!)重新安装,不要使用anaconda安装依赖包!
ref:
https://blog.csdn.net/kinfey/article/details/99691593
https://scisharp.github.io/Keras.NET/index.html
https://github.com/SciSharp/Numpy.NET