import torchc++
import torch.nn as nn网络
import torch.nn.functional as F #这个是函数形式定义,相对来讲更低层一点。ide
"""函数
Net(oop
(conv1): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1))优化
(conv2): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1))ci
(fc1): Linear(in_features=576, out_features=120, bias=True)get
(fc2): Linear(in_features=120, out_features=84, bias=True)input
(fc3): Linear(in_features=84, out_features=10, bias=True)it
)
"""
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 3x3 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 3)#注意这里1的大小是1*1*32*32
self.conv2 = nn.Conv2d(6, 16, 3)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
#卷经层计算公式:(w-k+2p)/s+1 k表明卷积尺寸,p是填充,s是步幅;
#池化层计算公式:(w-k)/s+1
def forward(self, x):
# Max pooling over a (2, 2) window
# conv1 layer calc:32-3+2*0/1+1 = 30
# pool1 layer calc:30/2 = 15
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
#print(y.size())
# If the size is a square you can only specify a single number
#conv2 layer calc:15-3+2*0/1+1=13
#pool2 layer calc:13/2=6 这里的问题是剩下的省略了?
x = F.max_pool2d(F.relu(self.conv2(x)), 2)#x 16*6*6
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
#原有尺寸为1*16*6*6;准确尺寸是16*6*6,第一个维度不要;
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension 取每个维度尺寸
num_features = 1
for s in size:#将每个维度尺寸乘;最终便是总的尺寸。
num_features *= s
return num_features
net = Net()
print(net)
params = list(net.parameters())#存储其全部参数,依然是张量,打印后格式为:
"""
torch.Size([6, 1, 3, 3]) torch.Size([6]) torch.Size([16, 6, 3, 3]) torch.Size([16]) torch.Size([120, 576]) torch.Size([120])
torch.Size([84, 120]) torch.Size([84])
torch.Size([10, 84]) torch.Size([10])
"""
for i in range(len(params)):
print(params[i].size(),end=' ')
input = torch.randn(1, 1, 32, 32)#随机输入
out = net(input)
print(out)
net.zero_grad( )#将全部梯度归零
out.backward(torch.randn(1,10))#反向传播,注意这里的传入方式是以前所说的雅各布矩阵
#偏差
output = net(input)
target = torch.randn(10)
target = target.view(1,-1)
loss = nn.MSELoss()(output,target)#相似c++函数传入两个参数,直观上不大好看;
print(loss)#会进行相似输出:tensor(0.4308, grad_fn=<MseLossBackward>)
#若是须要查看其调用属性,可进行以下相似操做
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
#也能够采起以下方式查看
tmpPrint = loss.grad_fn
for i in range(2):
print(tmpPrint.next_functions[0][0])
tmpPrint = tmpPrint.next_functions[0][0]
#反向传播
net.zero_grad()#主要目的是防止微分时出现异常;
print('conv1.bias.grad before backward',net.conv1.bias.grad)
loss.backward()
print('conv1.bias.grad after backward',net.conv1.bias.grad)
#更新权重
learning_rate=0.01
for f in net.parameters():
f.data.sub_(f.grad.data*learning_rate)
#根据NN的特色,咱们可能会考虑使用不一样的更新规则;因此整个流程简化为:
import torch.optim as optim
# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)#优化器
# in your training loop:
optimizer.zero_grad() # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step() # Does the update
"""
因此整个流程变成:
1.定义网络结构
2.输入数据正向计算
3.计算损失
4.进行反向传播
5.更新参数(方法可选)
"""