pytorch搭建神经网络五种方式
在进行深度学习的时候,往往会使用神经网络,而神经网络要么自己进行搭建,要么直接从官网上下载已经训练好的神经网络模型。
之前没有用几次markdown,所以排版有些混乱。
方式一 官网直接下载
from torchvision import datasets, transforms, models
model_ft = models.resnet50(pretrained=True)
print(model_ft)
这种方式下载现有的模型
def __init__(self, class_num = 751):
super(ft_net, self).__init__()
model_ft = models.resnet50(pretrained=True) #下载模型
model_ft.avgpool = nn.AdaptiveAvgPool2d((1,1))#将最后的宽x高无脑改为1*1,为啥这样我也不知道
self.model = model_ft
self.classifier = torch.nn.Linear(2048, class_num) # 对网络进行修改,在网络lay4后面加了classifier.
方式二 自己进行搭建
这种方式的好处就是自己可以随便修改其中神经元个数和隐藏层数。自己进行搭建的话是有四种不同的语法。
# Method 1 -----------------------------------------
class Net1(torch.nn.Module):
def __init__(self):
super(Net1, self).__init__()
self.conv1 = torch.nn.Conv2d(3, 32, 3, 1, 1)
self.dense1 = torch.nn.Linear(32 * 3 * 3, 128)
self.dense2 = torch.nn.Linear(128, 10)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv(x)), 2)
x = x.view(x.size(0), -1)
x = F.relu(self.dense1(x))
x = self.dense2()
return x
print("Method 1:")
model1 = Net1()
print(model1)
我比较喜欢下面这种
# -----Method 2 ------------------------------------------
class Net2(torch.nn.Module):
def __init__(self):
super(Net2, self).__init__()
self.conv = torch.nn.Sequential(
torch.nn.Conv2d(3, 32, 3, 1, 1),
torch.nn.ReLU(),
torch.nn.MaxPool2d(2))
self.dense = torch.nn.Sequential(
torch.nn.Linear(32 * 3 * 3, 128),
torch.nn.ReLU(),
torch.nn.Linear(128, 10)
)
def forward(self, x):
conv_out = self.conv1(x)
res = conv_out.view(conv_out.size(0), -1)
out = self.dense(res)
return out
print("Method 2:")
model2 = Net2()
print(model2)
# Method 3 -------------------------------
class Net3(torch.nn.Module):
def __init__(self):
super(Net3, self).__init__()
self.conv = torch.nn.Sequential()
self.conv.add_module("conv1", torch.nn.Conv2d(3, 32, 3, 1, 1))
self.conv.add_module("relu1", torch.nn.ReLU())
self.conv.add_module("pool1", torch.nn.MaxPool2d(2))
self.dense = torch.nn.Sequential()
self.dense.add_module("dense1", torch.nn.Linear(32 * 3 * 3, 128))
self.dense.add_module("relu2", torch.nn.ReLU())
self.dense.add_module("dense2", torch.nn.Linear(128, 10))
def forward(self, x):
conv_out = self.conv1(x)
res = conv_out.view(conv_out.size(0), -1)
out = self.dense(res)
return out
print("Method 3:")
model3 = Net3()
print(model3)
# Method 4 ------------------------------------------
class Net4(torch.nn.Module):
def __init__(self):
super(Net4, self).__init__()
self.conv = torch.nn.Sequential(
OrderedDict(
[
("conv1", torch.nn.Conv2d(3, 32, 3, 1, 1)),
("relu1", torch.nn.ReLU()),
("pool", torch.nn.MaxPool2d(2))
]
))
self.dense = torch.nn.Sequential(
OrderedDict([
("dense1", torch.nn.Linear(32 * 3 * 3, 128)),
("relu2", torch.nn.ReLU()),
("dense2", torch.nn.Linear(128, 10))
])
)
def forward(self, x):
conv_out = self.conv1(x)
res = conv_out.view(conv_out.size(0), -1)
out = self.dense(res)
return out
print("Method 4:")
model4 = Net4()
print(model4)