我有一个小例子(来自互联网),使用移动网络对两种鸟类进行分类。我不确定这是什么问题,但是该模型似乎与预期的鸟类图像类型配合得很好,但是对于随机图像却非常糟糕。例如,我可以传递一个人的图像并以100%的准确度进行响应,以将其归类为两种鸟类中的一种。
我在python 3.5中使用了keras和tensorflow
base_model=MobileNet(weights='imagenet', include_top=False)
x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(2,activation='softmax')(x) #final layer with softmax activation
model=Model(inputs=base_model.input,outputs=preds)
for layer in model.layers:
layer.trainable=False
for layer in model.layers[:20]:
layer.trainable=False
for layer in model.layers[20:]:
layer.trainable=True
batch_size=16
train_data_dir = 'downloads'
img_height = 64
img_width = 64
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input,
validation_split=0.30) # set validation split
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
color_mode='rgb',
class_mode='categorical',
shuffle=True,
subset='training') # set as training data
validation_generator = train_datagen.flow_from_directory(
train_data_dir, # same directory as training data
target_size=(img_height, img_width),
batch_size=batch_size,
color_mode='rgb',
class_mode='categorical',
shuffle=False,
subset='validation') # set as validation data
model.compile(optimizer=Adam(lr=0.0001),loss='categorical_crossentropy',metrics=['accuracy'])
step_size_train= train_generator.n//train_generator.batch_size
n_epochs = 20
history = model.fit_generator(
generator = train_generator,
steps_per_epoch = train_generator.samples // batch_size,
validation_data = validation_generator,
validation_steps = validation_generator.samples // batch_size,
epochs = n_epochs)
我期望该模型将以很小的百分比预测随机图像,但是事实并非如此,因此我确定我正在使用错误的参数来训练模型。如果有人可以提供一些帮助以改进模型或了解我的错误,我将不胜感激