利用pytorch来构建网络模型有很多种方法,以下简单列出其中的四种。
假设构建一个网络模型如下:
首先导入几种方法用到的包:
进口火炬 进口torch.nn。功能和F 从进口OrderedDict集合 >之前<强>第一种方法强>
#方法1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 类Net1 (torch.nn.Module): def __init__(自我): 超级(Net1自我). __init__ () 自我。conv1=torch.nn。Conv2d(3, 32岁,3,1,1) self.dense1=torch.nn。线性(32 * 3 * 3,128) self.dense2=torch.nn。线性(128年,10) def向前(自我,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 (x) 返回x print(方法1:) model1=Net1 () 打印(model1) >之前这种方法比较常用,早期的教程通常就是使用这种方法。
<强>第二种方法
强>#方法2 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 类Net2 (torch.nn.Module): def __init__(自我): 超级(Net2自我). __init__ () 自我。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。线性(32 * 3 * 3,128), torch.nn.ReLU (), torch.nn。线性(128年,10) ) def向前(自我,x): conv_out=self.conv1 (x) res=conv_out.view (conv_out.size (0) 1)=self.dense (res) 返回了 print(方法2:) model2=Net2 () 打印(model2) >之前
这种方法利用torch.nn。连续()容器进行快速搭建,模型的各层被顺序添加到容器中。缺点是每层的编号是默认的阿拉伯数字,不易区分。
<强>第三种方法:
强>#方法3 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 类Net3 (torch.nn.Module): def __init__(自我): 超级(Net3自我). __init__ () self.conv=torch.nn.Sequential () torch.nn self.conv.add_module (“conv1”。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向前(自我,x): conv_out=self.conv1 (x) res=conv_out.view (conv_out.size (0) 1)=self.dense (res) 返回了 打印(“方法3:”) model3=Net3 () 打印(model3) >之前
这种方法是对第二种方法的改进:通过add_module()添加每一层,并且为每一层增加了一个单独的名字只
<强>第四种方法:
强>#方法4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 类Net4 (torch.nn.Module): def __init__(自我): 超级(Net4自我). __init__ () 自我。conv=torch.nn.Sequential ( OrderedDict ( ( (“conv1 torch.nn。Conv2d(3, 32岁,3,1,1)), (“relu1”, torch.nn.ReLU ()), (“池”,torch.nn.MaxPool2d (2)) ] )) self.dense=torch.nn.Sequential ( OrderedDict ([ (“dense1 torch.nn。线性(32 * 3 * 3,128)), (“relu2”, torch.nn.ReLU ()), (“dense2 torch.nn。线性(128年,10)) ]) ) def向前(自我,x): conv_out=self.conv1 (x) res=conv_out.view (conv_out.size (0) 1)=self.dense (res) 返回了 打印(“方法4:”) model4=Net4 () 打印(model4) >之前
pytorch构建网络模型的4种方法