Pytorch搭建一个入门网络

395 阅读1分钟

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

x = torch.randn(3,2,5,6) ##意味着[batch_size,in_chnnedls,height,width]
#Conv2d的参数 [input_channels_number,output_channedls_output,height,width]
#nn.Linear参数 [input_features,output_features]

class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__()
        self.conv1 = nn.Conv2d(1,6,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):
        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

    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)
params = list(net.parameters())
print(params)
print(len(params)) ##需要训练的参数个数
print(params[0].size()) ##第一层训练的参数size

input = torch.randn(1,1,32,32)
out = net(input)
print(out)

net.zero_grad() #清除梯度缓存

##loss fucntion
target = torch.randn(10)
print(target)
print(target.size())
target = target.view(1,-1)
print(target)
criterion = nn.MSELoss()
net.zero_grad()
print(net.conv1.bias.grad)
loss = criterion(out,target)
loss.backward()

## 更新参数使用公式
learning_rate = 0.01
for f in net.parameters():
    f.data.sub_(f.grad.data * learning_rate)

## 使用现成包进行更新
import torch.optim as optim
optimizer = optim.SGD(net.parameters(),lr = 0.1)

optimizer.zero_grad()
output = net(input)
loss = criterion(output,target)
loss.backward()
optimizer.step()

print(target.size())
print(loss.grad_fn)
print(loss.grad_fn.next_functions) ##反向传播计算图
print(loss.grad_fn.next_functions[0][0])

print(net.conv1.bias.grad)