【问题标题】:How can I write the below equivalent code of Keras Neural Net in Pytorch?如何在 Pytorch 中编写以下 Keras 神经网络的等效代码?
【发布时间】:2019-06-05 03:31:08
【问题描述】:

如何在 Pytorch 中编写以下 Keras 神经网络的等效代码?

actor = Sequential()
        actor.add(Dense(20, input_dim=9, activation='relu', kernel_initializer='he_uniform'))
        actor.add(Dense(20, activation='relu'))
        actor.add(Dense(27, activation='softmax', kernel_initializer='he_uniform'))
        actor.summary()
        # See note regarding crossentropy in cartpole_reinforce.py
        actor.compile(loss='categorical_crossentropy',
                      optimizer=Adam(lr=self.actor_lr))[Please find the image eq here.][1]


  [1]: https://i.stack.imgur.com/gJviP.png

【问题讨论】:

  • 到目前为止你有什么尝试?

标签: python python-3.x keras pytorch


【解决方案1】:

类似的问题已经被问过,但这里是这样的:

import torch

actor = torch.nn.Sequential(
    torch.nn.Linear(9, 20), # output shape has to be specified
    torch.nn.ReLU(),
    torch.nn.Linear(20, 20), # same goes over here
    torch.nn.ReLU(),
    torch.nn.Linear(20, 27), # and here
    torch.nn.Softmax(),
)

print(actor)

初始化:默认情况下,从 1.0 版本开始,线性层将使用 Kaiming Uniform 进行初始化(参见this post)。如果您想以不同的方式初始化权重,请参阅this question 的最受好评的回答。

您也可以使用 Python 的 OrderedDict 来更轻松地匹配某些层,请参阅 Pytorch's documentation,您应该可以从那里继续。

【讨论】:

    猜你喜欢
    • 2019-12-07
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 2017-05-24
    • 2018-12-16
    • 2022-01-22
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多