一、实现软件配置
1.keras2.2.0-tensorflow-GPU1.8
2.python3.6
3.spyder3.3.2
二、实现步骤
1.收集猫狗图片,并且在当前文件运行目录,添加文件夹image,image里再添加train和test。最后在train和test文件夹添加dog和cat文件夹并将图片放入
2.定义简单顺序模型model = Sequential() 并在模型中添加卷积-卷积-池化 -卷积-卷积-池化- -卷积-卷积-池化- 全连接层-全连接层
3.定义优化器Adam和损失函数categorical_crossentropy
4.使用ImageDataGenerator生成增强训练、测试数据集 将处理完的图片使用train_datagen.flow_from_directory生成训练数据
5.使用model.fit_generator设置训练参数
6.最后用折线图展现模型效果
三、实现代码
# coding: utf-8
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
import os
import matplotlib.pyplot as plt
# 定义模型
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)
# 定义优化器,loss function,训练过程中计算准确率
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 # 批次大小
)
# 统计文件个数
totalFileCount = sum([len(files) for root, dirs, files in os.walk('image/train')])
totalFileCount
#查看标签
train_generator.class_indices
#
#model.fit_generator(
# train_generator,
# steps_per_epoch=totalFileCount/batch_size,
# epochs=5, #设置训练周期数50
# validation_data=test_generator,
# validation_steps=1000/batch_size
# )
#
## 保存模型
#model.save('CNN1.h5')
history = model.fit_generator(
train_generator, steps_per_epoch=totalFileCount/batch_size ,
epochs=50, verbose=1,
validation_data=test_generator, validation_steps=1000/batch_size
)
model.save('CNN1.h5')
#画图
acc = history.history['acc'] #获取训练集准确性数据
val_acc = history.history['val_acc'] #获取验证集准确性数据
loss = history.history['loss'] #获取训练集错误值数据
val_loss = history.history['val_loss'] #获取验证集错误值数据
epochs = range(1,len(acc)+1)
plt.title('model accuracy') #标题
plt.ylabel('accuracy') #y轴名称
plt.xlabel('epoch') #x轴名称
plt.plot(epochs,acc,label='Train_acc') #以epochs为横坐标,以训练集准确性为纵坐标
plt.plot(epochs,val_acc,label='Val_acc') #以epochs为横坐标,以验证集准确性为纵坐标
plt.plot(epochs,loss,label='Train_loss')
plt.plot(epochs,val_loss,label='Val_loss')
plt.legend(loc='upper left') #绘制图例,即标明图中的线段代表何种含义
plt.savefig('loss-acc.png')
plt.show() #显示所有图表
四、训练结果
五、测试代码
import numpy as np
from keras.models import load_model,Sequential
from keras.preprocessing.image import load_img,img_to_array
label = np.array(['cat','dog'])
#载入模型
model = load_model('CNN1.h5')
#导入图片
path = 'temp/2.jpg'
image = load_img(path)
image = image.resize((150,150))
image = img_to_array(image)
image = image/255
image = np.expand_dims(image,0)
image.shape
#print(label[model.predict_class(image)])
predict = model.predict(image) #采用合并预测的方法
predict=np.argmax(predict,axis=1)
print(label[predict])