做物流有哪些网站,优秀的营销案例,wordpress自动发货如何设置,网站如何做邮箱订阅目录 构建模型模型中的可训练参数假设输入尺寸为32*32损失函数反向传播更新网络参数 构建模型
import torch
import torch.nn as nn
import torch.nn.functional as Fclass Net(nn.Module):def __init__(self):super(Net,self).__init__()#定义第一层卷积层#xff0c;输入维… 目录 构建模型模型中的可训练参数假设输入尺寸为32*32损失函数反向传播更新网络参数 构建模型
import torch
import torch.nn as nn
import torch.nn.functional as Fclass Net(nn.Module):def __init__(self):super(Net,self).__init__()#定义第一层卷积层输入维度1输出维度6卷积核大小3*3self.conv1nn.Conv2d(1,6,3)self.conv2nn.Conv2d(6,16,3)self.fc1nn.Linear(16*6*6,120)self.fc2nn.Linear(120,84)self.fc3nn.Linear(84,10)def forward(self,x):#注意任意卷积层后面要加激活层池化层xF.max_pool2d(F.relu(self.conv1(x),(2,2)))xF.max_pool2d(F.relu(self.conv2(x),2))xx.view(-1,self.num_flat_features(x))xF.relu(self.fc1(x))xF.relu(self.fc2(x))xself.fc3(x)return xdef num_flat_features(self,x):sizex.size()[1:]num_features1for s in size:num_features*sreturn num_featuresnetNet()
print(net)模型中的可训练参数
paramslist(net.parameters())
print(len(params))
print(params[0].size()) #conv1的参数假设输入尺寸为32*32
inputtorch.randn(1,1,32,32) #个数通道数长宽
outnet(input)
print(out)
print(out.size())注意
损失函数 targettorch.randn(10)
targettarget.view(1,-1)
criterionnn.MSELoss()
losscriterion(out,target)
print(loss)print(loss.grad_fn)
print(loss.grad_fn.next_functions[0][0]) #上一层的grad_fn
print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) #上上一层的grad_fn反向传播 #首先要执行梯度清零的操作
net.zero_grad()print(conv1.bisa.grad before backward)
print(net.conv1.bias.grad)#实现一次反向传播
loss.backward()print(conv1.bisa.grad after backward)
print(net.conv1.bias.grad)更新网络参数 #导入优化器包
import torch.optim as optim
#构建优化器
optimizeroptim.SGD(net.parameters(),lr0.01)
#优化器梯度清零
optimizer.zero_grad()
#进行网络计算并计算损失值
outputnet(input)
losscriterion(output,target)
#执行反向传播
loss.backward()
#更新参数
optimizer.step()