# PyTorch实战：卷积神经网络的实现

LeNet模型如下所示：

``````from torch import nn
class LeNet (nn.Module):``````

``def __init__(self):``

``````super().__init__()
self.conv1=nn.Con2d(1, 20, 5, 1)
self.conv2=nn.Con2d(20, 50, 5, 1)``````

``````self.fully1=nn.Linear(4*4*50, 500)
self.fully2=nn.Linear(500, 10)``````

``````import torch.nn.functional as func
def forward(self, x):``````

``````x=func.relu(self.conv1(x))
x=func.max_pool2d(x, 2, 2)
x=func.relu(self.conv1(x))
x=func.max_pool2d(x, 2, 2)
x=x.view(-1, 4*4*50)	#Reshaping the output into desired shape
x=func.relu(self.fully1(x))	#Applying relu activation function to our first fully connected layer
x=self.fully2(x)	#We will not apply activation function here because we are dealing with multiclass dataset
return x``````

``model=LeNet()``

## 完整的代码

``````import torch
import matplotlib.pyplot as plt
import numpy as np
import torch.nn.functional as func
import PIL.ImageOps
from torch import nn
from torchvision import datasets, transforms
transform1=transforms.Compose([transforms.Resize((28, 28)), transforms.ToTensor(), transforms.Normalize((0.5, ), (0.5, ))])
def im_convert(tensor):
image=tensor.clone().detach().numpy()
image=image.transpose(1, 2, 0)
print(image.shape)
image=image*(np.array((0.5, 0.5, 0.5))+np.array((0.5, 0.5, 0.5)))
image=image.clip(0, 1)
return image
images, labels=dataiter.next()
fig=plt.figure(figsize=(25, 4))
for idx in np.arange(20):
plt.imshow(im_convert(images[idx]))
ax.set_title([labels[idx].item()])
class LeNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1=nn.Conv2d(1, 20, 5, 1)
self.conv2=nn.Conv2d(20, 50, 5, 1)
self.fully1=nn.Linear(4*4*50, 500)
self.fully2=nn.Linear(500, 10)
def forward(self, x):
x=func.relu(self.conv1(x))
x=func.max_pool2d(x, 2, 2)
x=func.relu(self.conv2(x))
x=func.max_pool2d(x, 2, 2)
x=x.view(-1, 4*4*50)	#Reshaping the output into desired shape
x=func.relu(self.fully1(x))	#Applying relu activation function to our first fully connected layer
x=self.fully2(x)	#We will not apply activation function here because we are dealing with multiclass dataset
return x
model=LeNet()``````

• 回顶