类型错误:forward()需要2个位置参数,但给出了3个

问题描述 投票:0回答:3

您好,我不明白为什么我会收到标题所示的错误,并使用以下内容作为我的前向传播函数

    # For function that will activate neurons and perform forward propagation
def forward(self, inputs):
    state, (hx, cx) = inputs # getting separately the input images to the tuple (hidden states, cell states)
    x = F.relu(self.lstm(state)) # forward propagating the signal from the input images to the 1st convolutional layer
    hx, cx = self.lstm(x, (hx, cx)) # the LSTM takes as input x and the old hidden & cell states and ouputs the new hidden & cell states
    x = hx # getting the useful output, which are the hidden states (principle of the LSTM)
    return self.fcL(x), (hx, cx) # returning the output of the actor (Q(S,A)), and the new hidden & cell states ((hx, cx))

这是我的action_selection函数:

    def select_action(self, state):
    #LSTM
    initialise = True # Initialise to zero at first iteration
    if initialise:
        cx = Variable(torch.zeros(1, 30))
        hx = Variable(torch.zeros(1, 30))
    else:  # The hx,cx from the previous iteration
        cx = Variable(cx.data) 
        hx = Variable(hx.data) 
    initialise = False
    q_values, (hx,cx) = self.model(Variable(state), (hx,cx))
    probs = F.softmax((q_values)*self.tau,dim=1)
    #create a random draw from the probability distribution created from softmax
    action = probs.multinomial()
    return action.data[0,0]
python typeerror lstm
3个回答
4
投票

我只是遇到了同样的非描述性问题,并且没有像之前所述的答案那样在类之外调用转发函数。一段时间后,我发现这是我在前向函数中添加到“x”变量的多个声明中的第二个值,因为我想创建一个 cuda 张量。我知道这是一个老问题,但它可能会对偶然发现它的人有所帮助。 检查前向函数下的 x 变量,因为它们不应采用多个参数。


1
投票

您在哪里使用转发功能?意思是在哪一行抛出错误?我找不到它。

但一般来说:如果您不在类内部使用函数forward,而是作为一个对象,它实际上需要一个参数。 ( self 是“自动”给出的,因此您可以在类中引用其他内容。为了更好的解释,请阅读以下内容:https://docs.python.org/3/tutorial/classes.html)。例如,如果您尝试做这样的事情:

myObject = myClass()
myObject.forward(a,b)

它会抛出这个错误


0
投票

就我而言,我遇到了这个错误,因为我定义了

self.fc = nn.Linear(2,1)
,然后有
forward(self,x1,x2)
,并期望
self.fc(x1,x2)
为我连接
x1
x2
,现在很搞笑,但花了几个小时才发现我的错误。出现这个问题是因为我最初从标量输入的模型开始,并尝试将代码调整为长度为 2 输入向量的模型。

© www.soinside.com 2019 - 2024. All rights reserved.