ML.NET在不久前发行了1.0版本,在考虑这一新轮子的实际用途时,最先想到的是其能否调用已有的模型,特别是最被广泛使用的Tensorflow模型。于是在查找了不少资料后,有了本篇示例。希望可以有抛砖引玉之功。
环境
Tensorflow 1.13.1
Microsoft.ML 1.0.0
Microsoft.ML.TensorFlow 0.12.0
netcoreapp2.2
训练模型
这里为了方便,利用Keras的API减少所需的代码。
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)
model.save('model.h5')
得到的模型精度在98%以上,不错的结果。
检验模型
加载已训练的模型,用某一测试数据验证结果。
with CustomObjectScope({'GlorotUniform': glorot_uniform()}):
model = load_model('model.h5')
data = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.027450980392156862, 0.09411764705882353, 0.5019607843137255, 0.5450980392156862, 0.5411764705882353, 0.7490196078431373, 0.7058823529411765, 0.9921568627450981, 0.7490196078431373, 0.5411764705882353, 0.18823529411764706, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.16862745098039217, 0.1843137254901961, 0.47058823529411764, 0.7294117647058823, 0.9882352941176471, 0.9882352941176471, 0.9921568627450981, 0.9882352941176471, 0.9882352941176471, 0.9882352941176471, 0.9882352941176471, 0.9921568627450981, 0.9882352941176471, 0.8901960784313725, 0.11372549019607843, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.07450980392156863, 0.6431372549019608, 0.9647058823529412, 0.9921568627450981, 0.9882352941176471, 0.9882352941176471, 0.8901960784313725, 0.7176470588235294, 0.7215686274509804, 0.6352941176470588, 0.27058823529411763, 0.27058823529411763, 0.27058823529411763, 0.30980392156862746, 0.8901960784313725, 0.9882352941176471, 0.17647058823529413, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.27450980392156865, 0.9882352941176471, 0.9882352941176471, 0.9921568627450981, 0.9215686274509803, 0.3019607843