导入库
import sys
from matplotlib import pyplot
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Dense
from keras.layers import Flatten
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDateGenerator
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
LS /home/jovyan/work/datasets/lizhensheng-cat-dog-all-modode1
创建CNN模型
定义一个CNN模型
要求:卷积层的卷积核数量为3,卷积核尺寸为3x3,激活函数为relu,padding设置为same
def define_cnn_model():
#使用序列模型
model = Sequential()
#卷积层
model.add(Conv2D(32,(3,3),activation='relu',padding='same',imput_shape=(200,200,3)))
#最大池化层
model.add(MaxPooling2D(2,2))
#Flatten层
model.add(Flatten())
#全连接层
model.add(Dense(128,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
#编译模型
opt = SGD(lr=0.001,momentum=0.9)
model.compile(optimize=opt,
loss='binary_crossentropy',
metrics=['accuracy'])
return model
验证模型是否符合要求
from keras.utils import plot_mode
model = define_cnn_model()
plot_model(model,
to_file='cnn_model.png',
dpi=100,
show_shape=True,
show_layer_names=True)
训练模型
def train_cnn_model():
# 实例化模型
model = define_cnn_model()
# 创建图片生成器
datagen = ImageDataGenerator(rescale=1.0 / 255.0) #数据值除以255,[0-255] ->[0,1]
train_it = datagen.flow_from_directory(
'./datasets/ma1ogo3ushu4ju4ji2-momodel/dogs_cats/data/train/',
class_mode='binary',
batch_size=64,
target_size=(200, 200))
# 训练模型
model.fit_generator(train_it,
steps_per_epoch=len(train_it),
epochs=1,
verbose=1)
预测模型
载入训练时保存的模型
from keras.models import load_model
# 修改 model_path 为你自己保存的模型的位置
model_path = './datasets/ma1ogo3ushu4ju4ji2-momodel/dogs_cats/model/basic_cnn_model.h5'
# 载入模型
model = load_model(model_path)
从测试文件夹中读取任意一张图片
import os,random
from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image
%matplotlib inline
def read_random_image():
folder=r"./datasets/ma1ogo3ushu4ju4ji2-momodel/dogs_cats/data/test/"
file_path = folder + random.choice(os.listdir(folder))
pil_im = Image.open(file_path,'r')
return pil_im
设定使用模型对读取出的图片进行预测
def get_predict(pil_im,model):
# 对图片进行缩放
pil_im = pil_im.resize((200,200))
#将格式转为numpy array 格式
array_im = np.asarray(pil_im)
array_im = np.expand_dims(array_im,axis=0)
#对图片进行预测
result = model.predict(array_im)
if result[0][0]>0.5:
print("预测结果是:狗")
else:
print("预测结果是:猫")
结果
pil_im = read_random_image()
#显示图片
imshow(np.asarray(pil_im))
get_predict(pil_im,model)