我有一个预训练的Pytorch模型,用于生成一些输入句子的特征/嵌入。这些特征本质上是torch
对象。例如,一个句子的input_embedding
(一个torch对象列表)样例如下所示:
[tensor([-0.8264, 0.2524], device='cuda:0', grad_fn=<SelectBackward>)]
现在,我希望将这个嵌入传递给一个自定义模型,该模型本质上是一个双向LSTM:
def custom_model(input_embedding): # 初始化BiLSTM bilstm = torch.nn.LSTM(input_size=1, hidden_size=1, num_layers=1, batch_first=False, bidirectional=True) # 将输入馈送到bilstm对象 bi_output, bi_hidden = bilstm(input_embedding) # 更多代码 .... return F.softmax(x)
我想将我的input_embedding
传递给这个自定义模型,以获得如下所示的预测输出:
for item in input_embedding: y_pred = biLSTM_single_sentence_student_model(item)
但在bi_output, bi_hidden = bilstm(input_embedding)
这行代码上抛出了错误,显示:
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
很可能是因为我对Pytorch nn.LSTM输入的理解不足,导致没有正确定义bilstm
对象。
请提供建议。
回答:
LSTM的输入必须是形状为(seq_len, batch, input_size)
的3D张量。在你的例子中,你提供的是形状为seq_len, input_size
的2D张量,正如你提到的,[-0.8264, 0.2524]
是一个示例句子。
所以,你可以按照以下方式修改你的示例:
# 两个句子的列表input_embedding = [ torch.FloatTensor([[-0.8264], [0.2524]]), torch.FloatTensor([[-0.3259], [0.3564]])]for item in input_embedding: # item是一个形状为`seq_len, input_size`的2D张量 # 因此,我们使用unsqueeze将其扩展为3D的`seq_len, 1, input_size`,其中batch_size = 1 y_pred = custom_model(item.unsqueeze(1)) print(y_pred.size()) # 2, 1, 2
希望这对你有帮助!