如何使用参数实现当前的pytorch激活函数?

我正在寻找一种简单的方法来使用 pytorch 库中存在的激活函数,但使用某种参数。例如:


tanh(x/10)


我想出寻找解决方案的唯一方法是完全从头开始实现自定义功能。有没有更好/更优雅的方法来做到这一点?


编辑:


我正在寻找某种方法将函数 Tanh(x/10) 而不是普通的 Tanh(x) 附加到我的模型中。这是相关的代码块:


    self.model = nn.Sequential()

    for i in range(len(self.layers)-1):

        self.model.add_module("linear_layer_" + str(i), nn.Linear(self.layers[i], self.layers[i + 1]))

        if activations == None:

            self.model.add_module("activation_" + str(i), nn.Tanh())

        else:

            if activations[i] == "T":

                self.model.add_module("activation_" + str(i), nn.Tanh())

            elif activations[i] == "R":

                self.model.add_module("activation_" + str(i), nn.ReLU())

            else:

                #no activation

                pass


慕莱坞森
浏览 217回答 2
2回答

慕慕森

您可以将其内联到自定义层中,而不是将其定义为特定函数。例如,您的解决方案可能如下所示:import torchimport torch.nn as nnclass Net(nn.Module):    def __init__(self):        super(Net, self).__init__()        self.fc1 = nn.Linear(4, 10)        self.fc2 = nn.Linear(10, 3)        self.fc3 = nn.Softmax()    def forward(self, x):        return self.fc3(self.fc2(torch.tanh(self.fc1(x)/10)))wheretorch.tanh(output/10)内联在模块的 forward 函数中。

绝地无双

您可以使用乘法参数创建一个图层:import torchimport torch.nn as nnclass CustomTanh(nn.Module):    #the init method takes the parameter:    def __init__(self, multiplier):        self.multiplier = multiplier    #the forward calls it:    def forward(self, x):        x = self.multiplier * x        return torch.tanh(x)将其添加到您的模型中,CustomTanh(1/10)而不是nn.Tanh()。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python