详解pytorch中循环神经网络(RNN、LSTM、GRU)的维度

详解pytorch中循环神经网络(RNN、LSTM、GRU)的维度

首先如果你对RNN、LSTM、GRU不太熟悉,可点击查看。

RNN

torch.nn.rnn详解

torch.nn.RNN(input_size,

hidden_size,

num_layers=1,

nonlinearity='tanh',

bias=True,

batch_first=False,

dropout=0.0,

bidirectional=False,

device=None,

dtype=None)

原理 :

参数详解:

  • input_size -- 输入x中预期特征的数量

  • hidden_size -- 隐藏状态h中的特征数量

  • num_layers -- 循环层数。例如,设置num_layers=2 意味着将两个LSTM堆叠在一起形成堆叠 LSTM,第二个 LSTM 接收第一个 LSTM 的输出并计算最终结果。默认值:1

  • nonlinearity-- 使用的非线性。可以是'tanh'或'relu'。默认:'tanh'

  • bias-- 如果False,则该层不使用偏差权重b_ih和b_hh。默认:True

  • batch_first -- 如果,则输入和输出张量以(batch, seq, feature)True形式提供,而不是(seq, batch, feature)。请注意,这不适用于隐藏状态或单元状态。默认:False

  • dropout -- 如果非零,则在除最后一层之外的每个LSTM层的输出上 引入Dropout层,dropout 概率等于 。默认值:0.0

  • bidirectional -- 如果True, 则成为双向LSTM。默认:False

RNN输入输出维度

python 复制代码
rnn = nn.RNN(10, 20, 2)
input = torch.randn(5, 3, 10)
h0 = torch.randn(2, 3, 20)
output, hn = rnn(input, h0)

可以看到输入是x和h_0,h_0可以是None。如果batch_size是第0维度,需设置batch_first=True。

输出则是output和h_n。h_n存了每一层的t时刻的隐藏状态值

python 复制代码
# Efficient implementation equivalent to the following with bidirectional=False
def forward(x, h_0=None):
    if batch_first:
        x = x.transpose(0, 1)
    seq_len, batch_size, _ = x.size()
    if h_0 is None:
        h_0 = torch.zeros(num_layers, batch_size, hidden_size)
	...
    return output, h_n

输入:
x的输入维度:(batch_size, sequence_length, input_size) 前提:batch_first=True
h_0的维度:(D∗num_layers, hidden_size) 可以为None
输出: output的输出维度:(batch_size, sequence_length, D*hidden_size)
D=2 if bidirectional=True otherwise 1
h_n的维度:(D∗num_layers, hidden_size)

LSTM

torch.nn.LSTM详解

torch.nn.LSTM(input_size,

hidden_size,

num_layers=1,

bias=True,

batch_first=False,

dropout=0.0,

bidirectional=False,

proj_size=0,

device=None,

dtype=None)

原理:

参数详解:

相比于RNN多了proj_size参数,少了nonlinearity参数

  • input_size -- 输入x中预期特征的数量

  • hidden_size -- 隐藏状态h中的特征数量

  • num_layers -- 循环层数。例如,设置num_layers=2 意味着将两个LSTM堆叠在一起形成堆叠 LSTM,第二个 LSTM 接收第一个 LSTM 的输出并计算最终结果。默认值:1

  • bias-- 如果False,则该层不使用偏差权重b_ih和b_hh。默认:True

  • batch_first -- 如果,则输入和输出张量以(batch, seq, feature)True形式提供,而不是(seq, batch, feature)。请注意,这不适用于隐藏状态或单元状态。默认:False

  • dropout -- 如果非零,则在除最后一层之外的每个LSTM层的输出上 引入Dropout层,dropout 概率等于 。默认值:0dropout

  • bidirectional -- 如果True, 则成为双向LSTM。默认:False

  • proj_size -- 如果,将使用具有相应大小投影的LSTM 。默认值:0

LSTM输入输出维度

python 复制代码
LSTM= nn.LSTM(10, 20, 2)
input = torch.randn(5, 3, 10)
h0 = torch.randn(2, 3, 20)
c0 = torch.randn(2, 3, 20)
output, (hn, cn) = LSTM(input, (h0, c0))

