我已经训练了vgg-19模型,现在需要预测单个图像。我已经尝试过类似的操作:Cannot predict the label for a single image with VGG19 in Keras
我在模型末尾添加了它,但是它不起作用。
base_model = VGG19(weights=None, include_top=False, pooling='avg', input_shape=(LEFT, RIGHT, 3))
# add a global spatial average pooling layer
x = base_model.output
x = Dense(1024, activation='relu')(x)
# and a logistic layer -- let's say we have 2 classes
predictions = Dense(2, activation='softmax')(x)
# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)
# Print the layers
for i, layer in enumerate(model.layers):
print(i, layer.name, layer.output_shape)
plot_model(model, show_shapes=True, to_file=MODELDIR + IDENTNAME + '_model.png')
# we chose to train the top inception blocks, i.e. we will freeze
# the first 5 layers and unfreeze the rest:
for layer in model.layers[:10]:
layer.trainable = True
for layer in model.layers[10:]:
layer.trainable = True
# we need to recompile the model for these modifications to take effect
from keras.optimizers import Adam
optimizer = Adam(lr=0.00008, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=True)
model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit_generator(generator(BATCHSIZE, DATADIR), steps_per_epoch=DATASTEPS,
validation_data=generator(NUMVALIDATIONFILES, VALIDATIONDIR), validation_steps=1,
epochs=EPOCHS, verbose=1, class_weight={0: 1, 1: 1})
# Save model and weights....
# serialize model to YAML
model_yaml = model.to_yaml()
with open(MODELDIR + IDENTNAME + '_model.yaml', "w") as yaml_file:
yaml_file.write(model_yaml)
# serialize weights to HDF5
model.save_weights(MODELDIR + IDENTNAME + '_weights.h5')
print("Saved model to disk")
#######predict one image#####
from keras.preprocessing.image import load_img
image = load_img('picture.png', target_size=(64, 64))
from keras.preprocessing.image import img_to_array
image = img_to_array(image)
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
from keras.applications.vgg19 import preprocess_input
image = preprocess_input(image)
yhat = model.predict(image)
# create a list containing the class labels
class_labels = ['class1', 'class2']
# find the index of the class with maximum score
pred = np.argmax(class_labels, axis=-1)
# print the label of the class with maximum score
print(class_labels[pred[0]])
最后一行产生错误:标量变量的索引无效。如何更正此错误?图片尺寸应该是问题吗?它实际上有4个维度:r,g,b和透明度?当我准备图片(在模型之前)时,请执行以下步骤:
batch_features[i, :, :, :] = imageio.imread(t)[:, :, :3]
即使是单张图像,这也是我要做的事情吗?
现在,导入单个图像的代码如下:
from keras.preprocessing.image import load_img
image = load_img('picture.png', target_size=(64, 64, 3))
np.expand_dims(image, axis=0)
from keras.preprocessing.image import img_to_array
image = img_to_array(image)
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
from keras.applications.vgg19 import preprocess_input
image = preprocess_input(image)
yhat = model.predict(image)
# create a list containing the class labels
class_labels = ['class1', 'class2']
# find the index of the class with maximum score
pred = np.argmax(class_labels, axis=-1)
# print the label of the class with maximum score
print(class_labels[pred[0]])
应该不是一个问题:
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
这是将数据输入模型的样子:
for i, t in enumerate(target_b):
batch_features[i, :, :, :] = imageio.imread(t)[:, :, :3]
batch_labels[i, :] = np.array([1, 0]) if "_avalanche_" in t else np.array([0, 1])
我想必须将单个图像的格式更改为[1,0]数组吗?