0%

犬种识别代码

模型训练

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
from google.colab import drive
drive.mount('/content/drive')

# 接受截断的图片
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import os
from keras.preprocessing.image import ImageDataGenerator

# 数据集路径
base_dir = '/content/drive/My Drive/MachineLearning/dogImages'

train_dir = os.path.join(base_dir, 'train')
valid_dir = os.path.join(base_dir, 'valid')
test_dir = os.path.join(base_dir, 'test')

# 使用图像生成器
# 使用归一化 和 图像增强
# 验证集不应该使用图像增强
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
vertical_flip=True,
fill_mode='nearest')
valid_datagen = ImageDataGenerator(rescale=1./255)

# 加载数据集
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(512, 512),
batch_size=32,
class_mode='categorical')
valid_generator = valid_datagen.flow_from_directory(
valid_dir,
target_size=(512, 512),
batch_size=32,
class_mode='categorical')

import matplotlib.pyplot as plt
from PIL import Image
Image.MAX_IMAGE_PIXELS = 1000000000
%matplotlib inline

print('训练集部分原始图像:')
display(Image.open(os.path.join(train_dir, '039.Bull_terrier/Bull_terrier_02752.jpg')))
print('训练集部分数据(图像)增强后的图像:')
img = train_generator[0][0]
fig = plt.figure(figsize=(40,4))
for i in range(0, 12):
ax = fig.add_subplot(1, 12, i+1)
ax.imshow(img[i])
plt.savefig('/content/drive/My Drive/MachineLearning/augmentation.png')
plt.show()
plt.close()

from keras.applications.inception_v3 import InceptionV3
from keras.models import Model
from keras.layers import Dense

# 构建不带分类器的预训练模型
base_model = InceptionV3(
weights='imagenet',
include_top=False,
input_shape=(512, 512, 3),
pooling='avg')
x = base_model.output
# 添加一个全连接层
x = Dense(1024, activation='relu')(x)
# 添加一个分类器
predictions = Dense(133, activation='softmax')(x)
# 构建需要训练的完整模型
model = Model(inputs=base_model.input, outputs=predictions)

# 锁住InceptionV3的卷积层
# for layer in base_model.layers:
# layer.trainable = False

# 编译模型
# model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

# 现在顶层训练好了,开始微调 Inception V3 的卷积层。
# 锁住底下的几层,然后训练其余的顶层。

# 每一层的名字和层号,决定应该锁多少层呢:
for i, layer in enumerate(base_model.layers):
print(i, layer.name)

# 选择训练最上面的两个 Inception block
# 即锁住前面249层,然后放开之后的层。
for layer in model.layers[:249]:
layer.trainable = False
for layer in model.layers[249:]:
layer.trainable = True

# 重新编译模型,使上面的修改生效
# 设置一个很低的学习率,使用 SGD 来微调
from keras.optimizers import SGD
model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy', metrics=['accuracy'])

# 查看模型结构
model.summary()


from keras.utils import plot_model
from PIL import Image

# 生成网络结构的png图像
plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=True)
# 显示png图像
display(Image.open('model.png'))

from keras.callbacks import ModelCheckpoint

# 加载之前训练好的权重
model.load_weights('/content/drive/My Drive/MachineLearning/dogImages.augmentation.model.weights.best.1.hdf5')

checkpointer = ModelCheckpoint(
filepath='/content/drive/My Drive/MachineLearning/dogImages.augmentation.model.weights.best.1.hdf5',
verbose=1,
save_best_only=True)

history = model.fit_generator(
generator=train_generator,
epochs=10,
validation_data=valid_generator,
callbacks=[checkpointer],
verbose=1,
steps_per_epoch=210,
validation_steps=50)

import matplotlib.pyplot as plt

# 绘制训练 & 验证的准确率值
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Val'], loc='upper left')
plt.savefig('/content/drive/My Drive/MachineLearning/acc_2.png')
plt.show()
plt.close()

# 绘制训练 & 验证的损失值
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Val'], loc='upper left')
plt.savefig('/content/drive/My Drive/MachineLearning/loss_2.png')
plt.show()
plt.close()

