我用Keras训练了一个模型手位置分类器,最后我用代码保存了模型(model.save('model.h5')) 现在我想用这个模型预测图像是否可行?如果是,你可以给我一些例子吗? PS:我的数据以CSV文件形式提供
答案 0 :(得分:1)
首先,您必须使用load_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)
答案 1 :(得分:0)
当我运行@Mihai Alexandru-Ionut的代码发布时
# dimensions of our images
img_width, img_height = 313, 220
# load the model we saved
model = load_model('hmodel.h5')
sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy','mse'])
test_image= image.load_img('/Images/1.jpg',target_size = (img_width, img_height))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = model.predict(test_image)
我收到以下错误:第_ 113行,在_standardize_input_data中 'with shape'+ str(data_shape)) ValueError:检查时出错:期望的dense_1_input有2个维度,但得到的数组有形状(1,313,220,3) 可以somoeone帮助我解决这个错误
答案 2 :(得分:0)
在这里,我提供了一个将tensorflow.keras模型保存到当前目录下的X
文件夹中的示例。这与最新的tensorflow(TF2.0.0rc2)一起很好地工作。如果近期有任何更改,我将更新此描述。请遵循以下示例代码,并更改数据加载,形状等。
model_path
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))
方法可保存所有内容:
由于model.save
保存了训练配置,因此使用model.save
恢复后,我们无需编译模型