部署CNN:训练和测试准确性高,但预测准确性低

时间:2020-07-16 20:11:25

标签: python tensorflow machine-learning keras deep-learning

仅从ML开始,创建了我的第一个CNN来检测面部图像的方向。在2套不同的1000张图片(128x128 RGB)上,我得到的培训和测试准确性高达96-99%。但是,当我自己根据测试集预测图像时,模型很少会正确预测。我认为在测试和预测期间将数据加载到模型中的方式一定有所不同。这是我将数据加载到模型中以进行训练和测试的方式:

datagen = ImageDataGenerator()
train_it = datagen.flow_from_directory('twoThousandTransformed/', class_mode='categorical', batch_size=32, color_mode="rgb", target_size=(64,64))
val_it = datagen.flow_from_directory('validation/', class_mode='categorical', batch_size=32, color_mode="rgb", target_size=(64,64))
test_it = datagen.flow_from_directory('test/', class_mode='categorical', batch_size=32, color_mode='rgb', target_size=(64,64))

这是我加载图像进行预测的方式:

image_path='inputPicture/02001.png'
image = tf.keras.preprocessing.image.load_img(image_path)
input_arr = keras.preprocessing.image.img_to_array(image)
reshaped_image = np.resize(input_arr, (64,64,3))
input_arr = np.array([reshaped_image]) 
predictions = model.predict(input_arr)
print(predictions)
classes = np.argmax(predictions, axis = 1)
print(classes)

ImageDataGenerator处理图像的方式必须与我在预测中的方式有​​所不同。你们都可以帮忙吗?谢谢!

编辑:以下是我的模型

imageInput = Input(shape=(64,64,3))
conv1 = Conv2D(128, kernel_size=16, activation='relu')(imageInput)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
conv2 = Conv2D(64, kernel_size=12, activation='relu')(pool1)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
conv3 = Conv2D(64, kernel_size=4, activation='relu')(pool2)
pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
flat = Flatten()(pool3)
hidden1 = Dense(16, activation='relu')(flat)
hidden2 = Dense(16, activation='relu')(hidden1)
hidden3 = Dense(10, activation='relu')(hidden2)
output = Dense(4, activation='softmax')(hidden3)
model = Model(inputs=imageInput, outputs=output)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(train_it, steps_per_epoch=16, validation_data=val_it, validation_steps=8, epochs=25)
print('here we go!')
_, accuracy = model.evaluate(test_it)
print('Accuracy: %.2f' % (accuracy*100))

1 个答案:

答案 0 :(得分:0)

您可以尝试做的一件事是复制所选图像,使其类似于训练模型时使用的批次大小。另外,由于训练精度高,因此您的模型似乎过拟合。因此,如果第一件事无法解决,请尝试添加Dropout或减少网络中的层数。