LSTM:解决梯度消失与长期依赖问题

LSTM(长短期记忆网络)是一种递归神经网络,设计用来解决梯度消失和长期依赖问题。

梯度消失:在反向传播过程中,由于链式法则,较早层的梯度小于1,连乘后数次迭代会导致梯度趋于0,使得网络很难学习早期信息。

长期依赖问题:传统神经网络在处理长序列数据时,梯度更新往往受限于短期依赖,难以有效学习长期依赖关系。

LSTM通过增加一个"遗忘门"、"输入门"和"输出门"来解决这些问题。它使用一个称为"单元状态"的隐藏状态,该状态可以记住长期信息。

以下是一个简单的LSTM单元的Python代码示例,使用PyTorch框架:

import torch

import torch.nn as nn

class LSTMCell(nn.Module):

def init(self, input_size, hidden_size):

super(LSTMCell, self).init()

self.hidden_size = hidden_size

self.input2hidden = nn.Linear(input_size + hidden_size, hidden_size)

self.input2cell = nn.Linear(input_size, hidden_size)

self.hidden2cell = nn.Linear(hidden_size, hidden_size)

def forward(self, input, hidden):

h, c = hidden

combined = torch.cat((input, h), dim=1) # concatenate along dimension 1 (channel dimension)

Input Gate

i = torch.sigmoid(self.input2hidden(combined))

Forget Gate

f = torch.sigmoid(self.input2cell(input) + self.hidden2cell(h))

New Cell State

new_c = f * c + i * torch.tanh(self.input2cell(combined))

Output Gate

o = torch.sigmoid(self.input2hidden(combined))

New Hidden State

new_h = o * torch.tanh(new_c)

return new_h, (new_h, new_c)

Example usage

input_size = 10

hidden_size = 20

lstm_cell = LSTMCell(input_size, hidden_size)

input = torch.randn(5, 3, input_size) # seq_len = 5, batch_size = 3

h0 = torch.randn(3, hidden_size)

c0 = torch.randn(3, hidden_size)

hidden_state = (h0, c0)

for input_step in input:

hidden_state = lstm_cell(input_step, hidden_state)

Output is the new hidden state

print(hidden_state[0])

这段代码定义了一个基本的LSTM单元,它接受一个输入序列和一个初始隐藏状态。然后,它遍历输入序列,逐个步骤地计算新的隐藏状态。这个例子中没有使用PyTorch提供的nn.LSTMCell模块,而是手动实现了LSTM单元的基本组成部分,以便更好地理解LSTM的工作原理。

相关推荐
Jing_Rainbow14 分钟前
【AI-7 全栈-2 /Lesson16(2025-11-01)】构建一个基于 AIGC 的 Logo 生成 Bot:从前端到后端的完整技术指南 🎨
前端·人工智能·后端
syounger15 分钟前
奔驰全球 IT 加速转型:SAP × AWS × Agentic AI 如何重塑企业核心系统
人工智能·云计算·aws
上班日常摸鱼20 分钟前
Shell脚本基础教程:变量、条件判断、循环、函数实战(附案例)
python
16_one29 分钟前
autoDL安装Open-WebUi+Rag本地知识库问答+Function Calling
人工智能·后端·算法
智能交通技术32 分钟前
iTSTech:自动驾驶技术综述报告 2025
人工智能·机器学习·自动驾驶
无心水39 分钟前
【Python实战进阶】5、Python字符串终极指南:从基础到高性能处理的完整秘籍
开发语言·网络·python·字符串·unicode·python实战进阶·python工业化实战进阶
2301_807583231 小时前
了解python,并编写第一个程序,常见的bug
linux·python
小白学大数据1 小时前
构建混合爬虫:何时使用Requests,何时切换至Selenium处理请求头?
爬虫·python·selenium·测试工具
2401_827560201 小时前
【Python脚本系列】PyAudio+librosa+dtw库录制、识别音频并实现点击(四)
python·语音识别
清云逸仙1 小时前
AI Prompt 工程最佳实践:打造结构化的Prompt
人工智能·经验分享·深度学习·ai·ai编程