实现一个自定义数据集上的图像识别项目

这次我们用卷积神经网络来解决一个猫、狗的分类问题,这是一个典型的二分类问题。
猫和狗的图片可以自行从网上搜集,尽量选择大小不一、角度不同、颜色不同的,存储成”类别.xxx.jpg”的形式,放入original_data文件夹。

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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
import os
import shutil
import numpy as np
import torch
from torch import nn
import torch.optim as optim
import torchvision.models as models
import torchvision.transforms as transforms
from torchvision.datasets import ImageFolder
from matplotlib import pyplot as plt
import random

#========================================================
# 超参数设置
#========================================================

class DefaultConfig(object):
def __init__(self):
self.EPOCH = 1 # 遍历数据集次数
self.BATCH_SIZE = 32 # 批处理尺寸(batch_size)
self.LR = 0.001 # 学习率

self.originial_dataset_dir = 'D:/download/original_data'
self.base_dir = 'DogCat/'

self.save_dir = './model/net_best.pth'

def parse(self, kwargs):
# 更新配置参数
for k, v in kwargs.items():
if not hasattr(self, k):
print('Warning: opt has not attribut {}'.format(k))
else:
setattr(self, k, v)

# 打印配置信息
print('user config:')
for k, v in self.__class__.__dict__.items():
if k == '__dict__':
print(getattr(self, k))

opt = DefaultConfig()
new_config = {'LR': 0.0015}
opt.parse(new_config)

#========================================================
# 文件准备
#========================================================

def image_preparation(original_dir, base_dir, labels):
'''
图像分类文件准备, 将文件复制到训练\测试集目录
INPUT -> 原始数据集地址, 数据集存放地址, 分类列表
'''
# 定义文件地址
base_dir = base_dir
if not os.path.exists(base_dir):
os.mkdir(base_dir)
train_dir = os.path.join(base_dir, 'traindata')
if not os.path.exists(train_dir):
os.mkdir(train_dir)
test_dir = os.path.join(base_dir, 'testdata')
if not os.path.exists(test_dir):
os.mkdir(test_dir)

names = locals()
# 图片转移
for label in labels:
names["train_"+str(label)+"dir"] = os.path.join(train_dir, str(label))
if not os.path.exists(names["train_"+str(label)+"dir"]):
os.mkdir(names["train_"+str(label)+"dir"])
names["test_"+str(label)+"dir"] = os.path.join(test_dir, str(label))
if not os.path.exists(names["test_"+str(label)+"dir"]):
os.mkdir(names["test_"+str(label)+"dir"])

fnames = [i for i in os.listdir(original_dir) if i.split('.')[0] == str(label)]
for fname in fnames[:int(len(fnames)*0.5)]:
src = os.path.join(original_dir, fname)
dst = os.path.join(names["train_"+str(label)+"dir"], fname)
shutil.copyfile(src, dst)
for fname in fnames[int(len(fnames)*0.5):]:
src = os.path.join(original_dir, fname)
dst = os.path.join(names["test_"+str(label)+"dir"], fname)
shutil.copyfile(src, dst)
print('total train '+str(label)+' images:', len(os.listdir(names["train_"+str(label)+"dir"])))
print('total test '+str(label)+' images:', len(os.listdir(names["test_"+str(label)+"dir"])))

# 将图片分别存到各个文件夹
image_preparation(opt.originial_dataset_dir, opt.base_dir, ['cat','dog'])

# 分类数
n_classes = 0
for fn in os.listdir(os.path.join(opt.base_dir, 'traindata')):
n_classes += 1

#========================================================
# 数据加工
#========================================================

# 定义数据预处理方式
transform = transforms.Compose([
transforms.Resize(256), # 缩放图片, 保持长宽比不变, 最短边256
transforms.CenterCrop(224), # 从图片中间切出224x224的图片
transforms.ToTensor(), # 将图片(Image)转化为Tensor, 归一化到[0,1]
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) # 标准化到[-1,1]
])

# 定义训练数据集
trainset = ImageFolder(os.path.join(opt.base_dir, 'traindata'), transform=transform)

