首页 > 解决方案 > 如何在pytorch中分离最后一层深层网络?

问题描述

我的深层网络是:

self.actor = nn.Sequential(
   nn.Linear(state_dim, 256),
   nn.Softplus(),
   nn.Linear(256, 256),
   nn.Softplus(),
   nn.Linear(256, action_dim),
   nn.Softplus())

现在,我希望网络提供两个单独的输出,如下所示:
演示网络

也就是说,只有网络的最后一层不同,可能最后一层的激活函数不同。我应该如何更改上面的代码?

标签: pythondeep-learningpytorch

解决方案


您要构建的模型不再是连续的,因为最后有两个并行分支。您可以保留公共主干并使用两个额外的单独层分开。就像是:

class Model(nn.Module):
    def __init__(self):
        super.__init__()

        self.actor = nn.Sequential(
            nn.Linear(state_dim, 256),
            nn.Softplus(),
            nn.Linear(256, 256),
            nn.Softplus())
      
        self.outA = nn.Sequential(
            nn.Linear(256, action_dim),
            nn.Softplus())

        self.outB = nn.Sequential(
            nn.Linear(256, action_dim),
            nn.Softplus())
  
    def forward(self, x):
      features = self.actor(x)
      return self.outA(features), self.outB(features)

推荐阅读