【作业】LSTM

目录

[习题6-4 推导LSTM网络中参数的梯度, 并分析其避免梯度消失的效果](#习题6-4 推导LSTM网络中参数的梯度, 并分析其避免梯度消失的效果)

​编辑

[习题6-3P 编程实现下图LSTM运行过程](#习题6-3P 编程实现下图LSTM运行过程)

[1. 使用Numpy实现LSTM算子](#1. 使用Numpy实现LSTM算子)

[2. 使用nn.LSTMCell实现](#2. 使用nn.LSTMCell实现)

[3. 使用nn.LSTM实现](#3. 使用nn.LSTM实现)

参考链接


习题6-4 推导LSTM网络中参数的梯度, 并分析其避免梯度消失的效果

LSTM框架如下:

**总而言之:**LSTM遗忘门值可以选择在[0,1]之间,让LSTM来改善梯度消失的情况。也可以选择接近1,让遗忘门饱和,此时远距离信息梯度不消失。也可以选择接近0,此时模型是故意阻断梯度流,遗忘之前信息。

习题6-3P编程实现下图LSTM运行过程

  1. 使用Numpy实现LSTM算子

  2. 使用nn.LSTMCell实现

  3. 使用nn.LSTM实现

1. 使用Numpy实现LSTM算子

python 复制代码
import numpy as np

#定义激活函数
def sigmoid(x):
    return 1/(1+np.exp(-x))

def tanh(x):
    return (np.exp(x)-np.exp(-x))/(np.exp(x)+np.exp(-x))

#权重
input_weight=np.array([1,0,0,0])
inputgate_weight=np.array([0,100,0,-10])
forgetgate_weight=np.array([0,100,0,10])
outputgate_weight=np.array([0,0,100,-10])

#输入
input=np.array([[1,0,0,1],[3,1,0,1],[2,0,0,1],[4,1,0,1],[2,0,0,1],[1,0,1,1],[3,-1,0,1],[6,1,0,1],[1,0,1,1]])

y=[]   #输出
c_t=0  #内部状态

for x in input:
    g_t=tanh(np.matmul(input_weight,x)) #候选状态
    i_t=np.round(sigmoid(np.matmul(inputgate_weight,x)))  #输入门
    after_inputgate=g_t*i_t       #候选状态经过输入门
    f_t=np.round(sigmoid(np.matmul(forgetgate_weight,x))) #遗忘门
    after_forgetgate=f_t*c_t      #内部状态经过遗忘门
    c_t=np.add(after_inputgate,after_forgetgate) #新的内部状态
    o_t=np.round(sigmoid(np.matmul(outputgate_weight,x))) #输出门
    after_outputgate=o_t*tanh(c_t)     #激活后新的内部状态经过输出门
    y.append(round(after_outputgate,2))   #输出

print('输出:',y)

输出:

python 复制代码
output:[0.0, 0.0, 0.0, 0.0, 0.0, 0.96, 0.0, 0.0, 0.76]

2. 使用nn.LSTMCell实现

python 复制代码
import torch
import torch.nn as nn

#实例化
input_size=4
hidden_size=1
cell=nn.LSTMCell(input_size=input_size,hidden_size=hidden_size)
#修改模型参数 weight_ih.shape=(4*hidden_size, input_size),weight_hh.shape=(4*hidden_size, hidden_size),
#weight_ih、weight_hh分别为输入x、隐层h分别与输入门、遗忘门、候选、输出门的权重
cell.weight_ih.data=torch.tensor([[0,100,0,-10],[0,100,0,10],[1,0,0,0],[0,0,100,-10]],dtype=torch.float32)
cell.weight_hh.data=torch.zeros(4,1)
print('cell.weight_ih.shape:',cell.weight_ih.shape)
print('cell.weight_hh.shape',cell.weight_hh.shape)
#初始化h_0,c_0
h_t=torch.zeros(1,1)
c_t=torch.zeros(1,1)
#模型输入input_0.shape=(batch,seq_len,input_size)
input_0=torch.tensor([[[1,0,0,1],[3,1,0,1],[2,0,0,1],[4,1,0,1],[2,0,0,1],[1,0,1,1],[3,-1,0,1],[6,1,0,1],[1,0,1,1]]],dtype=torch.float32)
#交换前两维顺序,方便遍历input.shape=(seq_len,batch,input_size)
input=torch.transpose(input_0,1,0)
print('input.shape:',input.shape)
output=[]
#调用
for x in input:
    h_t,c_t=cell(x,(h_t,c_t))
    output.append(np.around(h_t.item(), decimals=3))#保留3位小数
print('output:',output)

输出:

python 复制代码
output:[0.0, 0.0, 0.0, 0.0, 0.0, 0.96, 0.0, 0.0, 0.76]

3. 使用nn.LSTM实现

python 复制代码
#LSTM
#实例化
input_size=4
hidden_size=1
lstm=nn.LSTM(input_size=input_size,hidden_size=hidden_size,batch_first=True)
#修改模型参数
lstm.weight_ih_l0.data=torch.tensor([[0,100,0,-10],[0,100,0,10],[1,0,0,0],[0,0,100,-10]],dtype=torch.float32)
lstm.weight_hh_l0.data=torch.zeros(4,1)
#模型输入input.shape=(batch,seq_len,input_size)
input=torch.tensor([[[1,0,0,1],[3,1,0,1],[2,0,0,1],[4,1,0,1],[2,0,0,1],[1,0,1,1],[3,-1,0,1],[6,1,0,1],[1,0,1,1]]],dtype=torch.float32)
#初始化h_0,c_0
h_t=torch.zeros(1,1,1)
c_t=torch.zeros(1,1,1)
#调用
output,(h_t,c_t)=lstm(input,(h_t,c_t))
rounded_output = torch.round(output * 1000) / 1000  # 保留3位小数
print(rounded_output)

输出结果

python 复制代码
output:[0.0, 0.0, 0.0, 0.0, 0.0, 0.96, 0.0, 0.0, 0.7672]

参考链接

LSTM参数梯度推导与实现:对抗梯度消失,

LSTM参数梯度推导与编程实现,

李宏毅机器学习笔记:RNN循环神经网络_李宏毅机器学习课程笔记-CSDN博客

HBU-NNDL 作业10:第六章课后题(LSTM | GRU)-CSDN博客

相关推荐
测试员周周6 小时前
【Appium 系列】第16节-WebView-H5上下文切换 — 混合应用的自动化难点
运维·开发语言·人工智能·功能测试·appium·自动化·测试用例
K姐研究社8 小时前
怎么用AI制作电商口播视频,开拍APP一键生成
人工智能·音视频
LaughingZhu8 小时前
Product Hunt 每日热榜 | 2026-05-21
前端·人工智能·经验分享·chatgpt·html
传说故事9 小时前
【论文阅读】MotuBrain: An Advanced World Action Model for Robot Control
论文阅读·人工智能·具身智能·wam
北京耐用通信9 小时前
全域适配工业场景耐达讯自动化Modbus TCP 转 PROFIBUS 网关轻松实现以太网与现场总线互通
网络·人工智能·网络协议·自动化·信息与通信
火山引擎开发者社区9 小时前
TRAE × 火山引擎 Supabase:为你的 AI 应用装上“数据引擎”
人工智能
小a彤10 小时前
GE 在 CANN 五层架构中的位置
人工智能·深度学习·transformer
前端若水10 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
Upsy-Daisy10 小时前
AI Agent 项目学习笔记(八):Tool Calling 工具调用机制总览
人工智能·笔记·学习
企学宝10 小时前
企学宝5月专题课程丨《OpenClaw AI 智能体实战营:从零基础部署到全场景自动化落地》
人工智能·ai·企业培训