【发布时间】:2019-04-19 04:17:18
【问题描述】:
我正在制作一个卷积网络来预测 3 类图像,猫、狗和人。我对它进行了训练和训练,但是当我通过猫图像进行预测时,它总是给出错误的输出。我尝试了其他猫的照片,但结果没有改变。人和狗都没有问题,只有猫。
cnn = Sequential()
#------------------- Convolução e Pooling
cnn.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
cnn.add(Dropout(0.5))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(32, (3, 3), activation = 'relu'))
cnn.add(Dropout(0.5))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(64, (3, 3), activation = 'relu'))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
cnn.add(Conv2D(64, (3, 3), activation = 'relu'))
cnn.add(Dropout(0.5))
cnn.add(MaxPooling2D(pool_size = (2, 2)))
#Full connection
cnn.add(Flatten())
cnn.add(Dense(units = 128, activation = 'relu'))
cnn.add(Dense(units = 4, activation = 'softmax'))
# Compiling the CNN
cnn.compile(optimizer = OPTIMIZER, loss = 'categorical_crossentropy', metrics = ['accuracy'])
filepath="LPT-{epoch:02d}-{loss:.4f}.h5"
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
callbacks_list = [checkpoint]
12000 张训练图像 - 3000 张测试图像
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('data/train',
target_size = tgt_size,
batch_size = batch_size,
class_mode = 'categorical')
test_set = test_datagen.flow_from_directory('data/test',
target_size = tgt_size,
batch_size = batch_size,
class_mode = 'categorical')
cnn.fit_generator(training_set,
#steps_per_epoch = 12000,
steps_per_epoch = nb_train_samples // batch_size,
epochs = EPOCHS,
verbose = VERBOSE,
validation_data = test_set,
validation_steps = nb_validation_samples // batch_size,
callbacks = callbacks_list)
我最好的训练结果:
loss: 0.6410 - acc: 0.7289 - val_loss: 0.6308 - val_acc: 0.7293
类索引:
{'.ipynb_checkpoints': 0, 'cats': 1, 'dogs':2, 'person':3}
(我无法删除那个 ipynb 文件夹)
预测:
pred1 = 'single_prediction/ct.jpg'
pred2 = 'single_prediction/ps.jpg'
pred3 = 'data/single_prediction/dg.jpg'
test_img = image.load_img(pred1, target_size = tgt_size)
test_img = image.img_to_array(test_img)
test_img = np.expand_dims(test_img, axis = 0)
pred = new_model.predict(test_img)
print(pred)
if pred[0][1] == 1:
print('It is a cat!')
elif pred[0][2] == 1:
print('It is a dog!')
elif pred[0][3] == 1:
print('It is a Person!')
猫图像的输出:
[[0.000000e+00 0.000000e+00 8.265931e-34 1.000000e+00]]
我已经尝试过: 更改层数(添加和删除),增加时期,减少批次......我也尝试使用 np.argmax()。有人可以在这里给我点灯吗?
更新:我使用命令 shutil.rmtree() 删除了 jupyter notebook 的隐藏文件夹,并训练了大约 40 个 epoch,直到它停止改进。最后,我重新调整了预测图像的比例并得到了正确的结果。
test_img = image.img_to_array(test_img)/255
感谢大家的帮助!
【问题讨论】:
-
看起来欠拟合。所以请考虑首先提高模型的性能。您可以添加更多层,增加每个层的大小,并删除丢失。只有当您发现发生过拟合时,您才能开始添加 dropout 或限制模型的复杂性。
-
您不是通过除以 255 来重新缩放图像,而生成器会执行此操作(您指定了重新缩放值)。
-
您说您有 3 个类,但您的网络在输出端有 4 个节点。你的问题是 4 级吗?
-
我添加了更多层并更改了一些,val_acc 运行良好...让我们看看!
-
@MatiasValdenegro 我应该在哪里重新调整比例?
标签: python keras conv-neural-network