北大MOOC——TF2.0笔记
以下是我的听课笔记,供以后回忆(大多内容来自ppt)
1.循环核
有些数据与时间序列相关,是可以根据上文预测出下文的。通过脑记忆体(循环核)提取历史数据的特征,预测出接下来最可能发生的情况。
循环核(记忆体):循环核具有记忆力,通过不同时刻的参数共享,实现了对时间序列的信息提取。
循环核:可以设置记忆体的个数改变记忆容量。当记忆容量、输入xt、输出yt维度被指定,周围这些待训练参数的维度也就被限定了。
前向传播时:记忆体内存储着每个时刻的状态信息ht ,在每个时刻都被刷新,三个参数矩阵wxh、whh、why自始至终都是固定不变的。
反向传播时:三个参数矩阵wxh、whh、why被梯度下降法更新
yt就是一个全连接网络
2. 循环核按时间步展开
按时间步展开,就是把循环核按照时间轴方向展开,每个时刻记忆体状态信息ht被刷新,记忆体周围的参数矩阵wxh、whh、why是固定不变的,我们训练优化的就是这些参数矩阵,训练完成后,使得效果最好的参数矩阵执行前向传播,输出预测结果。
这与人类是相似的,人们脑中的记忆体是随当前的输入而更新的,当前的预测推理是根据以往的知识积累,用固化下来的参数矩阵进行推理判断的。
循环神经网络:借助循环核时间特征提取后,送入全连接网络。
yt是整个循环网络的末层,从公式来看就是一个全连接网络,借助全连接网络,实现连续数据预测。
3.循环计算层
每个循环核构成一层循环计算层。
循环计算层的层数是向输出方向增长的。
4.TF描述循环计算层
tf.keras.layers.SimpleRNN(记忆体个数,activation=‘激活函数’ , return_sequences=是否每个时刻输出ht到下一层)
activation=‘激活函数’ (不写,默认使用tanh)
return_sequences=True 各时间步输出ht
return_sequences=False 仅最后时间步输出ht(默认)
例:SimpleRNN(3, return_sequences=True)
一般最后一层的循环核用False,仅在最后一个时间步输出ht。
中间层的循环核使用True,每个时间步都把ht输出给下一层。
API对送入循环层的数据维度是有要求的,要求送入循环层的数据是三维的,第一维是送入样本的总数量,第二维是循环核时间展开步数,第三维是每个时间步输入特征个数。
5.循环计算过程(1)
神经网络的输入都是数字,所以使用独热码对5个字母进行编码,随机生成了参数矩阵wxh、whh、why。
记忆体的个数设置为3,记忆体状态信息。
当前输入xt[0,1,0,0,0](代表输入的为b),乘以wxh,上一时刻的记忆体状态信息为0,再加上偏置矩阵bh[0.5,0.3,-0.2],求和之后是[-1.8,1.1,0.9],过tanh激活函数之后,得到当前时刻的状态信息ht,记忆体存储的状态信息被刷新为[-0.9,0.8,0.7](脑中的记忆被更新),输出yt是吧提取到的时间信息,通过全连接进行识别预测的过程,是整个网络的输出层。
[-0.9,0.8,0.7]乘以why,加上偏置矩阵by得到[-0.7,-0.5,3.3,0.0,-0.7],过softmax函数得到最终结果[0.02,0.02,0.91,0.03,0.02]代表有91%的可能输出是字母c,所以RNN预测结果是c
6.字母预测
用RNN实现输入四个字母,预测下一个字母
为了将字母送入神经网络,将5个字母表示为5个数字0,1,2,3,4。再把每个数字编码为5位的独热码。
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, SimpleRNN
import matplotlib.pyplot as plt
import os
#为了将字母送入神经网络,将5个字母表示为5个数字0,1,2,3,4。
# 再把每个数字编码为5位的独热码。
input_word = "abcde"
w_to_id = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4} # 单词映射到数值id的词典
id_to_onehot = {0: [1., 0., 0., 0., 0.], 1: [0., 1., 0., 0., 0.], 2: [0., 0., 1., 0., 0.], 3: [0., 0., 0., 1., 0.],
4: [0., 0., 0., 0., 1.]} # id编码为one-hot
x_train = [
[id_to_onehot[w_to_id['a']], id_to_onehot[w_to_id['b']], id_to_onehot[w_to_id['c']], id_to_onehot[w_to_id['d']]],
[id_to_onehot[w_to_id['b']], id_to_onehot[w_to_id['c']], id_to_onehot[w_to_id['d']], id_to_onehot[w_to_id['e']]],
[id_to_onehot[w_to_id['c']], id_to_onehot[w_to_id['d']], id_to_onehot[w_to_id['e']], id_to_onehot[w_to_id['a']]],
[id_to_onehot[w_to_id['d']], id_to_onehot[w_to_id['e']], id_to_onehot[w_to_id['a']], id_to_onehot[w_to_id['b']]],
[id_to_onehot[w_to_id['e']], id_to_onehot[w_to_id['a']], id_to_onehot[w_to_id['b']], id_to_onehot[w_to_id['c']]],
]
y_train = [w_to_id['e'], w_to_id['a'], w_to_id['b'], w_to_id['c'], w_to_id['d']]
np.random.seed(7)
np.random.shuffle(x_train)
np.random.seed(7)
np.random.shuffle(y_train)
tf.random.set_seed(7)
# 使x_train符合SimpleRNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。
# 此处整个数据集送入,送入样本数为len(x_train);输入4个字母出结果,循环核时间展开步数为4; 表示为独热码有5个输入特征,每个时间步输入特征个数为5
x_train = np.reshape(x_train, (len(x_train), 4, 5)) #四个字母通过4个连续的时刻送入网络,所以时间展开步数是4
y_train = np.array(y_train)
model = tf.keras.Sequential([
SimpleRNN(3), #记忆体个数越多记忆力越好,但是占用资源更多
Dense(5, activation='softmax') #实现了yt的计算
])
model.compile(optimizer=tf.keras.optimizers.Adam(0.01),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])
checkpoint_save_path = "./checkpoint/rnn_onehot_4pre1.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
print('-------------load the model-----------------')
model.load_weights(checkpoint_save_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
save_weights_only=True,
save_best_only=True,
monitor='loss') # 由于fit没有给出测试集,不计算测试集准确率,根据loss,保存最优模型
history = model.fit(x_train, y_train, batch_size=32, epochs=100, callbacks=[cp_callback])
model.summary()
# print(model.trainable_variables)
file = open('./weights.txt', 'w') # 参数提取
for v in model.trainable_variables:
file.write(str(v.name) + '\n')
file.write(str(v.shape) + '\n')
file.write(str(v.numpy()) + '\n')
file.close()
############################################### show ###############################################
# 显示训练集和验证集的acc和loss曲线
acc = history.history['sparse_categorical_accuracy']
loss = history.history['loss']
plt.subplot(1, 2, 1)
plt.plot(acc, label='Training Accuracy')
plt.title('Training Accuracy')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(loss, label='Training Loss')
plt.title('Training Loss')
plt.legend()
plt.show()
############### predict #############
preNum = int(input("input the number of test alphabet:"))
for i in range(preNum):
alphabet1 = input("input test alphabet:")
alphabet = [id_to_onehot[w_to_id[a]] for a in alphabet1]
# 使alphabet符合SimpleRNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。此处验证效果送入了1个样本,送入样本数为1;输入4个字母出结果,所以循环核时间展开步数为4; 表示为独热码有5个输入特征,每个时间步输入特征个数为5
alphabet = np.reshape(alphabet, (1, 4, 5))
result = model.predict([alphabet])
pred = tf.argmax(result, axis=1)
pred = int(pred)
tf.print(alphabet1 + '->' + input_word[pred])
输出: