# -*- coding: utf-8 -*-
"""
Created on Tue Oct 19 15:50:59 2021
@author: Lancibe
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
# 定义网络类
class Net(nn.Module):
# 定义初始化函数
def __init__(self):
super(Net, self).__init__()
# 定义第一层卷积神经网络,输入通道维度为1,输出通道维度6,卷积核大小3*3
self.conv1 = nn.Conv2d(1, 6, 3)
# 第二层,6,16,3
self.conv2 = nn.Conv2d(6, 16, 3)
# 第三层全连接网络
self.fc1 = nn.Linear(16 * 6 * 6, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
# 在(2, 2)的池化窗口下执行最大池化操作
# 任意卷积层后面要加激活层、池化层
x = F.max_pool2d(F.relu(self.conv1(x)), (2,2))
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
`# 经过卷积层的处理之后,张量进入全连接层,进入前需要调整张量的形状
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# 把一个经历过卷积后的张量x计算size
def num_flat_features(self, x):
size = x.size()[1:]
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net()
print(net)
Net(
(conv1): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1))
(fc1): Linear(in_features=576, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)
params = list(net.parameters())
print(len(params()))
print(params[0].size())
10
torch.Size([6, 1, 3, 3])
input = torch.randn(1,1,32,32)
out = net(input)
print(out)
tensor([[-0.1169, -0.1627, 0.0504, -0.0820, -0.0311, -0.0599, 0.0003, -0.0024,
0.0026, 0.0187]], grad_fn=<AddmmBackward>)
net.zero_grad()
out.backward(torch.randn(1,10))
input = torch.randn(1,1,32,32)
out = net(input)
target = torch.randn(10)
# 改变target的形状
target = target.view(1,-1)
criterion = nn.MSELoss()
loss = criterion(out, target)
print(loss)
tensor(1.1196, grad_fn=<MseLossBackward>)
input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d
-> view -> linear -> relu -> linear -> relu -> linear
-> MSELoss
-> loss
print(loss.grad_fn) # MSELoss
print(loss.grad_fn.next_functions[0][0]) # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLU
<MseLossBackward object at 0x000001CD8A7F9888>
<AddmmBackward object at 0x000001CD8A7F9688>
<AccumulateGrad object at 0x000001CD8A7F9688>
# Pytorch中首先执行梯度清零
net.zero_grad()
print('before backward')
print(net.conv1.bias.grad)
loss.backward()
print('after backward')
print(net.conv1.bias.grad)
before backward
None
after backward
tensor([ 0.0067, -0.0037, 0.0111, -0.0024, -0.0077, 0.0114])
weight = weight - learning_rate * gradient
learning_rate = 0.01
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
# 导入优化器的包,optim包含若干常用的优化算法,比如SGD, Adam等
import torch.optim as optim
# 通过optim创建优化器对象
optimizer = optim.SGD(net.parameters(), lr = 0.01)
# 将优化器执行梯度清零的操作
optimizer.zero_grad()
output = net(input)
loss = criterion(output, target)
# 对损失值执行反向传播的操作
loss.backward()
# 参数的更新通过一行标准代码来执行
optimizer.step()
import torch
import torchvision
import torchvision.transforms as transforms #对图片进行调整转化
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(
root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(
trainset, batch_size=4, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(
root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(
testset, batch_size=4, shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck')
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
Broken pipe
,这是因为windows下线程文件读写的问题,需要把DataLoader方法中的num_workers设置为0。import numpy as np
import matplotlib.pyplot as plt
# 构建展示图片的函数
def imshow(img):
img = img / 2 + 0.5
npimg = img.numpy() # 只有先转化为numpy数据,才能应用matplot
plt.imshow(np.transpose(npimg, (1,2,0)))
plt.show()
# 从数据迭代器中读取一张图片
dataiter = iter(trainloader)
images, labels = dataiter.next()
# 展示图片
imshow(torchvision.utils.make_grid(images))
# 打印标签
print(" ".join('%5s' % classes[labels[j]] for j in range(4)))
cat ship ship plane
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 定义两个卷积层
self.conv1 = nn.Conv2d(3, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
# 定义池化层
self.pool = nn.MaxPool2d(2, 2)
# 定义三个全接连层
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10) #这几个参数只有120,84是可以改变的
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
# 变换x的形状以适配全连接层
x = x.view(-1, 16*5*5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
print(net)
Net(
(conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(fc1): Linear(in_features=400, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)
import torch.optim as optim
# 定义损失函数,使用交叉熵损失函数
criterion = nn.CrossEntropyLoss()
# 定义优化器,使用随机梯度下降优化器
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 训练模型
# 整体数据集遍历两轮
for epoch in range(2):
running_loss = 0.0
for i, data in enumerate(trainloader , 0):
# data中包含输入图象张量inputs,标签张量labels
inputs, labels = data
# 首先将优化器梯度归零
optimizer.zero_grad()
# 输入图像张量进网络, 得到输出张量outputs
outputs = net(inputs)
# 利用图像输出outputs和标签labels计算损失值
loss = criterion(outputs, labels)
# 反向传播+参数更新,标准代码的标准流程
loss.backward()
optimizer.step()
# 打印轮次和损失值
running_loss += loss.item()
if (i + 1) % 2000 == 0:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss/2000))
running_loss = 0.0
print('Finished Training')
[1, 2000] loss: 2.218
[1, 4000] loss: 1.939
[1, 6000] loss: 1.717
[1, 8000] loss: 1.580
[1, 10000] loss: 1.530
[1, 12000] loss: 1.488
[2, 2000] loss: 1.391
[2, 4000] loss: 1.405
[2, 6000] loss: 1.347
[2, 8000] loss: 1.359
[2, 10000] loss: 1.328
[2, 12000] loss: 1.297
Finished Training
# 保存模型
PATH = './cifat_net.pyh'
# 保存模型的状态字典
torch.save(net.state_dict(), PATH)
# 测试模型
dataiter = iter(testloader)
images, labels = dataiter.next()
# 打印原始图片
imshow(torchvision.utils.make_grid(images))
# 打印真实标签
print('GroundTruth: ', " ".join('%5s' % classes[labels[j]] for j in range(4)))
# 实例化类对象
net = Net()
# 加载训练阶段保存好的模型的状态字典
net.load_state_dict(torch.load(PATH))
# 利用模型对图片进行预测
outputs = net(images)
# 共有十个类别,采用模型计算出的概率最大的作为预测的类别(贪心)
_, predicted = torch.max(outputs, 1)
# 打印预测标签的结果
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))
发现测试的结果和实际结果有误差,这是很正常的,原因之一可能是因为模型数量较少。
可以看一下模型在全部测试集上的表现:
correct = 0
total = 0
with torch.no_grad(): # 表示代码块只对模型进行读取不对其进行改变
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d%%' % (
100 * correct / total))
Accuracy of the network on the 10000 test images: 52%
52%是一个很正常的数据,说明模型学到了东西。同时要十分警惕,如果模型正确率在10%左右,说明模型什么也没学到,就是全蒙猜到的10%正确率。
这个数据是一个很整体的数据,如果我们想更加细致的看一下模型在哪些类别上表现更好,可以分别进行准确率计算
# 对不同类别分别统计
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(4):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of %5s : %2d%%' %
(classes[i], 100*class_correct[i] / class_total[i]))
Accuracy of plane : 39%
Accuracy of car : 58%
Accuracy of bird : 30%
Accuracy of cat : 13%
Accuracy of deer : 36%
Accuracy of dog : 67%
Accuracy of frog : 69%
Accuracy of horse : 53%
Accuracy of ship : 74%
Accuracy of truck : 78%
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# 然后将模型转移到GPU
net.to(device)
# 最后在训练和测试时,每一步都将图片和标签张量转移到GPU上
inputs, labels = data[0].to(device), data[1].to(device)
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 19 20:18:46 2021
@author: Lancibe
"""
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
import torch
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
trainset = torchvision.datasets.CIFAR10(
root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(
trainset, batch_size=4, shuffle=True, num_workers=0)
testset = torchvision.datasets.CIFAR10(
root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(
testset, batch_size=4, shuffle=False, num_workers=0)
classes = ('plane', 'car', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck')
import numpy as np
import matplotlib.pyplot as plt
# 构建展示图片的函数
def imshow(img):
img = img / 2 + 0.5
npimg = img.numpy() # 只有先转化为numpy数据,才能应用matplot
plt.imshow(np.transpose(npimg, (1,2,0)))
plt.show()
# 从数据迭代器中读取一张图片
#dataiter = iter(trainloader)
#images, labels = dataiter.next()
# 展示图片
#imshow(torchvision.utils.make_grid(images))
# 打印标签
#print(" ".join('%5s' % classes[labels[j]] for j in range(4)))
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 定义两个卷积层
self.conv1 = nn.Conv2d(3, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
# 定义池化层
self.pool = nn.MaxPool2d(2, 2)
# 定义三个全接连层
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10) #这几个参数只有120,84是可以改变的
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
# 变换x的形状以适配全连接层
x = x.view(-1, 16*5*5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
device = torch.device('cuda' if torch.cuda.is_available() else "cpu")
net = Net()
net.to(device)
#print(net)
import torch.optim as optim
# 定义损失函数,使用交叉熵损失函数
criterion = nn.CrossEntropyLoss()
# 定义优化器,使用随机梯度下降优化器
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 训练模型
# 整体数据集遍历两轮
for epoch in range(2):
running_loss = 0.0
for i, data in enumerate(trainloader , 0):
# data中包含输入图象张量inputs,标签张量labels
inputs, labels = data[0].to(device), data[1].to(device)
# 首先将优化器梯度归零
optimizer.zero_grad()
# 输入图像张量进网络, 得到输出张量outputs
outputs = net(inputs)
# 利用图像输出outputs和标签labels计算损失值
loss = criterion(outputs, labels)
# 反向传播+参数更新,标准代码的标准流程
loss.backward()
optimizer.step()
# 打印轮次和损失值
running_loss += loss.item()
if (i + 1) % 2000 == 0:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss/2000))
running_loss = 0.0
print('Finished Training')
# 保存模型
PATH = './cifat_net.pyh'
# 保存模型的状态字典
torch.save(net.state_dict(), PATH)
# 测试模型
dataiter = iter(testloader)
images, labels = dataiter.next()
# 打印原始图片
#imshow(torchvision.utils.make_grid(images))
# 打印真实标签
#print('GroundTruth: ', " ".join('%5s' % classes[labels[j]] for j in range(4)))
# 实例化类对象
#net = Net()
# 加载训练阶段保存好的模型的状态字典
net.load_state_dict(torch.load(PATH))
# 利用模型对图片进行预测
#outputs = net(images)
# 共有十个类别,采用模型计算出的概率最大的作为预测的类别(贪心)
#_, predicted = torch.max(outputs, 1)
# 打印预测标签的结果
#print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4)))
'''
correct = 0
total = 0
with torch.no_grad(): # 表示代码块只对模型进行读取不对其进行改变
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d%%' % (
100 * correct / total))
'''
# 对不同类别分别统计
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in testloader:
images, labels = data[0].to(device), data[1].to(device)
outputs = net(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(4):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of %5s : %2d%%' %
(classes[i], 100*class_correct[i] / class_total[i]))