<总是容易忘== 接下来不断更新吧>
RNN最为原始的循环神经网络----容易梯度消失、梯度爆炸。
GRU只有两个门(update和reset),LSTM有三个门(forget,input,output)。
GRU直接将hidden state 传给下一个单元,而LSTM则用memory cell 把hidden state 包装起来。
LSTM图解
(中间的 cell 里面有四个黄色小框,每一个小黄框代表一个前馈网络层,就是经典的神经网络的结构,num_units就是这个层的隐藏神经元个数。)
- cell 的状态是一个向量,是有多个值的;
- 上一次的状态 h(t-1)直接和下一次的输入 x(t) 结合(concat)起来的。比如 x是28位的向量,h(t-1)是128位的,那么拼起来就是156位的向量;
- cell 的权重共享----图片上有三个绿色的大框,代表三个 cell 。但是实际上,它只是代表了一个 cell 在不同时序时候的状态,所有的数据只会通过一个 cell,然后不断更新它的权重。同一个cell前后时序共享
- LSTM参数的数量就是这个 cell 里面用到的参数个数。假设 num_units 是128,输入是28位的,那么根据上面的第 2 点,可以得到,四个小黄框的参数一共有 (128+28)×(128×4),也就是156 ×512。
- cell 最上面的一条线的状态即 s(t) 代表了长时记忆,而下面的 h(t)则代表了工作记忆或短时记忆。
class ConvLSTMCell(nn.Module):
def __init__(self, input_size, input_dim, hidden_dim, kernel_size, bias):
"""
Initialize ConvLSTM cell.
Parameters
----------
input_size: (int, int)
Height and width of input tensor as (height, width).
input_dim: int
Number of channels of input tensor.
hidden_dim: int
Number of channels of hidden state.
kernel_size: (int, int)
Size of the convolutional kernel.
bias: bool
Whether or not to add the bias.
"""
super(ConvLSTMCell, self).__init__()
self.height, self.width = input_size
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.kernel_size = kernel_size
self.padding = kernel_size[0] // 2, kernel_size[1] // 2
self.bias = bias
self.conv = nn.Conv2d(in_channels=self.input_dim + self.hidden_dim,
out_channels=4 * self.hidden_dim,
kernel_size=self.kernel_size,
padding=self.padding,
bias=self.bias)
def forward(self, input_tensor, cur_state):
'''
:param input_tensor:[batch,dim,inp_height,inp_width]
:param cur_state: [h,c] h:[batch,dim,H,W]
:return:
'''
h_cur, c_cur = cur_state
combined = torch.cat([input_tensor, h_cur], dim=1)
combined_conv = self.conv(combined)
cc_i, cc_f, cc_o, cc_g = torch.split(combined_conv, self.hidden_dim, dim=1)
i = torch.sigmoid(cc_i)
f = torch.sigmoid(cc_f)
o = torch.sigmoid(cc_o)
g = torch.tanh(cc_g)
c_next = f * c_cur + i * g
h_next = o * torch.tanh(c_next)
return h_next, c_next
def init_hidden(self, batch_size):
return (Variable(torch.zeros(batch_size, self.hidden_dim, self.height, self.width)),
Variable(torch.zeros(batch_size, self.hidden_dim, self.height, self.width)))
GRU