搜索

pdf文档 深度学习与PyTorch入门实战 - 52. LSTM-Layer使用

643.79 KB 11 页 1 下载 74 浏览 0 评论 0 收藏
语言 格式 评分
中文(简体)
.pdf
3
摘要
文档主要介绍了PyTorch中LSTM层的使用方法,包括LSTM的基本结构和数学公式,展示了如何通过PyTorch实现LSTM和LSTMCell。文档详细说明了LSTM的输入输出形状、隐藏状态的管理以及多层LSTM的实现方式,并通过代码示例展示了具体的使用方法和输出结果。
AI总结
### 文档总结 #### 1. LSTM基本原理 - LSTM(长短期记忆网络)通过门控机制(输入门、遗忘门、输出门、候选门)来控制信息的流动。 - 核心公式: - 门控向量计算:$$ \begin{pmatrix}\mathbf{i}^{(t)}\\\mathbf{f}^{(t)}\\\mathbf{o}^{(t)}\\\mathbf{g}^{(t)}\end{pmatrix}=\begin{pmatrix}\sigma\\\sigma\\\sigma\\\tanh\end{pmatrix}\mathbf{W}\begin{pmatrix}\mathbf{x}^{(t)}\\\mathbf{h}^{(t-1)}\end{pmatrix} $$ - 候选细胞状态更新:$$ \mathbf{c}^{(t)}=\mathbf{f}^{(t)}\circ\mathbf{c}^{(t-1)}+\mathbf{i}^{(t)}\circ\mathbf{g}^{(t)} $$ - 最终隐藏状态输出:$$ \mathbf{h}^{(t)}=\mathbf{o}^{(t)}\circ\mathrm{tanh}(\mathbf{c}^{(t)}) $$ #### 2. PyTorch中LSTM的实现 - **nn.LSTM**: - 初始化参数: - `input_size`:输入特征维度 - `hidden_size`:隐藏状态特征维度 - `num_layers`:堆叠的LSTM层数,默认为1 - 前向传播接口: - 输入:`x`(形状:[seq, b, vec]),初始隐藏状态 `[h, c]`(形状:[num_layer, b, h]) - 输出:`out`(形状:[seq, b, h]),最终隐藏状态 `[h, c]`(形状:[num_layer, b, h]) - 示例: ```python lstm = nn.LSTM(input_size=100, hidden_size=20, num_layers=4) x = torch.randn(10, 3, 100) out, (h, c) = lstm(x) print(out.shape, h.shape, c.shape) # torch.Size([10, 3, 20]) torch.Size([4, 3, 20]) torch.Size([4, 3, 20]) ``` - **nn.LSTMCell**: - 初始化参数: - `input_size`:输入特征维度 - `hidden_size`:隐藏状态特征维度 - 前向传播接口: - 输入:`xt`(形状:[b, vec]),初始隐藏状态 `[h, c]`(形状:[b, h]) - 输出:`ht, ct`(形状:[b, h]) - 示例: ```python cell = nn.LSTMCell(input_size=100, hidden_size=20) h = torch.zeros(3, 20) c = torch.zeros(3, 20) for xt in x: h, c = cell(xt, [h, c]) print(h.shape, c.shape) # torch.Size([3, 20]) torch.Size([3, 20]) ``` #### 3. 多层LSTM示例 - 使用多层LSTM需要堆叠多个LSTMCell: ```python cell1 = nn.LSTMCell(input_size=100, hidden_size=30) cell2 = nn.LSTMCell(input_size=30, hidden_size=20) h1 = torch.zeros(3, 30) c1 = torch.zeros(3, 30) h2 = torch.zeros(3, 20) c2 = torch.zeros(3, 20) for xt in x: h1, c1 = cell1(xt, [h1, c1]) h2, c2 = cell2(h1, [h2, c2]) print(h2.shape, c2.shape) # torch.Size([3, 20]) torch.Size([3, 20]) ``` #### 4. 总结 - PyTorch中的LSTM和LSTMCell提供了灵活的接口,支持单层和多层堆叠使用。 - 通过调整`input_size`和`hidden_size`,可以实现不同规模的模型。 - LSTM的门控机制使其在处理序列数据时表现出色,广泛应用于自然语言处理、时间序列预测等领域。
P1
P2
P3
P4
P5
P6
P7
下载文档到本地,方便使用
- 可预览页数已用完,剩余 4 页请下载阅读 -
文档评分
请文明评论,理性发言.