keras 构建CNN进行小样本集图像分类

keras 构建CNN进行小样本集图像分类

代码:
`
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

model = Sequential()
model.add(Conv2D(32, (3, 3),padding=‘same’,input_shape=(224, 224,3)))
model.add(Activation(‘relu’))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3),padding=‘same’))
model.add(Activation(‘relu’))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3),padding=‘same’))
model.add(Activation(‘relu’))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(64))
model.add(Activation(‘relu’))
model.add(Dropout(0.5))
model.add(Dense(3))
model.add(Activation(‘sigmoid’))

model.compile(loss=‘categorical_crossentropy’,
optimizer=‘rmsprop’,
metrics=[‘accuracy’])
batch_size = 16

train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
directory=“D:/PycharmProjects/Untitled Folder/GRAZ-02/train”, # this is the target directory
target_size=(224, 224), # all images will be resized to 150x150
batch_size=batch_size,
class_mode=‘categorical’) # since we use binary_crossentropy loss, we need binary labels

validation_generator = test_datagen.flow_from_directory(
directory=“D:/PycharmProjects/Untitled Folder/GRAZ-02/val”,
target_size=(224, 224),
batch_size=batch_size,
class_mode=‘categorical’)

history_t = model.fit_generator(
train_generator,
steps_per_epoch=479, # batch_size
epochs=50,
validation_data=validation_generator,
validation_steps=479 )#batch_size

def plot_training(history):
acc = history.history[‘acc’]
val_acc = history.history[‘val_acc’]
loss = history.history[‘loss’]
val_loss = history.history[‘val_loss’]
epochs = range(len(acc))

plt.plot(epochs, acc, ‘b’)
plt.plot(epochs, val_acc, ‘r’)
plt.title(‘Training and validation accuracy’)
pyplot.ylabel(‘accuracy’)
pyplot.xlabel(‘epoch’)
pyplot.legend([‘train’, ‘validation’], loc=‘upper right’)

plt.figure()
plt.plot(epochs, loss, ‘b’)
plt.plot(epochs, val_loss, ‘r-’)
plt.title(‘Training and validation loss’)
pyplot.ylabel(‘loss’)
pyplot.xlabel(‘epoch’)
pyplot.legend([‘train’, ‘validation’], loc=‘upper right’)
plt.show()

model.save_weights(‘first_cnn2.h5’) # always save your weights after training or during training
plot_training(history_t)
`

keras中文文档最新
keras2.0

你可能感兴趣的:(深度学习keras)