7クラス顔画像分類
from __future__ import print_function
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
nb_classes = 7
def cnn():
model = Sequential()
model.add(Convolution2D(32, 3, 3, border_mode='same',
input_shape=(32, 32, 3)))
model.add(Activation('relu'))
model.add(Convolution2D(32, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Convolution2D(64, 3, 3, border_mode='same'))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('softmax'))
return model
batch_size = 16
nb_classes = 7
nb_epoch = 50
data_augmentation = True
# input image dimensions
img_x, img_y = 32, 32
# images are RGB.
img_channels = 3
model = cnn()
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# input dataset
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=30,
zoom_range=0.1,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
'train',
target_size=(img_x, img_y),
batch_size=batch_size,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(
'validation',
target_size=(img_x, img_y),
batch_size=batch_size,
class_mode='categorical')
model.fit_generator(
train_generator,
samples_per_epoch=800,
nb_epoch=nb_epoch,
validation_data=validation_generator,
nb_val_samples=90,
verbose=1)
model.save_weights('sanoba_cnn.hdf5')