天天看点

pytorch构建模型三种方法

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()添加每一层,并且为每一层增加了一个单独的名字。

继续阅读