计算机视觉系列之学习笔记主要是本人进行学习人工智能(计算机视觉方向)的代码整理。本系列所有代码是用python3编写,在平台Anaconda中运行实现,在使用代码时,默认你已经安装相关的python库,这方面不做多余的说明。本系列所涉及的所有代码和资料可在我的github上下载到,gitbub地址:https://github.com/mcyJacky/DeepLearning-CV,如有问题,欢迎指出。
上一篇我们已经使用普通的CNN完成猫和狗的训练。本篇我们将基于VGG16完成猫狗分类。VGG16是ImageNet2014年的亚军,使用VGG16比普通卷积网络的效果要好很多,且训练时间较快。VGG16网络模型如下图1.1所示,
接下来对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去掉全连接层模型,include_top: 表示全连接层
vgg16_model = VGG16(weights='imagenet', include_top=False, input_shape=(150,150,3))
vgg16_model.output_shape
# (None, 4, 4, 512)
# 搭建新的全连接层
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,
)
# Found 400 images belonging to 2 classes.
# Found 200 images belonging to 2 classes.
# 目标索引
train_generator.class_indices
# {'cat': 0, 'dog': 1}
下面进行模型训练和保存:
# 定义优化器, 代价函数,训练过程中计算准确率
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))
# 模型保存
model.save('model_vgg16.h5')
# 训练的部分输出结果:
# Epoch 1/20
# 13/13 [==============================] - 29s 2s/step - loss: 1.0951 - acc: 0.4764 - val_loss: 0.8394 - val_acc: 0.5050
# Epoch 2/20
# 13/13 [==============================] - 11s 881ms/step - loss: 0.7912 - acc: 0.4979 - val_loss: 0.6850 - val_acc: 0.5200
# Epoch 3/20
# 13/13 [==============================] - 11s 880ms/step - loss: 0.7015 - acc: 0.5313 - val_loss: 0.6574 - val_acc: 0.6200
# Epoch 4/20
# 13/13 [==============================] - 11s 878ms/step - loss: 0.7005 - acc: 0.5415 - val_loss: 0.6279 - val_acc: 0.7200
# ...
# 13/13 [==============================] - 12s 885ms/step - loss: 0.3770 - acc: 0.8411 - val_loss: 0.3430 - val_acc: 0.8500
# Epoch 18/20
# 13/13 [==============================] - 11s 879ms/step - loss: 0.3797 - acc: 0.8533 - val_loss: 0.3542 - val_acc: 0.8400
# Epoch 19/20
# 13/13 [==============================] - 11s 879ms/step - loss: 0.3886 - acc: 0.8342 - val_loss: 0.3427 - val_acc: 0.8500
# Epoch 20/20
# 13/13 [==============================] - 11s 878ms/step - loss: 0.3570 - acc: 0.8437 - val_loss: 0.3510 - val_acc: 0.8500
载入训练好的模型:
from keras.models import load_model
import numpy as np
from keras.preprocessing.image import load_img, img_to_array
label = np.array(['cat','dog'])
# 载入模型
model = load_model('model_vgg16.h5')
# 导入图片
image = load_img('image/test/cat/cat.1002.jpg')
image
测试图片如下4.1所示:
下面对训练好的模型对测试图片进行测试:
# 测试图片预处理
image = image.resize((150,150))
image = img_to_array(image)
image = image/255
image = np.expand_dims(image,0)
image.shape
# (1, 150, 150, 3)
print(label[model.predict_classes(image)])
# ['cat']
通过上述一套过程,就能用VGG16实现对图片的类型进行预测。
【参考】:
1. 城市数据团课程《AI工程师》计算机视觉方向
2. deeplearning.ai 吴恩达《深度学习工程师》
3. 《机器学习》作者:周志华
4. 《深度学习》作者:Ian Goodfellow
转载声明:
版权声明:非商用自由转载-保持署名-注明出处
署名 :mcyJacky
文章出处:https://blog.csdn.net/mcyJacky