我正在阅读有关 Keras 的文档以及 StackOverFlow 上以前的问题和回复。目前,这是我到目前为止所拥有的:
#Creating base pre-trained model (Default Input Size for ResNet50 is (299, 299))
base_model = InceptionV3(weights = 'imagenet', include_top = False, input_shape = (299, 299, 3))
#Adding a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
#Adding a fully-connected dense layer
x = Dense(1024, activation = 'relu')(x)
#Adding a logistic layer - We have 2 classes: Cats and Dogs
predictions = Dense(2, activation = 'softmax')(x)
#Model to be trained
model = Model(inputs = base_model.input, outputs = predictions)
#First trains only the top layers
#Freeze all convolutional ResNet50 layers
for layer in base_model.layers:
layer.trainable = False
#Compile the model
model.compile(optimizer = 'rmsprop', loss = 'sparse_categorical_crossentropy')
#Train the model on the new data
train_datagen = ImageDataGenerator()
train_generator = train_datagen.flow_from_directory("./data/train",
target_size = (299, 299),
batch_size = 25,
class_mode = 'binary')
model.fit_generator(train_generator, steps_per_epoch = 10)
#Train top 2 inception blocks by freezing first 249 layers and unfreezing the rest
for layer in model.layers[:249]:
layer.trainable = False
for layer in model.layers[249:]:
layer.trainable = True
#Now to recompile the model for modifications to take effect, use SGD
model.compile(optimizer = SGD(lr = 0.0001, momentum = 0.9), loss = 'sparse_categorical_crossentropy')
#Train model again, fine-tuning top 2 inception blocks alongside top Dense layers
model.fit_generator(train_generator, steps_per_epoch = 10)
#Test model
imges = glob.glob('./test/*.jpg')
for fname in imges:
img_path = fname
img = image.load_img(img_path, target_size=(299, 299))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
pred = model.predict(x)
print('Predicted:', decode_predictions(pred, top=3)[0])
我目前收到一条错误消息,提示“decode_predictions 中的第 82 行,值错误:'decode_predictions' 需要一批预测(即二维形状数组(样本,1000))。找到形状为 (1, 2) 的数组"
有什么我忘了做的吗?我目前无计可施。任何和所有的帮助将不胜感激。先感谢您