1、首先導入共用的包
import torch.nn as nn
2、構模組化型的四種方法
2.1 第一種方法
import torch.nn as nn
#Method 1 ------------------------------------------------------------------------------
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()#以上固定
self.linear = nn.Linear(1, 1) #輸入和輸出的次元都是1
def forward(self, x):
x=self.linear(x)
return x
model1=LinearRegression()
print(model1)
LinearRegression(
(linear): Linear(in_features=1, out_features=1, bias=True)
)
這種方法比較常用,早期的教程通常就是使用這種方法。
2.2 第二種方法
import torch.nn as nn
#Method2 ---------------------------------------------------------------------------------
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression,self).__init__()
self.dense=nn.Sequential(
nn.Linear(1,1)
)
def forward(self, x):
x=nn.Linear(x)
print("Method 2:")
model2=LinearRegression()
print(model2)
LinearRegression(
(dense): Sequential(
(0): Linear(in_features=1, out_features=1, bias=True)
)
)
這種方法利用torch.nn.Sequential()容器進行快速搭建,模型的各層被順序添加到容器中。缺點是每層的編号是預設的阿拉伯數字,不易區分
2.3 第三種方法
import torch.nn as nn
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression,self).__init__()
self.dense=nn.Sequential()
self.dense.add_module("dense1",nn.Linear(1,1))
def forward(self, x):
x=nn.Linear(x)
return x
model3=LinearRegression()
print(model3)
LinearRegression(
(dense): Sequential(
(dense1): Linear(in_features=1, out_features=1, bias=True)
)
)
這種方法是對第二種方法的改進:通過add_module()添加每一層,并且為每一層增加了一個單獨的名字。