B站 刘二大人 传送门 循环神经网络(基础篇)
课件链接:https://pan.baidu.com/s/1vZ27gKp8Pl-qICn_p2PaSw
提取码:cxe4
模型还是将输入“hello”训练输出为“ohlol”,用LSTM网络实现。按照计算图实现LSTM之后,又尝试了加入embedding的方法。加embedding的训练快,但是我的LSTM效果不如前面RNN的,不知道是我网络写的有问题还是怎么回事。
LSTM的网络结构示意图和公式:
根据我自己的理解写出来的LSTM模型,有不对的地方欢迎指正。
首先看公式有8个线性层,之后又进行了非线性运算,所以模型定义了8个linear。输入是4维向量(h、e、l、o),不打算改变维度,所以输出也都是4维。只有5个输入,所以批量设为1.向前传播根据计算公式和计算图,返回hidden和c继续在下一轮计算继续用。
import torch
input_size = 4
batch_size = 1
class LSTM(torch.nn.Module):
def __init__(self):
super(LSTM, self).__init__()
self.linearix = torch.nn.Linear(4, 4)
self.linearfx = torch.nn.Linear(4, 4)
self.lineargx = torch.nn.Linear(4, 4)
self.linearox = torch.nn.Linear(4, 4)
self.linearih = torch.nn.Linear(4, 4)
self.linearfh = torch.nn.Linear(4, 4)
self.lineargh = torch.nn.Linear(4, 4)
self.linearoh = torch.nn.Linear(4, 4)
self.sigmoid = torch.nn.Sigmoid()
self.tanh = torch.nn.Tanh()
def forward(self, x, hidden, c):
i = self.sigmoid(self.linearix(x) + self.linearih(hidden))
f = self.sigmoid(self.linearfx(x) + self.linearfh(hidden))
g = self.tanh(self.lineargx(x) + self.lineargh