C#使用keras训练模型onnx

nb_epoch = 20     # number of epochs to train on
batch_size = 256  # training batch size
filepath = 'weights/mymodel_P1_1024.h5'


model = cldnn.CLDNNLikeModel(None,input_shape=[256,2],classes = len(classes))  
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')
model.summary()
def scheduler(epoch):
    print("epoch({}) lr is {}".format(epoch, K.get_value(model.optimizer.lr)))
    return K.get_value(model.optimizer.lr)
reduce_lr = LearningRateScheduler(scheduler)
history = model.fit(X_train,
    Y_train,
    batch_size=batch_size,
    epochs=nb_epoch,
    verbose=1,
    validation_data=(X_test, Y_test),
    callbacks = [reduce_lr,
                keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='auto'),
                keras.callbacks.ReduceLROnPlateau(monitor='val_loss',factor=0.5,verbose=1,patince=len(classes),min_lr=0.000001)
                ])

model = keras.models.load_model(filepath=filepath)

test_Y_hat = model.predict(X_test, batch_size=batch_size)

1、python端 

首先,使用python进行模型训练,如果不使用C# 程序,则直接使用

keras.models.load_model进行模型的加载即可。

如果模型需要在C#程序中运行,则在pycharm中import tf2onnx,或者cmd到python目录路径下,输入pip install tf2onnx,安装成功后在pycharm的终端里输入:python -m tf2onnx.convert --saved-model .\models --output .\models\onnx\model.onnx --opset 7

其中.\models\onnx\model.onnx是onnx的保存路径。

2、C#端 

新建一个C# 控制台应用项目,右键依赖包,选择NunGet程序包,安装Microsoft.ML.OnnxRuntime依赖包:

C#使用keras训练模型onnx_第1张图片

 然后输入以下代码:

using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;

namespace onnx.C
{
    class Program
    {
        public static void Main(string[] args)
        {
            //input
            Tensor input = new DenseTensor(new[] { 1, 960, 2 });
            for (int y = 0; y < 960; y++)
            {
                input[0, y, 0] = 0;
                input[0, y, 1] = 0;
            }

            var inputs = new List
                    {
                        NamedOnnxValue.CreateFromTensor("conv1_input", input)
                    };
            //run interfence
            string[] classesNames = new string[] { "dog", "cat", "fish", "flower", "tree" };

            using var session = new InferenceSession("./assets/Model/model.onnx");
            using IDisposableReadOnlyCollection results = session.Run(inputs);
            // Postprocess to get predictions
            var resultsArray = results.ToArray();
            float[] boxes = resultsArray[0].AsEnumerable().ToArray();
            var i_Pos = 0;
            var value = boxes[0];
            for (var i = 1; i < boxes.Length; ++i)
            {
                var _value = boxes[i];
                if (_value.CompareTo(value) > 0)
                {
                    value = _value;
                    i_Pos = i;
                }
            }
            float count = 0;
            for (int i = 0; i < boxes.Length; i++)
            {
                count += boxes[i];
            }
            var Confidence = boxes[i_Pos]/count;
            Console.WriteLine("recognition result is:"+classesNames[i_Pos]);
            Console.WriteLine("confidence is:"+Confidence);

        }
    }
}

其中"conv1_input"是神经网络输入层的取名,是在python中设置好的:

x = Conv1D(filters=64, kernel_size=kernel_size, padding='same', activation='relu',kernel_initializer='glorot_uniform',
           name='conv{}'.format(index + 1))(input) #name = "conv1_input"

你可能感兴趣的:(python,c#)