完整报错为:RuntimeError: input must have 3 dimensions, got 2
解决方法
前向传播代码中,加入:
def forward(self, x)
x = x.view(len(x), 1, -1) # 把原有2维度[a,b]改为3维[a,1,b]
# ......后续的代码
问题解析
比如我定义的LSTM:
class LSTM(nn.Module):
def __init__(self, input_size=5, hidden_layer_size=100, output_size=1):
# ....初始化
pass
def forward(self, input_x): # input_x.size() 为 [20个数据,5个维度]
lstm_out, self.hidden_cell = self.lstm(input_x, self.hidden_cell)
predictions = self.linear(lstm_out.view(len(input_x), -1))
return predictions[-1]
就会报错,改为如下即正确:
class LSTM(nn.Module):
def __init__(self, input_size=5, hidden_layer_size=100, output_size=1):
# ....初始化
pass
def forward(self, input_x): # input_x.size() 为 [20个数据,5个维度]
input_x = input_x.view(len(input_x), 1, -1) # 维度变为 [20,1,5]
lstm_out, self.hidden_cell = self.lstm(input_x, self.hidden_cell)
predictions = self.linear(lstm_out.view(len(input_x), -1))
return predictions[-1]