keras利用VGG16实现猫狗分类

  • 导入相关的包
from keras.applications.vgg16 import VGG16
from keras.models import Sequential
from keras.layers import Conv2D,MaxPool2D,Activation,Dropout,Flatten,Dense
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator,img_to_array,load_img
import numpy as np
  • 实例化一个VGG16对象,使用imagenet数据集训练,不包含顶层(即全连接层)
#实例化VGG16模型对象
vgg16_model = VGG16(weights='imagenet',include_top=False, input_shape=(150,150,3))
  • 基于VGG16建立模型
# 搭建全连接层
top_model = Sequential()
top_model.add(Flatten(input_shape=vgg16_model.output_shape[1:]))
top_model.add(Dense(256,activation='relu'))
top_model.add(Dropout(0.5))
top_model.add(Dense(2,activation='softmax'))

model = Sequential()
model.add(vgg16_model)
model.add(top_model)
  • 实例化数据生成器,进行数据增强
train_datagen = ImageDataGenerator(
    rotation_range = 40,     # 随机旋转度数
    width_shift_range = 0.2, # 随机水平平移
    height_shift_range = 0.2,# 随机竖直平移
    rescale = 1/255,         # 数据归一化
    shear_range = 20,       # 随机错切变换
    zoom_range = 0.2,        # 随机放大
    horizontal_flip = True,  # 水平翻转
    fill_mode = 'nearest',   # 填充方式
) 
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,
    )
  • debug训练数据的标签类别
train_generator.class_indices
  • 编译训练模型
# 定义优化器,代价函数,训练过程中计算准确率
model.compile(optimizer=SGD(lr=1e-4,momentum=0.9),loss='categorical_crossentropy',metrics=['accuracy'])

model.fit_generator(train_generator,steps_per_epoch=len(train_generator),epochs=20,
                    validation_data=test_generator,validation_steps=len(test_generator))

keras利用VGG16实现猫狗分类_第1张图片

  • 保存模型
# pip install h5py
model.save('model_vgg16.h5')
  • 加载模型 , 传入图片测试
from keras.models import load_model
import numpy as np

label = np.array(['cat','dog'])
# 载入模型
model = load_model('model_vgg16.h5')

# 导入图片
image = load_img('image/test/cat/cat.1003.jpg')
image

keras利用VGG16实现猫狗分类_第2张图片

image = image.resize((150,150))
image = img_to_array(image)
image = image/255
image = np.expand_dims(image,0)
image.shape
res = label[model.predict_classes(image)]
print(res)

在这里插入图片描述

import cv2
img = cv2.imread("image/test/dog/dog.1003.jpg")
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, res[0]+" detected", (30,30), font, 1, (200,100,255), 2, cv2.LINE_AA)
cv2.imshow("dst", img)
cv2.waitKey()
cv2.destroyAllWindows()

keras利用VGG16实现猫狗分类_第3张图片

你可能感兴趣的:(keras,python,深度学习,迁移学习,tensorflow,计算机视觉)