# 机器学习：基于PyTorch搭建神经网络

## 1，PyTorch安装

### 1.1，不需切换版本

PyTorch只对CUDA版本有要求，对于cudnn没有要求，甚至不需要安装。查看方式如下：

## 2，PyTorch基础知识

### 2.1，构造Tensor

``````#生成随机Tensor
import torch
x = torch.Tensor(2, 3)
print(x)
================================================
tensor([[-7.5173e-01,  9.3731e-38, -1.5563e-04],
[ 9.3731e-38, -4.4988e-05,  9.3731e-38]])``````
``````#利用list构造Tensor
import torch
x = torch.Tensor([1,2,3])
print(x)
y = torch.Tensor([[1,2,3],[6,5,4]])
print(y)
===================================
tensor([1., 2., 3.])
tensor([[1., 2., 3.],
[6., 5., 4.]])``````
``````import torch
#随机元素值0~1之间矩阵
x= torch.rand(3,3)
print(x)
#元素全部为0的矩阵
x= torch.zeros(3,3)
print(x)
#元素全部为1的矩阵
x= torch.ones(3,3)
print(x)
==================================
tensor([[0.3766, 0.8037, 0.7080],
[0.9064, 0.4387, 0.0712],
[0.0787, 0.1682, 0.7385]])
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])``````

``````x = torch.ones(3, 3)
print(x.size())
====================
torch.Size([3, 3])``````

### 2.2，Tensor操作

``````x=torch.ones(2,3)
y=torch.ones(2,3)*2
print(x+y)
print(x*y)``````

Tensor也支持NumPy中各种切片操作，比如操作矩阵的某一列：

``````x = torch.ones(3, 3)
x[:, 1] = x[:, 1] + 2
print(x)
====================
tensor([[3., 3., 3.],
[1., 1., 1.],
[1., 1., 1.]])
``````

``````x = torch.ones(3, 3)
x=x.view(1,9)
print(x)
==============================================
tensor([[1., 1., 1., 1., 1., 1., 1., 1., 1.]])``````

### 2.3，Tensor和NumPy array间的转化

Torch的Tensor和NumPy的array可以非常方便地进行相互转化。但是需要注意的是，它们会共享内存的地址，所以修改其中一个会导致另外一个也发生改变。

``````import torch
x = torch.ones(2, 3)
print(x)
y = x.numpy()
print(y)
print(y)
z = torch.from_numpy(y)
print(z)
========================
tensor([[1., 1., 1.],
[1., 1., 1.]])
[[1. 1. 1.]
[1. 1. 1.]]
[[3. 3. 3.]
[3. 3. 3.]]
tensor([[3., 3., 3.],
[3., 3., 3.]])``````

``````import torch
x = Variable(torch.ones(2, 2) * 2, requires_grad=True)
print(x)
print(x.data)
=====================================================
tensor([[2., 2.],
tensor([[2., 2.],
[2., 2.]])``````

``````x = Variable(torch.ones(2, 2) * 2, requires_grad=True)
y = 2 * (x * x) + 5 * x
print(y)
=============================
tensor([[18., 18.],

可以看作一个关于的函数，它关于  的梯度  的表达式我们可以通过计算得到：现在中的每一个元素值都是 ，将其带入  得到值

``````import torch
x = Variable(torch.ones(2, 2) * 2, requires_grad=True)
y = 2 * (x * x) + 5 * x
y=y.sum()
y.backward()
=====================
tensor([[13., 13.],
[13., 13.]])``````

## 3，PyTorch中搭建神经网络

### 3.1，定义神经网络

``````import torch
import torch.nn.functional as F
import torch.nn as nn

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)  # 输入3个通道，输出6个通道，卷积核5*5
self.fc1 = nn.Linear(16 * 5 * 5, 120)  # 输入84维，输出10维
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)

# 在init中我们值定义了搭建网络的层，但没有真正定义网络的结构
# 真正的输入输出关系是在forward()方法中定义的，控制数据在网络中的流动方式
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), 2)  # 激活函数ReLU，先经过一个卷积层，然后一个全连接层
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
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``````

PS：torch.nn中要求输入的数据是一个mini-batch，因为我们的图像数据（CIFAR-10）本身是3维的，所以forward()的输入x是4维的，在经过两个卷积层之后还是4维的Tensor，所以在输入后面的全连接层之前我们先使用.view()方法将其转化为2维的Tensor。

``````if __name__ == '__main__':
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))
(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)
)``````

``````params = list(net.parameters())
print(len(params))
print(params[0].size())
print(params[1].size())
===============================
10
torch.Size([6, 3, 5, 5])
torch.Size([6])
``````

``````print(net.conv1.weight.size())
print(net.conv1.bias.size())
=====================================
torch.Size([6, 3, 5, 5])
torch.Size([6])
True
``````

