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