Torch搭建网络层的三种方式

Torch搭建网络层的三种方式

import torch
import torch.nn as nn 
from collections import OrderedDict

class LinearNet(nn.Module):
    def __init__(self, n_feature):
        super(LinearNet, self).__init__()
        self.linear = nn.Linear(n_feature, 1)
    
    def forward(self, x):
        y = self.linear(x)

num_input = 2
net = LinearNet(num_input)
print(net)
# 这里没用到前向传播,在层与层之间连接形成网络时会用到
LinearNet(
  (linear): Linear(in_features=2, out_features=1, bias=True)
)
print('方法1')
net = nn.Sequential(
    nn.Linear(num_input, 1),
    nn.MSELoss()
    # 可以按照这个方式继续添加层
)
print(net)

print('方法2')
net = nn.Sequential()
net.add_module('linear', nn.Linear(num_input, 1))
net.add_module('MSELoss',nn.MSELoss())
# 可以按照这个方式继续添加层
print(net)

print('方法3')
from collections import OrderedDict
net = nn.Sequential(OrderedDict(
                        [
                        ('linera',nn.Linear(num_input,1)),
                        ('MSELoss',nn.MSELoss())
                        # 可以按照这个方式继续添加层
                        ]
))
print(net)

你可能感兴趣的:(pytorch,深度学习,pytorch)