猫狗分类 CNN
#%%
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import load_img, img_to_array
#%%
# 对图片进行随机处理,以扩大数据集
datagen = ImageDataGenerator(
# 随机旋转角度
rotation_range=40,
# 随机水平平移
width_shift_range=0.2,
# 随机竖直平移
height_shift_range=0.2,
# 数值归一化
rescale=1. / 255,
# 随机裁剪
shear_range=0.2,
# 随机放大
zoom_range=0.2,
# 水平翻转
horizontal_flip=True,
# 填充方式
fill_mode='nearest'
)
#%%
# 对一张图片进行图像增强
img = load_img('image/train/cat/cat.1.jpg')
# 转为numpy
x = img_to_array(img)
# (280, 300, 3)
print(x.shape)
x = x.reshape((1,) + x.shape)
# (1, 280, 300, 3)
print(x.shape)
#%%
i = 0
# flow 随机生成增强的图片
for batch in datagen.flow(x, batch_size=1, save_to_dir='temp', save_format='png'):
i += 1
# 生成10张
if i >= 10:
break
#%%
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.optimizers import Adam
#%%
model = Sequential()
model.add(
Convolution2D(input_shape=(150, 150, 3), filters=32, kernel_size=3, strides=1, padding='same', activation='relu'))
model.add(Convolution2D(filters=32, kernel_size=3, strides=1, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2, strides=2, padding='valid'))
model.add(Convolution2D(filters=64, kernel_size=3, strides=1, padding='same', activation='relu'))
model.add(Convolution2D(filters=64, kernel_size=3, strides=1, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2, strides=2, padding='valid'))
model.add(Convolution2D(filters=128, kernel_size=3, strides=1, padding='same', activation='relu'))
model.add(Convolution2D(filters=128, kernel_size=3, strides=1, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2, strides=2, padding='valid'))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))
#%%
adam = Adam(lr=1e-4)
model.compile(optimizer=adam, loss="categorical_crossentropy", metrics=['accuracy'])
model.summary()
#%%
# 训练集数据生成器
train_datagen = ImageDataGenerator(
rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)
# 测试集数据生成器
test_datagen = ImageDataGenerator(
rescale=1. / 255
)
#%%
batch_size = 32
# 生成训练集数据
train_generator = train_datagen.flow_from_directory(
# 训练集路径
'image/train',
# 设置生成的图片大小
target_size=(150, 150),
# 批次大小
batch_size=batch_size
)
# 生成测试集数据
test_generator = test_datagen.flow_from_directory(
# 训练集路径
'image/test',
# 设置生成的图片大小
target_size=(150, 150),
# 批次大小
batch_size=batch_size
)
#%%
model.fit_generator(
train_generator,
steps_per_epoch=train_generator.samples / batch_size,
epochs=2,
validation_data=test_generator,
validation_steps=test_generator.samples / batch_size
)
#%%
# 模型保存
model.save('cnn_cat_dog.h5')
#%%
from keras.models import load_model
# 模型加载
model_ = load_model("cnn_cat_dog.h5")