我想问一个问题,关于我几天前就摔断了头的模型... 我正在尝试编写CNN模型来预测2类之间的结果(类似于猫或狗的问题)。 我的代码可以识别“训练”和“验证”文件夹中的图片,也可以识别“测试”文件夹中要预测的图片,但是所有预测的图片的结果几乎相同,并且准确性很低(0.49)(附有图片)。 photo_of_the_results_from_sample_data
我尝试在adam,SGD,RMSprop之间更改优化器 我试图将损失更改为稀疏类别 我试图将指标更改为混淆矩阵(由于某种原因,它甚至无法识别) 没有任何作用......
有人可以帮我修复我的代码吗? 非常感谢您!
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D,
MaxPooling2D
from keras.optimizers import adam, SGD, RMSprop
from keras.preprocessing.image import ImageDataGenerator
# 1 - Load data
train_dataset = "\\Pictures_Dogs_DataSet\\Train1/"
validation_dataset="\\Pictures_Dogs_DataSet\\Validation1/"
test_dataset = "\\Pictures_Dogs_DataSet\\Test/"
# 2 - Create network layers
image_width = 200
image_height = 200
model = Sequential()
# add convolutional layer (CNN)
# 32 X 32 pixel matrix
# 3 layars (RGB)
# 3 X 3 sliding matrix
# a pixel value for each colour is between 0-255
model.add(Conv2D(filters=32,kernel_size=(3,3),input_shape=
(image_width,image_height,3),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
# Add another block for more abstract features
model.add(Conv2D(32,(3,3), input_shape=(image_width,
image_height,3),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
# Add another block for more abstract features
model.add(Conv2D(64,(3,3), input_shape=(image_width,
image_height,3),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
# Add another block for more abstract features
model.add(Conv2D(128,(3,3), input_shape=(image_width,
image_height,3),activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
# Let's DropOut some connections to avoid over-fitting.
model.add(Flatten())
model.add(Dense(128,activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(32,activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(1,activation='sigmoid'))
# Using the prediction model
sgd = SGD(lr=0.001)
model.compile(optimizer=sgd,loss='binary_crossentropy',
metrics=['accuracy'])
# used to rescale the pixel values from [0, 255] to [0, 1]
interval
datagen =ImageDataGenerator(rescale=1./255)
# automatically retrieve images and their classes for train
and validation sets
train_generator = datagen.flow_from_directory(
train_dataset,
target_size=(image_width, image_height),
batch_size=32,
class_mode='binary')
validation_generator = datagen.flow_from_directory(
validation_dataset,
target_size=(image_width, image_height),
batch_size=32,
class_mode='binary')
# 3 - Train
model.fit_generator(
train_generator,
steps_per_epoch=10,
epochs=1,
#just 1 epoch to practice and make sure it works#
validation_data=validation_generator,
validation_steps=5)
#evaluate the accuracy of the model
model.evaluate_generator(validation_generator,verbose=0)
#save modules
#model.save('model.h5')
# 5 - predict
test_generator =datagen.flow_from_directory(
directory=test_dataset,
target_size=(image_width,image_height),
class_mode=None,
batch_size=32)
print(model.predict_generator(test_generator))