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

时间:2019-01-10 09:36:21

标签: python python-3.x keras pytorch

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

1 个答案:

答案 0 :(得分: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,您应该可以从那里开始。