1

网络的结构必须如下:

(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 in check_input(self, input, batch_sizes) 201 raise RuntimeError( 202 'input must have {} dimensions, got { }'.format(--> 203 expected_input_dim, input.dim())) 204 if self.input_size != input.size(-1): 205 raise RuntimeError(

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

我的问题是什么?

4

1 回答 1

1

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

使用整形功能

首先,您需要使用 2D 输入的形状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)

于 2021-07-02T21:50:56.057 回答