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

2024-04-20 04:11:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: add神经网络uniformpytorchactivationkernelkerasdense
1条回答
网友
1楼 · 发布于 2024-04-20 04:11:11

类似的问题已经被问过了,但现在是:

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,您应该可以从那里继续。在

相关问题 更多 >