import torch.nn as nn
import torch.nn.functional as F
import torch
import torch.optim as optim
class LeNet(nn.Module):
# 构造方法里面定义可学习参数的层
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
# forward定义输入数据进行前向传播
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), 2)
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = x.view(x.size()[0], -1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
if __name__ == '__main__':
net = LeNet()
optimizer = optim.SGD(net.parameters(), lr=0.1)
criterion = nn.MSELoss()
input = torch.randn(1, 1, 32, 32)
target = torch.arange(0, 10)
target = target.view(-1, 10).float()
# print(net)
# print(len(list(net.parameters())))
# for name, para in net.named_parameters():
# print(name, para.size())
output = net(input)
loss = criterion(output, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
pytorch实现LeNet网络结构
最新推荐文章于 2024-06-26 09:57:38 发布