Python 如何使用Keras中保存的模型来预测和分类图像?
我用Keras训练了一个模型手位置分类器,最后用代码保存了模型(model.save('model.h5')) 现在我要用这个模型预测一幅图像,它可行吗?如果是,你能给我举几个例子吗?Python 如何使用Keras中保存的模型来预测和分类图像?,python,tensorflow,machine-learning,keras,artificial-intelligence,Python,Tensorflow,Machine Learning,Keras,Artificial Intelligence,我用Keras训练了一个模型手位置分类器,最后用代码保存了模型(model.save('model.h5')) 现在我要用这个模型预测一幅图像,它可行吗?如果是,你能给我举几个例子吗? PS:我的数据作为CSV文件提供首先,您必须使用load\u model功能导入保存的模型 from keras.models import load_model model = load_model('model.h5') 在预测新给定输入的结果之前,必须调用compile方法 classifier.comp
PS:我的数据作为CSV文件提供首先,您必须使用
load\u model
功能导入保存的模型
from keras.models import load_model
model = load_model('model.h5')
在预测新给定输入的结果之前,必须调用compile
方法
classifier.compile(loss='your_loss', optimizer='your_optimizer', metrics=['your_metrics'])
编译之后,您就可以处理新图像了
from keras.preprocessing import image
test_image= image.load_img(picturePath, target_size = (img_width, img_height))
test_image = image.img_to_array(test_image)
test_image = numpy.expand_dims(test_image, axis = 0)
test_image = test_image.reshape(img_width, img_height)
result = model.predict(test_image)
当我运行@Mihai Alexandru Ionut发布的代码时
#我们图像的尺寸
img_宽度,img_高度=313220
#加载我们保存的模型
模型=负荷\模型('hmodel.h5')
sgd=optimizers.sgd(lr=0.01,衰减=1e-6,动量=0.9,nesterov=True)
compile(loss='classifical_crossentropy',optimizer=sgd,metrics=['accurity','mse'])
test_image=image.load_img('/Images/1.jpg',target_size=(img_宽度,img_高度))
test_image=image.img_到_数组(test_image)
测试图像=np。展开图像(测试图像,轴=0)
result=model.predict(test_image)
这里我提供了一个将tensorflow.keras模型保存到当前目录下的model_path
文件夹的示例。这在最新的tensorflow(TF2.0.0rc2)中运行良好。如果在不久的将来有任何更改,我将更新此说明。按照下面的示例代码,更改数据加载、形状等
保存和加载整个模型
model.save
方法保存所有内容:
- 权重值
- 模型的体系结构
- 优化器配置
- 培训配置(传递给编译的内容)
当
model.save
保存培训配置时,我们不需要在使用keras.models.load\u model
还原后编译模型。首先感谢您的回复,在我的模型输入中,我应该调整图像大小吗?当我运行代码时,我得到以下错误:python2.7/site-packages/keras/preprocessing/image.py“,第360行,在加载模式中”(“无法导入PIL.Image.”导入错误:无法导入PIL.Image。使用array\u to\u img
需要PIL。而且PIL已经安装。您有什么建议吗?@Jennifer95,array\u to\u img是keras的一种方法。预处理是@Mihai,我已经通过安装“枕头”修复了错误^^^@Jennifer95,为了帮助其他人,请接受答案。你可以使用重塑
方法。看看我更新的答案。我添加了一段代码“test_image=test_image.reformate(img_width,img_height)”,现在得到这个错误值错误:无法将大小为206580的数组重塑为形状(313220)PS 206580=3*313*220我试着运行代码“x=scipy.misc.imread('/Images/1.jpg').shape”的图片,我得到了这个结果(313220,3)。你有什么建议吗?试试这个:test\u image=test\u image.reshave(img\u宽度,img\u高度,3)
我尝试了它,但出现了以下错误:ValueError:检查时出错:预期密集\u 1\u输入为二维,但得到了具有形状的数组(313、220、3)
import tensorflow as tf
from tensorflow import keras
mnist = tf.keras.datasets.mnist
#import data
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# create a model
def create_model():
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)
])
# compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
# Create a basic model instance
model=create_model()
model.fit(x_train, y_train, epochs=1)
loss, acc = model.evaluate(x_test, y_test,verbose=1)
print("Original model, accuracy: {:5.2f}%".format(100*acc))
# Save entire model to a HDF5 file
model.save('./model_path/my_model.h5')
# Recreate the exact same model, including weights and optimizer.
new_model = keras.models.load_model('./model_path/my_model.h5')
loss, acc = new_model.evaluate(x_test, y_test)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))