使用pytorch进行网络模型的搭建、保存与加载,是非常快速、方便的。
搭建ConvNet
所有的网络都要继承torch.nn.Module,然后在构造函数中使用torch.nn中的提供的接口定义layer的属性,最后,在forward函数中将各个layer连接起来。
下面,以LeNet为例:
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(3, 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)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = x.view(x.size(0), -1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
out = self.fc3(x)
retur