当前位置:   article > 正文

torch.nn.GRU使用详解

torch.nn.gru

torch.nn.GRU
输入:
(input_dim ,hidden_dim ,num_layers ,…)
– input_dim 表示输入的特征维度
– hidden_dim 表示输出的特征维度,如果没有特殊变化,相当于out
– num_layers 表示网络的层数
– nonlinearity 表示选用的非线性**函数,默认是 ‘tanh’
– bias 表示是否使用偏置,默认使用
– batch_first 表示输入数据的形式,默认是 False,[即(序列长度seq,批大小batch,特征维度feature)];若True则(batch,seq,feature)
– dropout 缺省值为0,表示不使用dropout层;若为1,则除最后一层外,其它层的输出都会加dropout层
– bidirectional 表示是否使用双向的 rnn,默认是 False
输出:out和 ht
out的输出维度:[seq_len,batch_size,output_dim]
ht的维度:[num_layers * num_directions, batch_size, hidden_size],num_directions=1,单向,取值2时为双向,num_layers为层数
out[-1]=ht[-1]

GRU公式:
在这里插入图片描述

举例:

import torch
import torch.nn as nn


# 例子1,单向一层网络
embed = nn.Embedding(3, 50) #一共3个词,每个词的词向量维度设置为50维
x = torch.LongTensor([[0, 1, 2]]) # 3个句子,每个句子只有一个词,对应的索引分别时0,1,2
x_embed = embed(x)
print(x_embed.size())
# torch.Size([1, 3, 50]) # [规整后的句子长度,样本个数(batch_size),词向量维度]

gru = nn.GRU(input_size=50, hidden_size=50) # 词向量维度,隐藏层维度
out, hidden = gru(x_embed)

print(out.size())
# torch.Size([1, 3, 50]) # [seq_len,batch_size,output_dim]

print(hidden.size())
# torch.Size([1, 1, 50]) # [num_layers * num_directions, batch_size, hidden_size]


# 例子2,单向2层网络
gru_seq = nn.GRU(10, 20,2) # x_dim,h_dim,layer_num
gru_input = torch.randn(3, 32, 10) # seq_len,batch_size,x_dim
out, h = gru_seq(gru_input)
print(out.size())
print(h.size())

'''
torch.Size([3, 32, 20]) # [seq_len,batch_size,output_dim]
torch.Size([2, 32, 20]) # [num_layers * num_directions, batch_size, hidden_size]

'''


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

参考资料:
torch.nn.GRU()函数解读
Pytorch中LSTM,GRU参数理解
【pytorch】关于Embedding和GRU、LSTM的使用详解

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号