pytorch 構建網絡模型的方法

1.常規

class Logistic_regression_1(nn.Module):
    def __init__(self):
        super(Logistic_regression_1, self).__init__()
        self.lr = nn.Linear(2, 1)
        self.sm = nn.Sigmoid()
    
    def forward(self, x):
        x = self.lr(x)
        x = self.sm(x)
        return x

2.sequential

class Logistic_regression_2(nn.Module):
    def __init__(self):
        super(Logistic_regression_2, self).__init__()
        self.lr = torch.nn.Sequential(
            nn.Linear(2, 1)
        )
        self.sm = torch.nn.Sequential(
            nn.Sigmoid()
        )

    def forward(self, x):
        x = self.lr(x)
        x = self.sm(x)
        return x

3.add_module


class Logistic_regression_3(torch.nn.Module):
    def __init__(self):
        super(Logistic_regression_3, self).__init__()
        self.lr = torch.nn.Sequential()
        self.lr.add_module("lr",torch.nn.Linear(2, 1))
        
        self.sm = torch.nn.Sequential()
        self.sm.add_module("sm",torch.nn.Sigmoid())
       

    def forward(self, x):
        x = self.lr(x)
        x = self.sm(x)
        return x

4.OrderedDict

import torch
from collections import OrderedDict
class Logistic_regression_4(torch.nn.Module):
    def __init__(self):
        super(Logistic_regression_4, self).__init__()
        self.lr = torch.nn.Sequential(
            OrderedDict(
                [
                    ("lr", torch.nn.Linear(2, 1)),
                    
                ]
            ))

        self.sm = torch.nn.Sequential(
            OrderedDict([
                 ("sm", torch.nn.Sigmoid()),
                
            ])
        )
    
    def forward(self, x):
        x = self.lr(x)
        x = self.sm(x)
        return x

model = Net4()

print(model)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章