keras分类猫狗数据(上)数据预处理
keras分类猫狗数据(中)使用CNN分类模型
keras分类猫狗数据(下)迁移学习
keras分类猫狗数据(番外篇)深度学习CNN连接SVM分类
1 . 如下代码,数据增强,并根据文件夹创建数据流(我的保存为了catvsdogs/morph.py
)。
from keras.preprocessing.image import ImageDataGenerator
train_dir="E:/MLdata/kaggle_Dogsvs.Cats/min_trainfordata/train"
test_dir="E:/MLdata/kaggle_Dogsvs.Cats/min_trainfordata/test"
train_pic_gen=ImageDataGenerator(rescale=1./255,rotation_range=20,width_shift_range=0.2,height_shift_range=0.2,
shear_range=0.2,zoom_range=0.5,horizontal_flip=True,fill_mode='nearest')
test_pic_gen=ImageDataGenerator(rescale=1./255)
train_flow=train_pic_gen.flow_from_directory(train_dir,(128,128),batch_size=32,class_mode='binary')
test_flow=test_pic_gen.flow_from_directory(test_dir,(128,128),batch_size=32,class_mode='binary')
# print(train_flow.class_indices)
2 .构建模型并训练
from keras.models import Sequential
from keras.layers import Convolution2D,MaxPool2D,Flatten,Dense,Dropout
from keras.callbacks import TensorBoard
model=Sequential([
Convolution2D(32,3,3,input_shape=(128,128,3),activation='relu'),
MaxPool2D(pool_size=(2,2)),
Convolution2D(64,3,3,input_shape=(128,128,3),activation='relu'),
MaxPool2D(pool_size=(2,2)),
Flatten(),
Dense(64,activation='relu'),
Dropout(0.5),
Dense(1,activation='sigmoid')
])
model.summary()
model.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['accuracy'])
import catvsdogs.morph as morph#引用上文1的数据增加代码
model.fit_generator(
morph.train_flow,steps_per_epoch=100,epochs=50,verbose=1,validation_data=morph.test_flow,validation_steps=100,
callbacks=[TensorBoard(log_dir='./logs/1')]
)
model.save('outputs/catdogs_model.h5')
3 .也可以将步骤2的模型数据重新加载继续训练。
from keras.callbacks import TensorBoard
from keras.models import load_model
model=load_model('outputs/catdogs_model.h5')
model.summary()
import catvsdogs.morph as morph
model.fit_generator(
morph.train_flow,steps_per_epoch=100,epochs=50,verbose=1,validation_data=morph.test_flow,validation_steps=100,
callbacks=[TensorBoard(log_dir='./logs/2')]
)
model.save('outputs/catdogs_model.h5')
4 . 以下加载模型数据并参与预测:
from keras import models
import numpy as np
import cv2
def get_inputs(src=[]):
pre_x = []
for s in src:
input = cv2.imread(s)
input = cv2.resize(input, (128, 128))
input = cv2.cvtColor(input, cv2.COLOR_BGR2RGB)
pre_x.append(input) # input一张图片
pre_x = np.array(pre_x) / 255.0
return pre_x
def put_prey(pre_y,label):
output=[]
for y in pre_y:
if y[0]<0.5:#二分类,此处只用一个神经元输出
output.append([label[0],1-y[0]])
else:
output.append([label[1], y[0]])
return output
model=models.load_model('outputs/catdogs_model.h5')
pre_x=get_inputs(['../data/rotman.jpg','../data/cat.jpg'])
pre_y=model.predict(pre_x)
import catvsdogs.morph as
[[‘dogs’, 0.8959254], [‘cats’, 0.6214156150817871]]
测试所用图片:
5 .第二次训练验证数据正确率和损失如下:
可以看到准确率在0.78左右。