pytorch中LSTM各参数理解
nn.LSTM(input_dim,hidden_dim,nums_layer,batch_first)
各参数理解:
- input_dim:输入的张量维度,表示自变量特征数
- hidden_dim:输出张量维度
- bias:True or False 是否使用偏置
- batch_first:True or False,nn.LSTM 接收的输入是(seq_len,batch_size,input_dim),将batch_first设置为True将输入变为(batch_size,seq_len,input_dim)
- dropout:除了最后层外都引入随机失活
- bidirectional:True or False 是否使用双向LSTM
举例:10000个句子,每个句子10个词,batch_size=10,embedding_size=300(input_dim)
此时各个参数为:
- input_size=embedding_size=300
- batch=batch_size=10
- seq_len=10
- 另外设置hidden_dim=128,num_layers=2
import torch
import torch.nn as nn
from torch.autograd import Variable
rnn = nn.LSTM(input_size=300,hidden_size=128,num_layers=2)
inputs = torch.randn(10,10,300)#输入(seq_len, batch_size, input_size) 序列长度为10 batch_size为10 输入维度为300
h_0 = torch.randn(2,10,128)#(num_layers * num_directions, batch, hidden_size) num_layers = 2 ,batch_size=10 ,hidden_size = 128,如果LSTM的bidirectional=True,num_directions=2,否则就是1,表示只有一个方
c_0 = torch.randn(2,10,128)#c_0和h_0的形状相同,它包含的是在当前这个batch_size中的每个句子的初始细胞状态。h_0,c_0如果不提供,那么默认是0
num_directions=1# 因为是单向LSTM
#输出格式为(output,(h_n,c_n))
output,(h_n,c_n) = rnn(inputs,(h0,c0))#输入格式为lstm(input,(h_0, c_0))
print("out:", output.shape)
print("h_n:", h_n.shape)
print("c_n:", c_n.shape)
输出结果:
out: torch.Size([10, 10, 128])
h_n: torch.Size([2, 10, 128])
c_n: torch.Size([2, 10, 128])
输出结果:
- output的shape为(seq_len=5,batch_size=3,num_directions*hidden_size),hidden_size为20,num_directions为1。它包含的LSTM的最后一层的输出特征(h_t),t是batch_size中每个句子的长度。
- h_n.shape为(num_directions*num_layers=2,batch_size=3,hidden_size=20)
- c_n.shape==h_n.shape
- h_n是句子最后一个单词的隐藏状态,c_n包含句子最后一个单词的细胞状态,它们与句子长度无关
- LSTM中的隐藏状态就是输出。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!