代码:
#Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
import keras.optimizers as optimizers
#Initialising the CNN
classifier = Sequential()
#Convolution Layer
classifier.add(Conv2D(32, (3, 3), input_shape = (32, 32, 3), activation = 'relu'))
#Max Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
#Flattening
classifier.add(Flatten())
#Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
# Compiling the CNN
sgd = optimizers.SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
classifier.compile(loss='mean_squared_error', optimizer=sgd, metrics = ['accuracy'])
#Fitting the CNN to the images
from keras.preprocessing.image import ImageDataGenerator
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('Oranges/training_set',
target_size = (32, 32),
batch_size = 32,
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('Oranges/test_set',
target_size = (32, 32),
batch_size = 32,
class_mode = 'binary')
classifier.fit_generator(training_set,
steps_per_epoch = 800,
epochs = 25,
validation_data = test_set,
validation_steps = 62.5)
classifier.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
输入大约是200个属于5个类别(蔬菜)的图像。虽然我让它训练整个过程(800步* 30个时期,批量大小为32),但仍然保持在18-19%左右。我试着弄乱优化器设置(lr,decay),但似乎没有什么对我有用。我有什么想法吗?