import torch
import torch.nn as nn
import torch.nn.functional as F
classNet(nn.Module):# 括号里的为父类def__init__(self):# 构造方法super(Net, self).__init__()
self.conv1 = nn.Conv2d(1,6,3)# 1个输入,6个输出特征,3x3的卷积核
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)defforward(self, x):
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))# -1不指定reshape成多少行,根据具体情况
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)return x
defnum_flat_features(self, x):
size = x.size()[1:]
num_features =1for s in size:
num_features *= s
return num_features
net = Net()input= torch.randn(1,1,32,32)# nSamples x nChannels x Height x Width, channels为特征的数量
output = net(input)
target = torch.randn(10)
target = target.view(1,-1)
criterion = nn.MSELoss()# 损失函数
loss = criterion(output, target)
loss
tensor(0.9012, grad_fn=<MseLossBackward>)
net.zero_grad()
loss.backward()
learning_rate =0.01for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)