织梦搭建企业网站厦门seo俱乐部
文章目录
- 循环神经网络介绍
- 代码实现
- 1、导入需要的库
- 2、加载周杰伦歌词数据集
- 3、定义采样函数
- 3.1 随机采样
- 3.2 相邻采样
- 4、one-hot向量
- 5、初始化模型参数
- 6、定义模型
- 6.1 初始化隐藏状态
- 6.2 在一个时间步里计算隐藏状态和输出
- 7、定义预测函数
- 8、裁剪梯度
- 9、定义模型训练函数
- 9.1 困惑度
- 9.2 初始化优化器
- 9.3 定义梯度下降函数
- 9.4 定义训练函数
- 9.5 训练
循环神经网络介绍
在循环神经网络中输入数据是存在时间相关性的,也就是说,前一个时间点的数据会对后一时间点的数据产生影响。假设 Xt∈Rn×d\boldsymbol{X}_t \in \mathbb{R}^{n \times d}Xt∈Rn×d 是序列中时间步 ttt 的小批量输入,Ht∈Rn×h\boldsymbol{H}_t \in \mathbb{R}^{n \times h}Ht∈Rn×h 是该时间步的隐藏变量。与多层感知机不同的是,这里我们保存上一时间步的隐藏变量 Ht−1\boldsymbol{H}_{t-1}Ht−1,并引入一个新的权重参数 Whh∈Rh×h\boldsymbol{W}_{hh} \in \mathbb{R}^{h \times h}Whh∈Rh×h,该参数用来描述在当前时间步如何使用上一时间步的隐藏变量。具体来说,时间步 ttt 的隐藏变量的计算由当前时间步的输入和上一时间步的隐藏变量共同决定:
Ht=ϕ(XtWxh+Ht−1Whh+bh).\boldsymbol{H}_t = \phi(\boldsymbol{X}_t \boldsymbol{W}_{xh} + \boldsymbol{H}_{t-1} \boldsymbol{W}_{hh} + \boldsymbol{b}_h).Ht=ϕ(XtWxh+Ht−1Whh+bh).
与多层感知机相比,我们在这里添加了 Ht−1Whh\boldsymbol{H}_{t-1} \boldsymbol{W}_{hh}Ht−1Whh 一项。由上式中相邻时间步的隐藏变量 Ht\boldsymbol{H}_tHt 和 Ht−1\boldsymbol{H}_{t-1}Ht−1 之间的关系可知,这里的隐藏变量能够捕捉截至当前时间步的序列的历史信息,就像是神经网络当前时间步的状态或记忆一样。因此,该隐藏变量也称为隐藏状态。隐藏状态中 XtWxh+Ht−1Whh\boldsymbol{X}_t \boldsymbol{W}_{xh} + \boldsymbol{H}_{t-1} \boldsymbol{W}_{hh}XtWxh+Ht−1Whh 的计算等价于 Xt\boldsymbol{X}_tXt与Ht−1\boldsymbol{H}_{t-1}Ht−1 连结后的矩阵乘以Wxh\boldsymbol{W}_{xh}Wxh与Whh\boldsymbol{W}_{hh}Whh连结后的矩阵。由于隐藏状态在当前时间步的定义使用了上一时间步的隐藏状态,上式的计算是循环的。使用循环计算的网络即循环神经网络(recurrent neural network)。
循环神经网络有很多种不同的构造方法。含上式所定义的隐藏状态的循环神经网络是极为常见的一种。在时间步 ttt,输出层的输出和多层感知机中的计算类似:
Ot=HtWhq+bq.\boldsymbol{O}_t = \boldsymbol{H}_t \boldsymbol{W}_{hq} + \boldsymbol{b}_q.Ot=HtWhq+bq.
循环神经网络的参数包括隐藏层的权重 Wxh∈Rd×h\boldsymbol{W}_{xh} \in \mathbb{R}^{d \times h}Wxh∈Rd×h、Whh∈Rh×h\boldsymbol{W}_{hh} \in \mathbb{R}^{h \times h}Whh∈Rh×h 和偏差 bh∈R1×h\boldsymbol{b}_h \in \mathbb{R}^{1 \times h}bh∈R1×h,以及输出层的权重 Whq∈Rh×q\boldsymbol{W}_{hq} \in \mathbb{R}^{h \times q}Whq∈Rh×q 和偏差 bq∈R1×q\boldsymbol{b}_q \in \mathbb{R}^{1 \times q}bq∈R1×q。值得一提的是,即便在不同时间步,循环神经网络也始终使用这些模型参数。因此,循环神经网络模型参数的数量不随时间步的增加而增长。
上图展示了循环神经网络在3个相邻时间步的计算逻辑。在时间步 ttt,隐藏状态的计算可以看成是将输入 Xt\boldsymbol{X}_tXt 和前一时间步隐藏状态 Ht−1\boldsymbol{H}_{t-1}Ht−1 连结后输入一个激活函数为 ϕ\phiϕ 的全连接层。该全连接层的输出就是当前时间步的隐藏状态 Ht\boldsymbol{H}_tHt,且模型参数为 Wxh\boldsymbol{W}_{xh}Wxh 与 Whh\boldsymbol{W}_{hh}Whh 的连结,偏差为 bh\boldsymbol{b}_hbh。当前时间步 ttt 的隐藏状态 Ht\boldsymbol{H}_tHt 将参与下一个时间步 t+1t+1t+1 的隐藏状态 Ht+1\boldsymbol{H}_{t+1}Ht+1 的计算,并输入到当前时间步的全连接输出层。
代码实现
在这个部分,我们将从零开始实现一个基于字符级循环神经网络的语言模型,并在周杰伦专辑歌词数据集上训练一个模型来进行歌词创作。
1、导入需要的库
import tensorflow as tf
from tensorflow import keras
import numpy as np
import zipfile
import math
2、加载周杰伦歌词数据集
def load_data_jay_lyrics():with zipfile.ZipFile('./jaychou_lyrics.txt.zip') as zin:with zin.open('jaychou_lyrics.txt') as f:corpus_chars = f.read().decode('utf-8')corpus_chars = corpus_chars.replace('\n', ' ').replace('\r', ' ')corpus_chars = corpus_chars[0:10000]idx_to_char = list(set(corpus_chars))char_to_idx = dict([(char, i) for i, char in enumerate(idx_to_char)])vocab_size = len(char_to_idx)corpus_indices = [char_to_idx[char] for char in corpus_chars]return corpus_indices, char_to_idx, idx_to_char, vocab_size(corpus_indices, char_to_idx, idx_to_char, vocab_size) = load_data_jay_lyrics()
对这一部分以及下一部分的采样有疑惑的小伙伴请移步至:Tensorflow2.0之语言模型数据集(周杰伦专辑歌词)预处理。
3、定义采样函数
3.1 随机采样
def data_iter_random(corpus_indices, batch_size, num_steps):num_examples = (len(corpus_indices)-1) // num_stepsepoch_size = num_examples // batch_sizeexample_indices = list(range(num_examples))random.shuffle(example_indices)# 返回从pos开始的长为num_steps的序列def _data(pos):return corpus_indices[pos: pos + num_steps]for i in range(epoch_size):# 每次读取batch_size个随机样本i = i * batch_sizebatch_indices = example_indices[i: i + batch_size]X = [_data(j * num_steps) for j in batch_indices]Y = [_data(j * num_steps + 1) for j in batch_indices]yield np.array(X), np.array(Y)
3.2 相邻采样
def data_iter_consecutive(corpus_indices, batch_size, num_steps, ctx=None):corpus_indices = np.array(corpus_indices)data_len = len(corpus_indices)batch_len = data_len // batch_sizeindices = corpus_indices[0: batch_size*batch_len].reshape((batch_size, batch_len))epoch_size = (batch_len - 1) // num_stepsfor i in range(epoch_size):i = i * num_stepsX = indices[:, i: i + num_steps]Y = indices[:, i + 1: i + num_steps + 1]yield X, Y
4、one-hot向量
为了将词表示成向量输入到神经网络,一个简单的办法是使用one-hot向量,即独热编码。假设词典中不同字符的数量为NNN(即词典大小vocab_size),每个字符已经和一个从0到N−1N-1N−1的连续整数值索引一一对应,包含这些一一对应的字符及其索引值的字典是第二部分得到的 char_to_idx。如果一个字符的索引是整数iii, 那么我们创建一个全0的长为NNN的向量,并将位置为iii的元素设成1。该向量就是对原字符的one-hot向量。
我们每次采样的小批量的形状是(批量大小, 时间步数)。下面的函数将这样的小批量变换成数个可以输入进网络的形状为 (批量大小, 词典大小) 的矩阵,矩阵个数等于时间步数。也就是说,时间步ttt的输入为Xt∈Rn×d\boldsymbol{X}_t \in \mathbb{R}^{n \times d}Xt∈Rn×d,其中nnn为批量大小,ddd为输入个数,即one-hot向量长度(词典大小)。
def to_onehot(X, size):# X shape: (batch, steps), output shape: (batch, vocab_size)return [tf.one_hot(x, size,dtype=tf.float32) for x in X.T]
举例来说:
X = np.arange(10).reshape((2, 5))
inputs = to_onehot(X, vocab_size)
那么 X 为:
[[0 1 2 3 4][5 6 7 8 9]]
是一个包含两个 batch,且时间步长为5的数据。也就是说,第一个时间点的输入为0和5,第二个时间点的输入为1和6,以此类推。
经过 one-hot 变换后得到的 inputs 为:
[<tf.Tensor: id=9, shape=(2, 1027), dtype=float32, numpy=
array([[1., 0., 0., ..., 0., 0., 0.],[0., 0., 0., ..., 0., 0., 0.]], dtype=float32)>, <tf.Tensor: id=14, shape=(2, 1027), dtype=float32, numpy=
array([[0., 1., 0., ..., 0., 0., 0.],[0., 0., 0., ..., 0., 0., 0.]], dtype=float32)>, <tf.Tensor: id=19, shape=(2, 1027), dtype=float32, numpy=
array([[0., 0., 1., ..., 0., 0., 0.],[0., 0., 0., ..., 0., 0., 0.]], dtype=float32)>, <tf.Tensor: id=24, shape=(2, 1027), dtype=float32, numpy=
array([[0., 0., 0., ..., 0., 0., 0.],[0., 0., 0., ..., 0., 0., 0.]], dtype=float32)>, <tf.Tensor: id=29, shape=(2, 1027), dtype=float32, numpy=
array([[0., 0., 0., ..., 0., 0., 0.],[0., 0., 0., ..., 0., 0., 0.]], dtype=float32)>]
包含了5个时间点的数据,第一个时间点的数据是0和5的独热编码,以此类推。
5、初始化模型参数
根据上文中对循环神经网络的介绍,我们可以得到所有参数(权重和阈值)的 shape:
- Wxh∈Rd×h\boldsymbol{W}_{xh} \in \mathbb{R}^{d \times h}Wxh∈Rd×h
- Whh∈Rh×h\boldsymbol{W}_{hh} \in \mathbb{R}^{h \times h}Whh∈Rh×h
- bh∈R1×h\boldsymbol{b}_h \in \mathbb{R}^{1 \times h}bh∈R1×h
- Whq∈Rh×q\boldsymbol{W}_{hq} \in \mathbb{R}^{h \times q}Whq∈Rh×q
- bq∈R1×q\boldsymbol{b}_q \in \mathbb{R}^{1 \times q}bq∈R1×q
其中,ddd 指的是每个(经过独热编码后的)输入样本的维度,即词典的大小;hhh 指的是隐藏层中的神经元个数;qqq 指的是输出向量的维度,由于输出向量中包含着下一个时间点选择各个字符的概率,所以 qqq 也等于词典大小。
num_epochs = 2500 # 训练2500次
num_steps = 35 # 时间步长为35
num_inputs, num_hiddens, num_outputs = vocab_size, 256, vocab_size
def get_params():def _one(shape):return tf.Variable(tf.random.normal(shape=shape,stddev=0.01,mean=0,dtype=tf.float32))# 隐藏层参数W_xh = _one((num_inputs, num_hiddens))W_hh = _one((num_hiddens, num_hiddens))b_h = tf.Variable(tf.zeros(num_hiddens), dtype=tf.float32)# 输出层参数W_hq = _one((num_hiddens, num_outputs))b_q = tf.Variable(tf.zeros(num_outputs), dtype=tf.float32)params = [W_xh, W_hh, b_h, W_hq, b_q]return params
6、定义模型
在定义模型之前,我们要先对一个时间点上的输入数据及隐藏状态的 shape 进行归纳:
- Xt∈Rn×d\boldsymbol{X}_t \in \mathbb{R}^{n \times d}Xt∈Rn×d
- Ht∈Rn×h\boldsymbol{H}_t \in \mathbb{R}^{n \times h}Ht∈Rn×h
其中,nnn指的是每批样本的个数;ddd 指的是每个(经过独热编码后的)输入样本的维度,即词典的大小;hhh 指的是隐藏层中的神经元个数。
6.1 初始化隐藏状态
我们根据循环神经网络的计算表达式实现该模型。首先定义 init_rnn_state 函数来返回初始化的隐藏状态。它返回由一个形状为 (批量大小, 隐藏单元个数) 的所有值都为0的数组。
# 返回初始化的隐藏状态
def init_rnn_state(batch_size):return tf.zeros(shape=(batch_size, num_hiddens))
6.2 在一个时间步里计算隐藏状态和输出
这里的激活函数使用了 tanh 函数,因为当元素在实数域上均匀分布时,tanh 函数值的均值为0。
def rnn(inputs, state, params):W_xh, W_hh, b_h, W_hq, b_q = paramsH = stateoutputs = []for X in inputs:X = tf.reshape(X,[-1,W_xh.shape[0]])H = tf.tanh(tf.matmul(X, W_xh) + tf.matmul(H, W_hh) + b_h)Y = tf.matmul(H, W_hq) + b_qoutputs.append(Y)return outputs, H
在上面的函数中,inputs 和 outputs 皆为 num_steps 个形状为 (batch_size, vocab_size) 的矩阵,每次循环只对其中一个矩阵进行计算。
在进行训练时,inputs 的形状为 (batch_size, vocab_size),但是在进行预测时,inputs 的形状为 (1, vocab_size),所以要先将 X 的形状转换为 (-1, vocab_size),否则 X 的形状就是 (vocab_size,) 从而不能进行下面的操作了。
如:
A = np.array([[1, 2, 3, 4, 5, 6]])
print(A.shape)
for a in A:print(a.shape)
(1, 6)
(6,)
7、定义预测函数
以下函数基于前缀 prefix(含有数个字符的字符串)来预测接下来的 num_chars 个字符。
def predict_rnn(prefix, num_chars, params):state = init_rnn_state(batch_size=1)output = [char_to_idx[prefix[0]]]for t in range(num_chars + len(prefix) - 1):# 将上一时间步的输出作为当前时间步的输入X = tf.convert_to_tensor(to_onehot(np.array([output[-1]]), vocab_size),dtype=tf.float32)# 计算输出和更新隐藏状态(Y, state) = rnn(X, state, params)# 下一个时间步的输入是prefix里的字符或者当前的最佳预测字符if t < len(prefix) - 1:output.append(char_to_idx[prefix[t + 1]])else:output.append(int(np.array(tf.argmax(Y[0],axis=1))))return ''.join([idx_to_char[i] for i in output])
我们可以先试验一下:
params = get_params()
print(predict_rnn('分开', 10, params))
得到:
分开盯欠袋王中写鸥油村丛
因为模型参数为随机值,所以预测结果也是随机的。
8、裁剪梯度
循环神经网络中较容易出现梯度衰减或梯度爆炸。为了应对梯度爆炸,我们可以裁剪梯度(clip gradient)。假设我们把所有模型参数梯度的元素拼接成一个向量 g\boldsymbol{g}g,并设裁剪的阈值是 θ\thetaθ。裁剪后的梯度
min(θ∣g∣,1)g\min\left(\frac{\theta}{|\boldsymbol{g}|}, 1\right)\boldsymbol{g}min(∣g∣θ,1)g
的L2L_2L2范数不超过θ\thetaθ。
# 计算裁剪后的梯度
def grad_clipping(grads,theta):norm = np.array([0])for i in range(len(grads)):norm+=tf.math.reduce_sum(grads[i] ** 2)norm = np.sqrt(norm).item()new_gradient=[]if norm > theta:for grad in grads:new_gradient.append(grad * theta / norm)else:for grad in grads:new_gradient.append(grad) return new_gradient
9、定义模型训练函数
跟之前的模型训练函数相比,这里的模型训练函数有以下几点不同:
- 使用困惑度评价模型。
- 在迭代模型参数前裁剪梯度。
- 对时序数据采用不同采样方法将导致隐藏状态初始化的不同。
9.1 困惑度
我们通常使用困惑度(perplexity)来评价语言模型的好坏。困惑度是对交叉熵损失函数做指数运算后得到的值。特别地,
- 最佳情况下,模型总是把标签类别的概率预测为1,此时困惑度为1;
- 最坏情况下,模型总是把标签类别的概率预测为0,此时困惑度为正无穷;
- 基线情况下,模型总是预测所有类别的概率都相同,此时困惑度为类别个数。
显然,任何一个有效模型的困惑度必须小于类别个数。在本例中,困惑度必须小于词典大小vocab_size。
9.2 初始化优化器
optimizer = tf.keras.optimizers.SGD(learning_rate=1e2)
9.3 定义梯度下降函数
def train_step(params, X, Y, state, clipping_theta):with tf.GradientTape(persistent=True) as tape:tape.watch(params)inputs = to_onehot(X, vocab_size)# outputs有num_steps个形状为(batch_size, vocab_size)的矩阵(outputs, state) = rnn(inputs, state, params)# 拼接之后形状为(num_steps * batch_size, vocab_size)outputs = tf.concat(outputs, 0)# Y的形状是(batch_size, num_steps),转置后再变成长度为# batch * num_steps 的向量,这样跟输出的行一一对应y = Y.T.reshape((-1,))y = tf.convert_to_tensor(y, dtype=tf.float32)# 使用交叉熵损失计算平均分类误差l = tf.reduce_mean(tf.losses.sparse_categorical_crossentropy(y, outputs))grads = tape.gradient(l, params)grads = grad_clipping(grads, clipping_theta) # 裁剪梯度optimizer.apply_gradients(zip(grads, params))return l, y
9.4 定义训练函数
- is_random_iter:是否随机采样;
- pred_period:间隔多少次展示一次结果;
- pred_len:要求预测的字符长度。
def train_and_predict_rnn(is_random_iter, batch_size, clipping_theta, pred_period, pred_len, prefixes):if is_random_iter:data_iter_fn = data_iter_randomelse:data_iter_fn = data_iter_consecutiveparams = get_params()for epoch in range(num_epochs):if not is_random_iter: # 如使用相邻采样,在epoch开始时初始化隐藏状态state = init_rnn_state(batch_size)l_sum, n = 0.0, 0data_iter = data_iter_fn(corpus_indices, batch_size, num_steps)for X, Y in data_iter:if is_random_iter: # 如使用随机采样,在每个小批量更新前初始化隐藏状态state = init_rnn_state(batch_size, num_hiddens)l, y = train_step(params, X, Y, state, clipping_theta)l_sum += np.array(l).item() * len(y)n += len(y)if (epoch + 1) % pred_period == 0:print('epoch %d, perplexity %f' % (epoch + 1, math.exp(l_sum / n)))for prefix in prefixes:print(prefix)print(' -', predict_rnn(prefix, pred_len, params))
9.5 训练
pred_period, pred_len, prefixes = 50, 50, ['分开', '不分开']
clipping_theta = 0.01
batch_size = 32
train_and_predict_rnn(False, batch_size, clipping_theta, pred_period, pred_len, prefixes)