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的工作原理。

相关推荐
X566127 分钟前
如何在 Laravel 中正确保存嵌套动态表单数据(主服务与子服务)
jvm·数据库·python
zhuiyisuifeng35 分钟前
2026前瞻:GPTimage2镜像官网或将颠覆视觉创作
人工智能·gpt
徐健峰37 分钟前
GPT-image-2 热门玩法实战(一):AI 看手相 — 一张手掌照片生成专业手相分析图
人工智能·gpt
weixin_3709763539 分钟前
AI的终极赛跑:进入AGI,还是泡沫破灭?
大数据·人工智能·agi
Slow菜鸟41 分钟前
AI学习篇(五) | awesome-design-md 使用说明
人工智能·学习
ZhengEnCi1 小时前
03ab-PyTorch安装教程 📚
python
冬奇Lab1 小时前
RAG 系列(五):Embedding 模型——语义理解的核心
人工智能·llm·aigc
深小乐1 小时前
AI 周刊【2026.04.27-05.03】:Anthropic 9000亿美元估值、英伟达死磕智能体、中央重磅定调AI
人工智能
码点滴1 小时前
什么时候用 DeepSeek V4,而不是 GPT-5/Claude/Gemini?
人工智能·gpt·架构·大模型·deepseek
狐狐生风2 小时前
LangChain 向量存储:Chroma、FAISS
人工智能·python·学习·langchain·faiss·agentai