主角torch.nn.LSTM()

初始化时要传入的参数

 |  Args:
| input_size: The number of expected features in the input `x`
| hidden_size: The number of features in the hidden state `h`
| num_layers: Number of recurrent layers. E.g., setting ``num_layers=2``
| would mean stacking two LSTMs together to form a `stacked LSTM`,
| with the second LSTM taking in outputs of the first LSTM and
| computing the final results. Default: 1
| bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`.
| Default: ``True``
| batch_first: If ``True``, then the input and output tensors are provided
| as `(batch, seq, feature)` instead of `(seq, batch, feature)`.
| Note that this does not apply to hidden or cell states. See the
| Inputs/Outputs sections below for details. Default: ``False``
| dropout: If non-zero, introduces a `Dropout` layer on the outputs of each
| LSTM layer except the last layer, with dropout probability equal to
| :attr:`dropout`. Default: 0
| bidirectional: If ``True``, becomes a bidirectional LSTM. Default: ``False``
| proj_size: If ``> 0``, will use LSTM with projections of corresponding size. Default: 0

input_size:一般是词嵌入的大小

hidden_size:隐含层的维度

num_layers:默认是1,单层LSTM

bias:是否使用bias

batch_first:默认为False,如果设置为True,则表示第一个维度表示的是batch_size

dropout:直接看英文吧

bidirectional:默认为False,表示单向LSTM,当设置为True,表示为双向LSTM,一般和num_layers配合使用(需要注意的是当该项设置为True时,将num_layers设置为1,表示由1个双向LSTM构成)

模型输入输出-单向LSTM

import torch
import torch.nn as nn
import numpy as np inputs_numpy = np.random.random((64,32,300))
inputs = torch.from_numpy(inputs_numpy).to(torch.float32)
inputs.shape

torch.Size([64, 32, 300]):表示[batchsize, max_length, embedding_size]

hidden_size = 128
lstm = nn.LSTM(300, 128, batch_first=True, num_layers=1)
output, (hn, cn) = lstm(inputs)
print(output.shape)
print(hn.shape)
print(cn.shape)

torch.Size([64, 32, 128])

torch.Size([1, 64, 128])

torch.Size([1, 64, 128])

说明:

output:保存了每个时间步的输出,如果想要获取最后一个时间步的输出,则可以这么获取:output_last = output[:,-1,:]

h_n:包含的是句子的最后一个单词的隐藏状态,与句子的长度seq_length无关

c_n:包含的是句子的最后一个单词的细胞状态,与句子的长度seq_length无关

另外:最后一个时间步的输出等于最后一个隐含层的输出

output_last = output[:,-1,:]
hn_last = hn[-1]
print(output_last.eq(hn_last))

模型输入输出-双向LSTM

首先我们要明确:

output :(seq_len, batch, num_directions * hidden_size)

h_n:(num_layers * num_directions, batch, hidden_size)

c_n :(num_layers * num_directions, batch, hidden_size)

其中num_layers表示层数,这里是1,num_directions表示方向数,由于是双向的,这里是2,也是,我们就有下面的结果:

import torch
import torch.nn as nn
import numpy as np inputs_numpy = np.random.random((64,32,300))
inputs = torch.from_numpy(inputs_numpy).to(torch.float32)
inputs.shape
hidden_size = 128
lstm = nn.LSTM(300, 128, batch_first=True, num_layers=1, bidirectional=True)
output, (hn, cn) = lstm(inputs)
print(output.shape)
print(hn.shape)
print(cn.shape)

torch.Size([64, 32, 256])

torch.Size([2, 64, 128])

torch.Size([2, 64, 128])

这里面的hn包含两个元素,一个是正向的隐含层输出,一个是方向的隐含层输出。

#获取反向的最后一个output
output_last_backward = output[:,0,-hidden_size:]
#获反向最后一层的hn
hn_last_backward = hn[-1] #反向最后的output等于最后一层的hn
print(output_last_backward.eq(hn_last_backward)) #获取正向的最后一个output
output_last_forward = output[:,-1,:hidden_size]
#获取正向最后一层的hn
hn_last_forward = hn[-2]
# 反向最后的output等于最后一层的hn
print(output_last_forward.eq(hn_last_forward))

https://www.cnblogs.com/LiuXinyu12378/p/12322993.html

https://blog.csdn.net/m0_45478865/article/details/104455978

https://blog.csdn.net/foneone/article/details/104002372

关于torch.nn.LSTM()的输入和输出的更多相关文章

  1. torch.nn.LSTM()函数维度详解

    123456789101112lstm=nn.LSTM(input_size,                     hidden_size,                      num_la ...

  2. PyTorch官方中文文档:torch.nn

    torch.nn Parameters class torch.nn.Parameter() 艾伯特(http://www.aibbt.com/)国内第一家人工智能门户,微信公众号:aibbtcom ...

  3. pytorch nn.LSTM()参数详解

    输入数据格式:input(seq_len, batch, input_size)h0(num_layers * num_directions, batch, hidden_size)c0(num_la ...

  4. pytorch中文文档-torch.nn.init常用函数-待添加

    参考:https://pytorch.org/docs/stable/nn.html torch.nn.init.constant_(tensor, val) 使用参数val的值填满输入tensor ...

  5. pytorch中文文档-torch.nn常用函数-待添加-明天继续

    https://pytorch.org/docs/stable/nn.html 1)卷积层 class torch.nn.Conv2d(in_channels, out_channels, kerne ...

  6. torch.nn.functional中softmax的作用及其参数说明

    参考:https://pytorch-cn.readthedocs.io/zh/latest/package_references/functional/#_1 class torch.nn.Soft ...

  7. torch.nn.Embedding理解

    Pytorch官网的解释是:一个保存了固定字典和大小的简单查找表.这个模块常用来保存词嵌入和用下标检索它们.模块的输入是一个下标的列表,输出是对应的词嵌入. torch.nn.Embedding(nu ...

  8. pytorch torch.nn.functional实现插值和上采样

    interpolate torch.nn.functional.interpolate(input, size=None, scale_factor=None, mode='nearest', ali ...

  9. pytorch torch.nn 实现上采样——nn.Upsample

    Vision layers 1)Upsample CLASS torch.nn.Upsample(size=None, scale_factor=None, mode='nearest', align ...

随机推荐

  1. TVM性能评估分析(三)

    TVM性能评估分析(三) Figure 1. TVM's WebGPU backend close to native GPU performance when deploying models to ...

  2. CentOS:操作系统级监控及常用计数器解析

    我相信有一些人看到这篇文章的标题肯定有种不想看的感觉,因为这样的内容实在被写得太多太多了.操作系统分析嘛,无非就是 CPU 使用率.I/O 使用率.内存使用率.网络使用率等各种使用率的描述. 然而因为 ...

  3. 【NX二次开发】Block UI 整形

    属性说明 常规         类型 描述     BlockID     String 控件ID     Enable     Logical 是否可操作     Group     Logical ...

  4. 深入理解Java中的反射机制和使用原理!详细解析invoke方法的执行和使用

    反射的概念 反射: Refelection,反射是Java的特征之一,允许运行中的Java程序获取自身信息,并可以操作类或者对象的内部属性 通过反射,可以在运行时获得程序或者程序中的每一个类型的成员活 ...

  5. 学习响应式编程 Reactor (3) - reactor 基础

    Reactor Reactor 项目的主要 artifact 是 reactor-core,这是一个基于 Java 8 的实现了响应式流规范的响应式库. Reactor 提供了实现 Publisher ...

  6. 史上最详细的Air7xx驱动安装教程

    由于Air7xx系列4G模块需要安装USB驱动,但是很多开发者对USB驱动的安装方法不是十分了解,所以经常出现问题,导致安装失败.特书此文,手把手教你装USB驱动. 第一步 从官网下载最新的驱动程序 ...

  7. oracle中如何处理null

    从两个表达式返回一个非 null 值.语法NVL(eExpression1, eExpression2)参数eExpression1, eExpression2如果 eExpression1 的计算结 ...

  8. 【题解】Luogu p2014 选课 树型dp

    题目描述 在大学里每个学生,为了达到一定的学分,必须从很多课程里选择一些课程来学习,在课程里有些课程必须在某些课程之前学习,如高等数学总是在其它课程之前学习.现在有N门功课,每门课有个学分,每门课有一 ...

  9. 【题解】Grape luogu1156改 dp

    考试时被数据坑了 题目 原题 传送门 题目描述: 众所周知的是oyyf 沉迷葡萄,今天的oyyf为了葡萄溜到了He 大佬家的葡萄园偷葡萄,可惜的是还没偷到葡萄He 大佬就来葡萄园了,吓的oyyf 直接 ...

  10. 如何编写shell脚本

    1.首先创建一个目录 vi hello.sh 2.编写shell第一行 #!/bin/bash    (为了声明是shell脚本,第一行都要这么写) 3.可以添加注释     #the first p ...