Я обучил эту модель vgg-19 и теперь должен предсказать одно изображение. Я пробовал что-то вроде этого: Невозможно предсказать метку для одного изображения с VGG19 в 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]))
Edit (1):
Вот так выглядит ввод данных в модель:
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] массив?