输入是x,此外h_0和c_0可以是None。如果batch_size是第0维度,需设置batch_first=True。

输出则是output和一个元组(h_n, c_n)。

输入: x的输入维度:(batch_size, sequence_length, input_size)`
前提:batch_first=True
输出: output的输出维度:(batch_size, sequence_length, D*hidden_size)
D=2 if bidirectional=True otherwise 1

具体可参考官方文档:nn.LSTM

GRU

torch.nn.GRU详解

torch.nn.GRU(input_size,

hidden_size,

num_layers=1,

bias=True,

batch_first=False,

dropout=0.0,

bidirectional=False,

device=None,

dtype=None)

原理:

参数详解:

与上文LSTM相比,缺少了proj_size参数,与RNN相比也缺少了nonlinearity参数

GRU输入输出维度

python 复制代码
gru= nn.GRU(10, 20, 2)
input = torch.randn(5, 3, 10)
h0 = torch.randn(2, 3, 20)
output, hn = gru(input, h0)

与RNN一致见上文,相比LSTM少了c_n

三种RNN的示例

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

rnn = nn.RNN(10, 20, 2, batch_first=True) # (input_size, hidden_size, num_layer)
lstm = nn.LSTM(10, 20, 2, batch_first=True)
gru = nn.GRU(10, 20, 2, batch_first=True)

input = torch.randn(5, 3, 10)  # (batchsize, seq, input_size)
h0 = torch.randn(2, 3, 20)
c0 = torch.randn(2, 3, 20)

output_rnn, h_n = rnn(input)
output_lstm, (hn, cn) = lstm(input)
output_gru, h_n2 = gru(input)
print("输入维度:", input.shape)
print(f"RNN 输出维度:{output_rnn.shape}, h_n维度:{h_n.shape}" )
print("LSTM 输出维度:", output_lstm.shape)
print("GRU 输出维度:", output_gru.shape)


"""
输入维度: torch.Size([5, 3, 10])
RNN 输出维度:torch.Size([5, 3, 20]), h_n维度:torch.Size([2, 5, 20])
LSTM 输出维度: torch.Size([5, 3, 20])
GRU 输出维度: torch.Size([5, 3, 20])
"""
相关推荐
Be for thing12 小时前
PyTorch自动求导Autograd详解|requires_grad、backward、grad、梯度清零
pytorch·学习·1024程序员节
小毕超13 小时前
从推理到训练:Intel Ultra 核显 GPU 加速 YOLO 模型训练
pytorch·yolo·gpu·intel
摸鱼仙人~18 小时前
从 AI 应用开发到 GPU 计算软件:一份完整的 GPGPU、PyTorch、vLLM 与 AI Infra 学习路线
人工智能·pytorch·vllm
计算机毕业编程指导师2 天前
计算机毕设推荐:基于深度学习的动物图像识别方法研究(Python+Django+PyTorch)
pytorch·python·深度学习·计算机·毕业设计·课程设计·图像识别
zh路西法2 天前
【四足强化学习经典算法】(一):RMA——盲视运动控制与快速适应模块
pytorch·强化学习·1024程序员节·四足机器人·dagger·pyhon·rma
Be for thing3 天前
PyCharm安装与PyTorch项目配置|Jupyter Notebook与PyCharm使用对比
pytorch·学习·1024程序员节
zh路西法3 天前
【模型式强化学习】(二)PETS——从概率动力学模型到模型预测控制(MPC)
pytorch·python·强化学习·pe·mpc·ces·pets
段一凡-华北理工大学4 天前
高炉炼铁机器视觉与智能识别十八讲~系列文章17:实战案例:一个风口监控系统的完整搭建
人工智能·pytorch·深度学习·机器学习·计算机视觉·高炉风口监测系统
Yolanda_20224 天前
PyTorch 线性层nn.Linear底层数学原理
人工智能·pytorch·python
专注仿真4 天前
多智能体强化学习实战:从 Dec-POMDP 到 QMIX/MADDPG/MAPPO 的可运行 PyTorch 实现
人工智能·pytorch·python