输入必须有3个维度,在创建LSTM分类器时出现2个错误

2024-10-01 02:21:59 发布

您现在位置:Python中文网/ 问答频道 /正文

网络结构必须如下所示:

(lstm):lstm(1,64,批次_first=True)

(fc1):线性(输入特征=64,输出特征=32,偏差=真)

(relu):relu()

(fc2):线性(输入特征=32,输出特征=5,偏差=真)

我写了这段代码:

class LSTMClassifier(nn.Module):

    def __init__(self):
        super(LSTMClassifier, self).__init__() 
        self.lstm = nn.LSTM(1, 64, batch_first=True)
        self.fc1 = nn.Linear(in_features=64, out_features=32, bias=True)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(in_features=32, out_features=5, bias=True)
         

    def forward(self, x):
       x = torch.tanh(self.lstm(x)[0])
       x = self.fc1(x)
       x = F.relu(x)
       x = self.fc2(x)

这是为了测试:

    (batch_data, batch_label) = next (iter (train_loader))
    model = LSTMClassifier().to(device)
    output = model (batch_data.to(device)).cpu()
    assert output.shape == (batch_size, 5)
    print ("passed")

错误是:

----->;3输出=型号(批处理数据到(设备)).cpu()

5帧 /检查输入中的usr/local/lib/python3.7/dist-packages/torch/nn/modules/rnn.py(自身、输入、批量大小) 201引发运行时错误( 202'输入必须有{}个维度,得到{}'。格式( -->;203预期的输入尺寸,input.dim()) 204如果自输入大小!=输入。大小(-1): 205提升运行时错误(

运行时错误:输入必须有3个维度,得到2个维度

我有什么问题


Tags: selftrue错误batch线性nn特征first
1条回答
网友
1楼 · 发布于 2024-10-01 02:21:59

LSTM支持三维输入(示例、时间步长、功能)。您需要将输入从二维转换为三维。为此,您可以:

使用整形功能

首先,您需要使用batch_data.shape获得2D输入的形状。让我们假设2D输入的形状为(15, 4)。 现在,要将输入从2D重塑为3D,请使用重塑函数np.reshape(data, new_shape)

    (batch_data, batch_label) = next (iter (train_loader))
    batch_data = np.reshape(batch_data, (15, 4, 1)) # line to add
    model = LSTMClassifier().to(device)
    output = model (batch_data.to(device)).cpu()
    assert output.shape == (batch_size, 5)
    print ("passed")

稍后,还需要将测试数据从二维重塑为三维

添加RepeatVector层

这一层是在Keras中实现的,我不确定它是否在PyTorch中可用,这就是您的情况。 该层为数据添加了一个额外维度(重复输入n次)。例如,您可以将2D输入(batch size, input size)转换为3D输入(batch_size, sequence_length, input size)

相关问题 更多 >