簡體   English   中英

如何使用參數實現當前的pytorch激活函數?

[英]How to implement current pytorch activation functions with parameters?

我正在尋找一種簡單的方法來使用 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

您可以將其內聯到自定義層中,而不是將其定義為特定函數。

例如,您的解決方案可能如下所示:


import torch
import torch.nn as nn

class 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)))

其中torch.tanh(output/10)內聯在模塊的 forward 函數中。

您可以使用乘法參數創建一個圖層:

import torch
import torch.nn as nn

class 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()將其添加到您的模型中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM