Import torch import torch. Nn as nn import torch. Nn. Functional as F x = torch. Randn (3,2,5,6)## means [batch_size,in_chnnedls,height,width]
Conv2d parameters [input_channels_number,output_channedls_output,height,width]
# nn. Linear parameter [input_features output_features]class Net(nn.Module): def __init__(self): Super (Net,self).__init__() self.conv1 = nn.Conv2d(1,6,3) self.fc1 = nn.Linear(16*6*6,120) Self. Fc2 = nn.Linear(120,84) def forward(self, x): X = f. may ax_pool2d (F.r elu (self conv1 (x)), (2, 2)) x = f. may ax_pool2d (F.r elu (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)) Number of parameters to train
print(params[0].size()) ## The size parameter of the first layer trainingInput = torch. Randn (1,1,32,32) out = net(input)print(out)

net.zero_grad() Clear gradient cache

##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()

## Update parameters using formulasLearning_rate = 0.01for f in net.parameters():
    f.data.sub_(f.grad.data * learning_rate)

## Update with off-the-shelf packagesImport 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) ## Backpropagation calculation diagram
print(loss.grad_fn.next_functions[0][0])

print(net.conv1.bias.grad)
Copy the code