【问题标题】:input must have 3 dimensions, got 2 Error in create LSTM Classifier输入必须有 3 个维度,在创建 LSTM 分类器时出现 2 个错误
【发布时间】:2021-09-14 17:10:53
【问题描述】:

网络的结构必须如下:

(lstm): LSTM(1, 64, batch_first=True)

(fc1):线性(in_features=64,out_features=32,bias=True)

(relu): ReLU()

(fc2):线性(in_features=32,out_features=5,bias=True)

我写了这段代码:

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 输出 = 模型 (batch_data.to(device)).cpu()

5 帧 /usr/local/lib/python3.7/dist-packages/torch/nn/modules/rnn.py 在 check_input(self, input, batch_sizes) 201 引发运行时错误( 202 '输入必须有{}个维度,得到{}'.format( --> 203 预期的_input_dim, input.dim())) 204 如果 self.input_size != input.size(-1): 205 引发运行时错误(

RuntimeError:输入必须有 3 个维度,得到 2 个维度

我的问题是什么?

【问题讨论】:

  • 粘贴完整的错误日志。这样,我们就可以看到哪里出了问题。
  • @Sr.S 我做到了。
  • 问题是 LSTM 需要 3D 输入(并且您没有指定要提供的输入),而您的输入只是 2D。 LSTM 处理序列,序列至少是 3D 的。

标签: python tensorflow machine-learning lstm relu


【解决方案1】:

LSTM 支持 3 维输入(样本、时间步长、特征)。您需要将输入从 2D 转换为 3D。为此,您可以:

使用整形功能

首先,您需要使用batch_data.shape 来确定二维输入的形状。假设您的 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")

稍后,您还需要将测试数据从 2D 重塑为 3D。

添加重复向量层

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

【讨论】:

    猜你喜欢
    • 2018-10-28
    • 1970-01-01
    • 2021-04-08
    • 2021-05-27
    • 2018-12-04
    • 2019-01-13
    • 2019-01-21
    • 2019-11-18
    • 2020-01-04
    相关资源
    最近更新 更多