● 难度:新手入门⭐
● 语言:Python3、Pytorch3
🍺要求:
1、本地读取并加载数据
2、测试集accuracy达到93%
🍻拔高:
1、测试集accuracy达到95%
2、调用模型识别一张本地图片
🍨 本文为🔗365天深度学习训练营 中的学习记录博客
🍖 原作者:K同学啊|接辅导、项目定制
365天深度学习训练营打卡
第3周-天气识别
本文将采用CNN实现多云、下雨、晴、日出四种天气状态的识别。较上篇文章,本文为了增加模型的泛化能力,新增了Dropout层并且将最大池化层调整成了平均池化层。
一、前期准备
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision
from torchvision import transforms, datasets
import os, PIL, pathlib
1.设置GPU
device = torch.device("cude" if torch.cuda.is_available() else "cpu")
device
2.导入数据
# 数据的根目录
data_dir = "./data/"
# 实例化Path对象
data_dir = pathlib.Path(data_dir)
# .glob 返回一个迭代器,储存当前路径下的所有文件与路径
data_paths = list(data_dir.glob('*'))
# 从文件名,分离出具体的类别名
class_names = [str(path).split("\\")[1] for path in data_paths]
class_names
['cloudy', 'rain', 'shine', 'sunrise']
图像增广
数据集一共分为cloudy
、rain
、shine
、sunrise
四类,分别存放于weather_photos
文件夹中以各自名字命名的子文件夹
image_count = len(list(data_dir.glob('*/*.jpg')))
print("图片总数为:", image_count)
roses = list(data_dir.glob('sunrise/*.jpg'))
print(str(roses[13]))
PIL.Image.open(str(roses[13]))
train_transforms = transforms.Compose([
transforms.Resize([224, 224]), # 将输入图片resize成统一尺寸
transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0, 1]之间
transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
# mean, std是从数据集中随机抽样计算得到的
])
total_data = datasets.ImageFolder(data_dir, transform=train_transforms)
total_data
total_data里面的结构如下:
1.图片的像素值 2. 图片的类别
3.划分数据集
train_size = int(0.8 * len(total_data))
test_size = len(total_data) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size])
train_dataset, test_dataset
train_size, test_size
(900,225)
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=1)
test_dl = torch.utils.data.DataLoader(test_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=1)
plt.figure(figsize=(20, 10))
for images, labels in train_dl:
for i in range(20):
ax = plt.subplot(5, 10, i + 1)
plt.imshow(images[i].numpy().transpose((1, 2, 0)), cmap=plt.cm.binary)
plt.title(class_names[labels[i]])
plt.axis("off")
(这里为进行图像增广之后的图片)
for X, y in test_dl:
print("Shape of X [N, C, H, W]: ", X.shape)
print("Shape of y: ", y.shape, y.dtype)
break
二、构建简单的分类网络
class Network_bn(nn.Module):
def __init__(self):
super(Network_bn, self).__init__()
# 特征提取网络
self.feature_net = nn.Sequential(nn.Conv2d(3, 12, 5), nn.BatchNorm2d(12),
nn.ReLU(),
nn.Conv2d(12, 12, 5), nn.BatchNorm2d(12),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(12, 24, 5), nn.BatchNorm2d(24),
nn.ReLU(),
nn.Conv2d(24, 24, 5), nn.BatchNorm2d(24),
nn.ReLU(),
nn.MaxPool2d(2))
# 分类网络
self.class_net = nn.Sequential(nn.Linear(24*50*50, len(class_names)))
def forward(self, x):
x = self.feature_net(x)
x = x.view(-1, 24*50*50)
x = self.class_net(x)
return x
print("Using {} device".format(device))
model = Network_bn().to(device)
model
- Batch_Normalization(批标准化):
如何理解BatchNorm?参考论文Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
机器学习领域有个很重要的假设:IID独立同分布假设,就是假设训练数据和测试数据是满足相同分布的,这是通过训练数据获得的模型能够在测试集获得好的效果的一个基本保障。
BatchNorm就是在深度神经网络训练过程中使得每一层神经网络的输入保持相同分布的。- “Internal Covariate Shift”问题:
- 对于深度学习这种包含很多隐层的网络结构,在训练过程中,因为各层参数老在变,所以每个隐层都会面临covariate shift的问题,也就是在训练过程中,隐层的输入分布老是变来变去,这就是所谓的“Internal Covariate Shift”,Internal指的是深层网络的隐层,是发生在网络内部的事情,而不是covariate shift问题只发生在输入层。
- 然后提出了BatchNorm的基本思想:能不能让每个隐层节点的激活输入分布固定下来呢?这样就避免了“Internal Covariate Shift”问题了。
- BatchNorm的本质思想:
-
对于每个隐层神经元,把逐渐向非线性函数映射后向取值区间极限饱和区靠拢的输入分布强制拉回到均值为0方差为1的比较标准的正态分布,使得非线性变换函数的输入值落入对输入比较敏感的区域,以此避免梯度消失问题。因为梯度一直都能保持比较大的状态,所以很明显对神经网络的参数调整效率比较高,就是变动大,就是说向损失函数最优值迈动的步子大,也就是说收敛地快。
-
- “Internal Covariate Shift”问题:
三、训练模型
1.设置超参数
loss_fn = nn.CrossEntropyLoss()
lr = 2e-4
opt = torch.optim.SGD(model.parameters(), lr=lr)
2.编写训练函数
# 训练循环
def train_batch(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
num_batches = len(dataloader)
train_acc, train_loss = 0, 0
for X, y in dataloader:
X, y = X.to(device), y.to(device)
# loss
y_pred = model(X)
loss = loss_fn(y_pred, y)
# backward
optimizer.zero_grad()
loss.backward()
optimizer.step()
# log
train_acc += (y_pred.argmax(1) == y).type(torch.float).sum().item()
train_loss += loss.item()
train_acc /= size
train_loss /= num_batches
return train_acc, train_loss
3.编写测试函数
def test(dataloader, model, loss_fn):
size = len(dataloader.dataset)
num_batches = len(dataloader)
test_acc, test_loss = 0, 0
with torch.no_grad():
for img, target in dataloader:
img, target = img.to(device), target.to(device)
# 计算loss
target_pred = model(img)
loss = loss_fn(target_pred, target)
test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()
test_loss += loss.item()
test_acc /= size
test_loss /= num_batches
return test_acc, test_loss
4.正式训练
epochs = 20
train_loss, train_acc = [], []
test_loss, test_acc = [], []
for epoch in range(epochs):
model.train()
epoch_train_acc, epoch_train_loss = train_batch(train_dl, model, loss_fn, opt)
model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
# log
train_acc.append(epoch_train_acc)
train_loss.append(epoch_train_loss)
test_acc.append(epoch_test_acc)
test_loss.append(epoch_test_loss)
template = ("Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}")
print(template.format(epoch+1,
epoch_train_acc*100, epoch_train_loss,
epoch_test_acc*100, epoch_test_loss))
print("Done!")
四、结果可视化
import warnings
warnings.filterwarnings("ignore")
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['figure.dpi'] = 200
epoch_range = range(epochs)
plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)
plt.plot(epoch_range, train_acc, label="Training Accuracy")
plt.plot(epoch_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Traing and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epoch_range, train_loss, label="Training Loss")
plt.plot(epoch_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Traing and Validation Loss')
plt.show()
目标1:调整参数使得预测Accuracy达到95%
调整:
1.网络结构:将第一层最大池化调整为平均池化;增加一层全连接层
2.训练策略:epoch改成26;学习率改成动态自适应,初始学习率为2e-4,当epoch大于15学习率降低0.1
目标2:预测结果精度太低,无论是什么样的输入,均预测为sunshine