``````input = Variable(torch.rand(1,3,32,32))
output = net(input)
print(output)
================================================================================
tensor([[ 0.1417,  0.0634, -0.0652, -0.0445,  0.0899,  0.0334,  0.0029, -0.0582,

### 3.2，训练神经网络

``criterion = nn.CrossEntropyLoss()``

``````if __name__ == '__main__':
net = Net()
criterion = nn.CrossEntropyLoss()
input = Variable(torch.rand(1, 3, 32, 32))
output = net(input)
print(output)
label = Variable(torch.LongTensor([4]))
print(label)
loss = criterion(output,label)
print(loss)
================================================================================
tensor([[ 0.1201,  0.0682,  0.0639,  0.0945, -0.0587,  0.0728,  0.0730,  0.1388,
tensor([4])

``````import torch.optim as optim
optimizer = optim.SGD(net.parameters(),lr=0.001,momentum=0.9)``````

``````print(net.conv1.bias)
==============================
Parameter containing:
tensor([ 0.0416, -0.0456, -0.0261,  0.0349, -0.0015, -0.0484],

``````if __name__ == '__main__':
net = Net()
print(net.conv1.bias)
criterion = nn.CrossEntropyLoss()  # 损失函数
input = Variable(torch.rand(1, 3, 32, 32))
output = net(input)
print(output)
label = Variable(torch.LongTensor([4]))
loss = criterion(output, label)
print(loss)
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
loss.backward() #计算梯度
optimizer.step()
print(net.conv1.bias)
===========================================
Parameter containing:
tensor([ 0.0580,  0.0789,  0.0258, -0.0612, -0.0216,  0.0890],
tensor([[-0.0903, -0.0205,  0.0408, -0.0373,  0.0255,  0.0164,  0.1519,  0.1117,
Parameter containing:
tensor([ 0.0580,  0.0789,  0.0258, -0.0613, -0.0216,  0.0891],

### 3.3，在CIFAR-10数据集上进行训练和测试

``````import torch.utils.data
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))]
)
transform = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
)

classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
``````

``````import matplotlib.pyplot as plt
import numpy as np
# functions to show an image
def imshow(img):
img = img / 2 + 0.5  # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
# get some random training images
images, labels = dataiter.next()
# show images
imshow(torchvision.utils.make_grid(images))
# print labels
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.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)

def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(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
``````

``````criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)``````

• 先通过 `optimizer.zero_grad()` 把梯度清理干净，防止受之前遗留梯度的影响。
• `outputs = net(inputs)`, 把图片数据送到网络里面，得到预测结果。
• `loss = criterion(outputs, labels)`, 计算当前 batch 的损失值。
• `loss.backward()`，执行链式求导，计算梯度。
• `optimizer.step()`，通过4中计算出来的梯度，更新每个可训练权重。
``````net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

for epoch in range(5):

running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
inputs, labels = Variable(inputs), Variable(labels)
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 6000 == 5999:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 6000))
running_loss = 0.0

print('Finished Training')``````

``````# 测试模型
correct = 0
total = 0
images, labels = data
outputs = net(Variable(images))
# 返回可能性最大的索引 -> 输出标签
_, predicted = torch.max(outputs, 1)
total += labels.size(0)
correct += (predicted == labels).sum()

print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))
==============================================
Accuracy of the network on the 10000 test images: 62 %``````

``````class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
images, labels = data
outputs = net(Variable(images))
_, predicted = torch.max(outputs.data, 1)
c = (predicted == labels).squeeze()
for i in range(4):  # mini-batch's size = 4
label = labels[i]
class_correct[label] += c[i]
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 : 69 %
Accuracy of   car : 66 %
Accuracy of  bird : 58 %
Accuracy of   cat : 35 %
Accuracy of  deer : 54 %
Accuracy of   dog : 56 %
Accuracy of  frog : 70 %
Accuracy of horse : 73 %
Accuracy of  ship : 71 %
Accuracy of truck : 67 %``````

### 3.4，模型的保存和加载

``````print(net.state_dict().keys())
print(net.state_dict()['conv1.bias'])
============================================================================
odict_keys(['conv1.weight', 'conv1.bias', 'conv2.weight', 'conv2.bias', 'fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias', 'fc3.weight', 'fc3.bias'])
tensor([ 0.0970, -0.3732, -0.6456, -0.3526,  0.4653, -0.4466])``````

``````torch.save(net.state_dict(), './data/' + 'model.pt')

### 3.5，代码

``````import torch.utils.data
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim

transform = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
)

classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')

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)  # 输入3个通道，输出6个通道，卷积核5*5
self.fc1 = nn.Linear(16 * 5 * 5, 120)  # 输入84维，输出10维
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)

# 在init中我们值定义了搭建网络的层，但没有真正定义网络的结构
# 真正的输入输出关系是在forward()方法中定义的，控制数据在网络中的流动方式
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), 2)  # 激活函数ReLU，先经过一个卷积层，然后一个全连接层
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
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()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 训练模型
# for epoch in range(5):
#
#     running_loss = 0.0
#     for i, data in enumerate(trainloader, 0):
#         inputs, labels = data
#         inputs, labels = Variable(inputs), Variable(labels)
#         outputs = net(inputs)
#         loss = criterion(outputs, labels)
#         loss.backward()
#         optimizer.step()
#         running_loss += loss.item()
#         if i % 6000 == 5999:
#             print('[%d, %5d] loss: %.3f' %
#                   (epoch + 1, i + 1, running_loss / 6000))
#             running_loss = 0.0

print('Finished Training')
# 保存训练好的模型
#torch.save(net.state_dict(), './data/' + 'model.pt')
print(net.state_dict().keys())
print(net.state_dict()['conv1.bias'])

# 测试模型
# correct = 0
# total = 0
#     images, labels = data
#     outputs = net(Variable(images))
#     # 返回可能性最大的索引 -> 输出标签
#     _, predicted = torch.max(outputs, 1)
#     total += labels.size(0)
#     correct += (predicted == labels).sum()
#
# 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))
#     images, labels = data
#     outputs = net(Variable(images))
#     _, predicted = torch.max(outputs.data, 1)
#     c = (predicted == labels).squeeze()
#     for i in range(4):  # mini-batch's size = 4
#         label = labels[i]
#         class_correct[label] += c[i]
#         class_total[label] += 1
#
# for i in range(10):
#     print('Accuracy of %5s : %2d %%' % (
#         classes[i], 100 * class_correct[i] / class_total[i]
#     ))
``````

THE END

)">