# 定义训练批处理数据
trainloader = torch.utils.data.DataLoader(
trainset,
batch_size=opt.BATCH_SIZE,
shuffle=True
)

# 定义测试数据集
testset = ImageFolder(os.path.join(opt.base_dir, 'testdata'), transform=transform)

# 定义测试批处理数据
testloader = torch.utils.data.DataLoader(
testset,
batch_size=opt.BATCH_SIZE,
shuffle=False
)

#========================================================
# 模型结构设计
#========================================================

class Net(nn.Module):
'''
基于resnet50网络做迁移学习
INPUT -> 图像规格(224, 224, 3), 待分类数(2)
'''
def __init__(self, n_classes=n_classes):
super(Net, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameters():
param.requires_grad_(False)

modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*modules)
self.classifier = nn.Linear(resnet.fc.in_features, n_classes)

def forward(self, x):
x = self.resnet(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x

#========================================================
# 模型实例化
#========================================================

# 定义是否使用GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
net = Net().to(device)

# 定义损失函数loss function 和优化方式
criterion = nn.CrossEntropyLoss() # 交叉熵损失函数,通常用于多分类问题上
optimizer = optim.SGD(net.parameters(), lr=opt.LR, momentum=0.9)

#========================================================
# 训练模式和测试模型
#========================================================

def train_work(mode=None):
'''
训练阶段
'''
net.train() # 设置模式为训练模式
if mode == 'Update' and os.path.exists(opt.save_dir):
net.load_state_dict(torch.load(opt.save_dir)) # 加载模型参数
loss_over_time = []
for epoch in range(opt.EPOCH):
running_loss = 0.0
# 数据读取
i = 0
for data in trainloader:
i += 1
images, labels = data
images, labels = images.to(device), labels.to(device)

optimizer.zero_grad()

# forward + backward + optimize
outputs = net(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()

# 每训练10个batch打印一次平均loss
running_loss += loss.item()
if i % 10 == 9:
avg_loss = running_loss/10
loss_over_time.append(avg_loss)
print('[%d] loss: %.03f' % (epoch + 1, avg_loss))
running_loss = 0.0

# 每跑完一次epoch测试一下准确率
with torch.no_grad():
correct = 0
total = 0
for data in testloader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = net(images)
# 取得分最高的那个类
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
print('第%d个epoch的识别准确率为:%d%%' % (epoch + 1, (100 * correct / total)))
torch.save(net.state_dict(), opt.save_dir)
print('Finished Training')
return loss_over_time

def test_work():
'''
测试阶段
'''
net.load_state_dict(torch.load(opt.save_dir)) # 加载模型参数
net.eval() # 设置模式为验证模式
correct = 0
total = 0
for data in testloader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = net(images)
# 取得分最高的那个类
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
print('当前模型识别准确率为:%d%%' % (100 * correct / total))

def show_loss(training_loss):
'''
可视化损失变化
'''
plt.plot(training_loss)
plt.xlabel('10\'s of batches')
plt.ylabel('loss')
plt.ylim(0, 2.5) # consistent scale
plt.show()

def show_predicted():
'''
展示预测结果
'''
net.load_state_dict(torch.load(opt.save_dir))
net.eval() # 设置模式为验证模式
n_examples = 8
[examples] = random.sample(list(testloader), 1)
images, labels = examples
images, labels = images.to(device), labels.to(device)
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)

for i in range(n_examples):
img = images[i,0,:,:]
img = img.cpu()
img = img.data.numpy()

img = 1.0/(1+np.exp(-1*img))
img = np.round(img*255)

ax = plt.subplot((n_examples//4), 4, i+1)
plt.imshow(img, cmap='gray')
plt.title('label:{}\nPredicted: {}'.format(labels[i],predicted[i]))
plt.axis('off')
plt.show()

#========================================================
# 主程序
#========================================================

if __name__ == "__main__":
training_loss = train_work()
show_loss(training_loss)
test_work()
show_predicted()
0%