一、pytorch中GRU实现原理:
对于输入序列中的每个元素,每层计算以下函数:
r
t
=
σ
(
W
i
r
x
t
+
b
i
r
+
W
h
r
h
(
t
−
1
)
+
b
h
r
)
r_t=\sigma(W_{ir}x_t + b_{ir} + W_{hr}h_{(t-1)} + b_{hr})
rt=σ(Wirxt+bir+Whrh(t−1)+bhr)
z
t
=
σ
(
W
i
z
x
t
+
b
i
z
+
W
h
z
h
(
t
−
1
)
+
b
h
z
)
z_t=\sigma(W_{iz}x_t + b_{iz} + W_{hz}h_{(t-1)} + b_{hz})
zt=σ(Wizxt+biz+Whzh(t−1)+bhz)
n
t
=
t
a
n
h
(
W
i
n
x
t
+
b
i
n
+
r
t
∗
(
W
h
n
h
(
t
−
1
)
)
+
b
h
n
)
n_t=tanh(W_{in}x_t + b_{in} +r_t*(W_{hn}h_{(t-1)}) + b_{hn})
nt=tanh(Winxt+bin+rt∗(Whnh(t−1))+bhn)
h
t
=
(
1
−
z
t
)
∗
n
t
+
z
∗
h
(
t
−
1
)
h_t=(1-z_t)*n_t + z*h_{(t-1)}
ht=(1−zt)∗nt+z∗h(t−1)
其中各个变量的含义如下:
- h t h_t ht:是在t时间步的hidden state
- x t x_t xt:是在t时间步的输入
- h ( t − 1 ) h_{(t-1)} h(t−1):是上个时间步的hidden state 或者 初始化的hidden state
-
r
t
r_t
rt,
z
t
z_t
zt是 重置门,更新门
二、参数
1.初始化参数
- input_size:输入x的 维度
- hidden_size:hidden state 的维度
- num_layers:GRU堆叠层数,设置num_layers=2 的话,表示堆叠两层GRU到一起,第二个 GRU 接收第一个 GRU的输出并计算最终结果;默认为1
- bias:如果是False,将不再加入 b_ih和b_hh,默认为True
- batch_first:如果为True,则输入和输出的tensors的维度为(batch,seq,feature)而不是(seq,batch,feature)。注意:此标识只对output有效,对hidden state 和 cell state无效,默认为False
- dorpout:如果为非0,在每个 GRU 层(最后一层除外)的输出上引入一个dropout层,dropout概率等于此参数值。默认值:0,只对多层GRU有效。
- bidirectional:如果为True,则是双向GRU,默认为False
2.forward入参
- input:单个样本(unbatched)输入,则形状为 ( L , H i n ) (L, H_{in}) (L,Hin);batch_first=False则输入的形状为 ( L , N , H i n ) (L,N,H_{in}) (L,N,Hin);当batch_first=True时,形状为 ( N , L , H i n ) (N,L,H_{in}) (N,L,Hin),输入也可以是打包的可变长度序列。
- h_0:单个样本(unbatched)输入,形状为
(
D
∗
n
u
m
l
a
y
e
r
s
,
H
o
u
t
)
(D*num_layers, H_out)
(D∗numlayers,Hout);batch样本输入,则形状为
(
D
∗
n
u
m
l
a
y
e
r
s
,
N
,
H
o
u
t
)
(D*num_layers, N, H_out)
(D∗numlayers,N,Hout)也就是初始化的hidden state.
其中: - N=batch size
- L=sequence length
- D=2 if bidirectional=True otherwise 1
- H i n H_{in} Hin=input_size
- H o u t H_{out} Hout=hidden_size
3.输出
- output:单个样本(unbatched)输入,则形状为 ( L , D ∗ H o u t ) (L, D*H_{out}) (L,D∗Hout);batch_first=False,则形状为 ( L , N , D ∗ H o u t ) (L,N,D*H_{out}) (L,N,D∗Hout);batch_first=True,则形状为 ( N , L , D ∗ H o u t ) (N,L,D*H_{out}) (N,L,D∗Hout)。输入也可以是打包的可变长度序列。参考packedtorch.nn.utils.rnn.pack_padded_sequence() h或者torch.nn.utils.rnn.pack_sequence() 方法。
- h_0:单个样本(unbatched)输入,形状为 ( D ∗ n u m l a y e r s , H o u t ) (D*num_layers, H_out) (D∗numlayers,Hout);batch样本输入,则形状为 ( D ∗ n u m l a y e r s , N , H o u t ) (D*num_layers, N, H_out) (D∗numlayers,N,Hout),包含序列中每个元素的最终隐藏状态。当双向 = True 时,h_n将分别包含最终正向和反向隐藏状态的串联。
三、实例
rnn = nn.GRU(10, 20, 2)# embedding_size, hidden_size, num_layer
input = torch.randn(5, 3, 10)# sequence length, batch size, embedding_size
h0 = torch.randn(2, 3, 20)# num_layer*dirc, batch size, hidden_size
output, hn = rnn(input, h0)
output.shape
torch.Size([5, 3, 20])# sequence length, batch size, hidden_size