一、目的
搭建简单的RNN,实现seq2seq的转换
二、编程
先大概了解一下RNN
RNN 其实也是一个普通的神经网络,只不过多了一个 hidden_state 来保存历史信息。跟一般网络不同的是,RNN 网络的输入数据的维度通常是
[
b
a
t
c
h
_
s
i
z
e
∗
s
e
q
l
e
n
∗
i
n
p
u
t
_
s
i
z
e
]
[batch\_size*seqlen*input\_size]
[batch_size∗seqlen∗input_size],它多了一个序列长度
s
e
q
l
e
n
seqlen
seqlen。在前向过程中,我们会把样本
t
t
t个时间序列
x
1
,
x
2
,
.
.
.
,
x
t
x_1,x_2,...,x_t
x1,x2,...,xt的信息不断输入同一个网络 ,因为是重复地使用同一个网络,所以称为循环神经网络。
关于 RNN,你只需要记住一个公式:
h
t
=
t
a
n
h
(
w
i
h
x
t
+
b
i
h
+
w
h
h
h
t
−
1
+
b
h
h
)
h_t=tanh(w_{ih}x_t+b_{ih}+w_{hh}h_{t-1}+b_{hh})
ht=tanh(wihxt+bih+whhht−1+bhh)这也是 pytorch 官方文档中给出的最原始的 RNN 公式,其中
w
w
w表示 weight,
b
b
b表示 bias,
x
t
x_t
xt是输入,
h
t
h_t
ht是隐藏状态。回忆一下,普通的神经网络只有
w
i
h
x
t
+
b
i
h
w_{ih}x_t+b_{ih}
wihxt+bih这一部分,而 RNN 无非就是多加了一个隐藏状态的信息
w
h
h
h
t
−
1
+
b
h
h
w_{hh}h_{t-1}+b_{hh}
whhht−1+bhh而已。
普通网络都是一次前向传播就得到结果,而 RNN 因为多了 sequence 这个维度,所以需要跑 n 次前向。
编程实现分为两种一种是使用RNNCell,另一种是直接使用RNN
RNNCell:
import torch
# 输入样本特征数
input_size = 4
# 隐藏层样本特征数(分类数)
hidden_size = 4
# batch大小
batch_size = 1
idx2char = ['e', 'h', 'l', 'o']
# hello
x_data = [1, 0, 2, 2, 3]
# ohlol
y_data = [3, 1, 2, 3, 2]
# 将x_data转换为one_hot表示
'''
torch.eye()
参数:
n (int ) – 行数
m (int, optional) – 列数.如果为None,则默认为n
out (Tensor, optinal) - Output tensor
'''
x_one_hot = torch.eye(n=4)[x_data, :]
y_one_hot = torch.eye(n=4)[y_data, :]
# x_data转换维度为(seqlen, batch_size, input_size),此维度为RNN的输入
inputs = x_one_hot.view(-1, batch_size, input_size)
# y_data转换维度为(seqlen,1)
labels = torch.LongTensor(y_data).view(-1, 1)
# 构建神经网络模型
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.input_size = input_size
self.batch_size = batch_size
self.hidden_size = hidden_size
# 对于RNNCell输入为(batch_size, input_size),隐层为(batch_size, hidden_size)
self.rnncell = torch.nn.RNNCell(input_size=self.input_size, hidden_size=self.hidden_size)
def forward(self, input, hidden):
# h_t=Cell(x_t, h_t-1)
hidden = self.rnncell(input, hidden)
return hidden
# 初始化隐层h_0
def init_hidden(self):
return torch.zeros(self.batch_size, self.hidden_size)
model = Model()
# 构建损失函数和优化器
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# 训练
for epoch in range(60):
loss = 0
optimizer.zero_grad()
# h_0
hidden = model.init_hidden()
print('Predicted string:', end='')
for input, label in zip(inputs, labels):
hidden = model(input, hidden)
loss += criterion(hidden, label)
_, idx = hidden.max(dim=1)
print(idx2char[idx.item()], end='')
loss.backward()
optimizer.step()
print(', epoch[%d/60] loss=%.4f' % (epoch+1, loss.item()))
预测结果:
Predicted string:llllo, epoch[1/60] loss=6.3004
Predicted string:lllll, epoch[2/60] loss=6.1191
...
Predicted string:ohlol, epoch[59/60] loss=3.0500
Predicted string:ohlol, epoch[60/60] loss=3.0195
RNN:
import torch
# 输入样本特征数
input_size = 4
# 隐藏层样本特征数(分类数)
hidden_size = 4
# batch大小
batch_size = 1
# RNN的层数
num_layers = 1
idx2char = ['e', 'h', 'l', 'o']
# hello
x_data = [1, 0, 2, 2, 3]
# ohlol
y_data = [3, 1, 2, 3, 2]
# 将x_data转换为one_hot表示
'''
torch.eye()
参数:
n (int ) – 行数
m (int, optional) – 列数.如果为None,则默认为n
out (Tensor, optinal) - Output tensor
'''
x_one_hot = torch.eye(n=4)[x_data, :]
y_one_hot = torch.eye(n=4)[y_data, :]
# x_data转换维度为(seqlen, batch_size, input_size),此维度为RNN的输入
inputs = x_one_hot.view(-1, batch_size, input_size)
# y_data转换维度为(seqlen*batch_size,1)
labels = torch.LongTensor(y_data)
# 构建神经网络模型
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.input_size = input_size
self.batch_size = batch_size
self.hidden_size = hidden_size
self.num_layers = num_layers
# 对于RNN输入为(seqlen, batch_size, input_size)
self.rnn = torch.nn.RNN(input_size=self.input_size, hidden_size=self.hidden_size, num_layers=self.num_layers)
def forward(self, input):
hidden = torch.zeros(self.num_layers, self.batch_size, self.hidden_size)
# h_t=Cell(x_t, h_t-1)
out, _ = self.rnn(input, hidden)
out = out.view(-1, self.hidden_size)
return out
model = Model()
# 构建损失函数和优化器
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.1)
# 训练
for epoch in range(60):
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
_, idx = outputs.max(dim=1)
idx = idx.data.numpy()
print("Predicted:", ''.join([idx2char[x]for x in idx]), end='')
print(",epoch[%d/60] loss=%.4f" % (epoch+1, loss.item()))
预测结果:
Predicted: hhhhh,epoch[1/60] loss=1.4128
Predicted: oholl,epoch[2/60] loss=1.1269
...
Predicted: ohlol,epoch[59/60] loss=0.4408
Predicted: ohlol,epoch[60/60] loss=0.4407