Python 如何编写 PyTorch 顺序模型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46141690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:30:22  来源:igfitidea点击:

How to write a PyTorch sequential model?

pythonsequentialpytorch

提问by Eka

So far, I wrote my MLP, RNN and CNN in Keras, but now PyTorch is gaining popularity inside deep learning communities, and so I also started to learn this framework. I am a big fan of sequential models in Keras, which allow us to make simple models very fast. I also saw that PyTorch has this functionality, but I don't know how to code one. I tried this way

到目前为止,我在 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)

but it is giving this error

但它给出了这个错误

AttributeError: 'Sequential' object has no attribute 'add'

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

Also, if possible, can you give simple examples for RNN and CNN models in PyTorch sequential model?

另外,如果可能的话,您能否给出 PyTorch 序列模型中 RNN 和 CNN 模型的简单示例?

回答by McLawrence

Sequentialdoes not have an addmethod at the moment, though there is some debateabout adding this functionality.

Sequential目前没有add方法,尽管关于添加此功能存在一些争论

As you can read in the documentationnn.Sequentialtakes as argument the layers separeted as sequence of arguments or an OrderedDict.

正如您在文档nn.Sequential中所读到的那样,将作为参数序列或OrderedDict.

If you have a model with lots of layers, you can create a list first and then use the *operator to expand the list into positional arguments, like this:

如果你有一个有很多层的模型,你可以先创建一个列表,然后使用*运算符将列表扩展为位置参数,如下所示:

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)

This will result in a similar structure of your code, as adding directly.

这将导致您的代码结构与直接添加类似。

回答by Chris Palmer

As described by the correct answer, this is what it would look as a sequence of arguments:

正如正确答案所描述的,这就是一系列参数:

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()
  )

回答by yrd241

As McLawrence said nn.Sequentialdoesn't have the addmethod. I think maybe the codes in which you found the using of addcould have lines that modified the torch.nn.Module.addto a function like this:

正如麦克劳伦斯所说nn.Sequential,没有这个add方法。我想也许你发现使用 of 的代码add可能有将 the 修改为torch.nn.Module.add这样的函数的行:

def add_module(self,module):
    self.add_module(str(len(self) + 1 ), module)

torch.nn.Module.add = add_module

after doing this, you can add a torch.nn.Moduleto a Sequentiallike you posted in the question.

完成此操作后,您可以将一个添加torch.nn.ModuleSequential您在问题中发布的赞。