首页 > 解决方案 > 如何在 Pytorch 中编写以下 Keras 神经网络的等效代码?

问题描述

如何在 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

标签: pythonpython-3.xkeraspytorch

解决方案


已经提出了类似的问题,但在这里:

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进行初始化(参见这篇文章)。如果你想以不同的方式初始化你的权重,请参阅这个问题的最受好评的答案。

您也可以使用 PythonOrderedDict更轻松地匹配某些层,请参阅Pytorch 的文档,您应该可以从那里继续。


推荐阅读