如何编写PyTorch序列模型?

Eka*_*Eka 8 python sequential pytorch

到目前为止,我在Keras写了我的MLP,RNN和CNN,但现在PyTorch在深度学习社区中越来越受欢迎,所以我也开始学习这个框架.我是Keras顺序模型的忠实粉丝,它使我们能够非常快速地制作简单的模型.我还看到PyTorch具有此功能,但我不知道如何编写代码.我试过这种方式

import torch
import torch.nn as nn

net = nn.Sequential()
net.add(nn.Linear(3, 4))
net.add(nn.Sigmoid())
net.add(nn.Linear(4, 1))
net.add(nn.Sigmoid())
net.float()

print(net)
Run Code Online (Sandbox Code Playgroud)

但它给出了这个错误

AttributeError:'Sequential'对象没有属性'add'

另外,如果可能的话,你能在PyTorch序列模型中给出RNN和CNN模型的简单例子吗?

McL*_*nce 16

Sequentialadd虽然在添加此功能方面存在一些争议,但目前还没有方法.

正如你可以在文档中 看到的nn.Sequential那样,将图层作为参数序列或者作为参数序列OrderedDict.

如果您有一个包含大量图层的模型,您可以先创建一个列表,然后使用*运算符将列表展开为位置参数,如下所示:

layers = []
layers.append(nn.Linear(3, 4))
layers.append(nn.Sigmoid())
layers.append(nn.Linear(4, 1))
layers.append(nn.Sigmoid())

net = nn.Sequential(*layers)
Run Code Online (Sandbox Code Playgroud)

这将导致代码的结构类似,直接添加.


Chr*_*mer 9

正如正确答案所描述的,这就是看起来像一系列参数的样子:

device = torch.device('cpu')
if torch.cuda.is_available():
    device = torch.device('cuda')

net = nn.Sequential(
      nn.Linear(3, 4),
      nn.Sigmoid(),
      nn.Linear(4, 1),
      nn.Sigmoid()
      ).to(device)


print(net)

Sequential(
  (0): Linear(in_features=3, out_features=4, bias=True)
  (1): Sigmoid()
  (2): Linear(in_features=4, out_features=1, bias=True)
  (3): Sigmoid()
  )
Run Code Online (Sandbox Code Playgroud)


小智 6

layerlist = []
for i in layers:
    layerlist.append(nn.Linear(n_in, i))  # n_in input neurons connected to i number of output neurons
    layerlist.append(nn.ReLU(inplace=True))  # Apply activation function - ReLU
    layerlist.append(nn.BatchNorm1d(i))  # Apply batch normalization
    layerlist.append(nn.Dropout(p))  # Apply dropout to prevent overfitting
    n_in = i  # Reassign number of input neurons as the number of neurons from previous last layer

    # Establish the FCC between the last hidden layer and output layer
    layerlist.append(nn.Linear(layers[-1], out_sz))

    self.layers = nn.Sequential(*layerlist)
Run Code Online (Sandbox Code Playgroud)