照着博客大佬提供的LeNet网络自己敲了一个,但是因为第一次接触python小白,报了这个很简单的错误,从名字来看是模型没有该属性,找了好久才发现是__init__()的原因,
最好小白刚刚学习LeNet的时候不要自己手打需要的属性,直接继承就好了,省时省力还不出错,踩坑+1
附上结果
LeNet(
(conv1): Conv2d(3, 16, kernel_size=(5, 5), stride=(1, 1))
(pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(conv2): Conv2d(16, 32, kernel_size=(5, 5), stride=(1, 1))
(pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(fc1): Linear(in_features=800, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)
附上代码
import torch
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module):
#搭建网络
def __init__(self):
super(LeNet,self).__init__()
self.conv1 = nn.Conv2d(in_channels=3,out_channels=16,kernel_size=5)
self.pool1=nn.MaxPool2d(2,2)
self.conv2=nn.Conv2d(16,32,5)
self.pool2=nn.MaxPool2d(2,2)
self.fc1=nn.Linear(32*5*5,120)
self.fc2=nn.Linear(120,84)
self.fc3=nn.Linear(84,10)
def forward(self,x):
x=F.relu(self.conv1(x))
x=self.pool1(x)
x=F.relu(self.conv2(x))
x=self.pool2(x)
x=x.view(-1,32*5*5)
x=F.relu(self.fc1(x))
x=F.relu(self.fc2(x))
x=self.fc3(x)
return x
#测试输出
input=torch.rand([1,3,32,32])
model=LeNet()
output=model(input)
print(model)
print(output.shape)