Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python LSTM模型实现_Python_Deep Learning_Sequence_Lstm - Fatal编程技术网

Python LSTM模型实现

Python LSTM模型实现,python,deep-learning,sequence,lstm,Python,Deep Learning,Sequence,Lstm,这是我的LSTM模型,输入是一个4维向量。批量大小为16,时间戳为12。我想用12序列向量找到第13个向量。我的LSTM块有[16,12,48]输出。我不明白为什么我选择了最后一个: out[:,-1,:]从外观上看,您的问题就像一个文本(即序列)分类问题,output\u size是您要分配文本的类的数量。通过选择lstm_out[:,-1,:],您实际上打算仅使用lstm网络的最后隐藏状态来预测与输入文本相关联的标签,这完全有道理。这是人们通常对文本分类问题所做的。此后,您的线性层将为每个类

这是我的LSTM模型,输入是一个4维向量。批量大小为16,时间戳为12。我想用12序列向量找到第13个向量。我的LSTM块有[16,12,48]输出。我不明白为什么我选择了最后一个:
out[:,-1,:]

从外观上看,您的问题就像一个文本(即序列)分类问题,
output\u size
是您要分配文本的类的数量。通过选择
lstm_out[:,-1,:]
,您实际上打算仅使用lstm网络的最后隐藏状态来预测与输入文本相关联的标签,这完全有道理。这是人们通常对文本分类问题所做的。此后,您的线性层将为每个类输出logit,然后您可以使用
nn.Softmax()
获取这些类的概率

LSTM网络的最后一个隐藏状态是LSTM的所有先前隐藏状态的传播,这意味着它具有先前编码的输入状态的聚集信息(让我们考虑一下,在示例中使用单向LSTM)。因此,要对输入文本进行分类,您必须根据输入文本中所有标记的总体信息进行分类(在LSTM的最后一个隐藏状态中进行编码)。这就是为什么只将最后一个隐藏状态提供给LSTM网络上的线性层


注意:如果您打算进行序列标记(例如命名实体识别),那么您将使用LSTM网络的所有隐藏状态输出。在这些任务中,您实际上需要输入中特定令牌的信息。

之所以选择最后一个
lstm_out[:,-1,:]
是因为LSTMs顶部的线性层将最后一个lstm层的输出作为输入。我的网络聚合数据集的平均值,有什么理由这样做吗?
class LSTM(nn.Module):
    def __init__(self, input_size=1, output_size=1, hidden_size=100, num_layers=16):
        super().__init__()
        self.hidden_size = hidden_size

        self.lstm = nn.LSTM(input_size, hidden_size, num_layers)

        self.linear = nn.Linear(hidden_size, output_size)

        self.num_layers = num_layers

        self.hidden_cell = (torch.zeros(self.num_layers,12 ,self.hidden_size).to(device),
                            torch.zeros(self.num_layers,12 ,self.hidden_size).to(device))

    def forward(self, input_seq):
        #lstm_out, self.hidden_cell = self.lstm(input_seq.view(len(input_seq) ,1, -1), self.hidden_cell)
        lstm_out, self.hidden_cell = self.lstm(input_seq, self.hidden_cell)        
        predictions = self.linear(lstm_out[:,-1,:])

        return predictions