# 加载最佳模型
model.load_weights('/content/drive/My Drive/MachineLearning/dogImages.augmentation.model.weights.best.1.hdf5')
# 归一化 & 加载测试集
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory(
test_dir,
target_size=(512, 512),
batch_size=20,
class_mode='categorical')
# 训练集, 验证集, 测试集 loss 和 accuracy
train_loss, train_acc = model.evaluate_generator(train_generator)
print('train_loss: ', train_loss)
print('train_acc: ', train_acc)
valid_loss, valid_acc = model.evaluate_generator(valid_generator)
print('valid_loss: ', valid_loss)
print('valid_acc: ', valid_acc)
test_loss, test_acc = model.evaluate_generator(test_generator)
print('test_loss: ', test_loss)
print('test_acc: ', test_acc)

模型预测

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from keras.models import load_model
import os
import numpy as np
from keras.preprocessing import image
import matplotlib.pyplot as plt
from PIL import Image
Image.MAX_IMAGE_PIXELS = 1000000000
%matplotlib inline

print('loading model ...')
model = load_model('./dogImages.augmentation.model.weights.best.1.hdf5')

samples_dir = './samples/'
classes = sorted(os.listdir(samples_dir))

pred_dir = './pred/'
pred_files = sorted(os.listdir(pred_dir))
img = []

for i in range(len(pred_files)):
print('loading no.%s image %s ...' % (i, pred_files[i]))
images = image.load_img(pred_dir+pred_files[i], target_size=(512, 512))
x = image.img_to_array(images)
x = x / 255.
x = np.expand_dims(x, axis=0)
img.append(x)

# 把图片数组联合在一起
x = np.concatenate([x for x in img])

print('predicting ...')
preds = model.predict(x)
preds_class = preds.argmax(axis=-1)
preds_percent = preds.max(axis=-1)

for i in range(len(pred_files)):
print('no.%s image %s ' % (i, pred_files[i]))
display(Image.open(pred_dir+pred_files[i]))
print('{:.2f}% belong to '.format(preds_percent[i]*100))
print('%s' % classes[preds_class[i]])
display(Image.open(samples_dir+classes[preds_class[i]]+'/0.jpg'))
print()

# 网络认为预测向量中最大激活的元素对应是"Afghan_hound"类别的元素, 索引编号1
preds_class[0]

# 应用Grad-CAM算法

from keras import backend as K

dog_output = model.output[:, preds_class[0]]# 预测向量中的"Afghan_hound"元素

last_conv_layer = model.get_layer('conv2d_94')# conv2d_94层的输出特征图,它是该模型的最后一个卷积层

grads = K.gradients(dog_output, last_conv_layer.output)[0]# "Afghan_hound"类别相对于conv2d_94输出特征图的梯度

pooled_grads = K.mean(grads, axis=(0, 1, 2))# 形状是(192, )的向量,每个元素是特定特征图通道的梯度平均大小

iterate = K.function([model.input], [pooled_grads, last_conv_layer.output[0]])# 这个函数允许我们获取刚刚定义量的值:对于给定样本图像,pooled_grads和conv2d_94层的输出特征图

pooled_grads_value, conv_layer_output_value = iterate([x])# 给我们两个"Afghan_hound"样本图像,这两个量都是Numpy数组

for i in range(192):
conv_layer_output_value[:, :, i] *= pooled_grads_value[i]# 将特征图数组的每个通道乘以这个通道对"Afghan_hound"类别重要程度

heatmap = np.mean(conv_layer_output_value, axis=-1)# 得到的特征图的逐通道的平均值即为类激活的热力图

# 热力图后处理

heatmap = np.maximum(heatmap, 0)# heatmap与0比较,取其大者

heatmap /= np.max(heatmap)

plt.matshow(heatmap)

plt.show()

plt.close()

# 将热力图与原始图叠加, 实现可视化

import cv2

img = cv2.imread(pred_dir+pred_files[0])# 用cv2加载原始图像

heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))# 将热力图的大小调整为与原始图像相同

heatmap = np.uint8(255 * heatmap)# 将热力图转换为RGB格式

heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)# 将热力图应用于原始图像

superimposed_img = heatmap * 0.4 + img# 这里的0.4是热力图强度因子

cv2.imwrite('./CAM/Afghan_hound_00081.cam.jpg', superimposed_img)# 将图像保存到硬盘

display(Image.open('./CAM/Afghan_hound_00081.cam.jpg'))
Thank you for your reward !