TensorFlow学习笔记——(11)循环神经网络
文章目录
- 一、循环核
- 二、循环核时间步展开
- 三、循环计算层
- 四、TF描述循环计算层
- 五、循环计算过程
- 1、RNN实现单个字母预测
- (1)过程
- (2)完整代码
- 2、RNN实现输入多个字母,预测一个字母
- (1)过程
- (2)完整代码
- 六、补充
- 1、AttributeError: 'tuple' object has no attribute 'shape'
一、循环核
首先回顾下卷积神经网络:
- 卷积核:参数空间共享,卷积层提取空间信息。
- 卷积神经网络:借助卷积核提取空间特征后,送入全连接网络。
然后引入循环核:
- 循环核:参数时间共享,循环曾提取时间信息。循环核具有记忆力,通过不同时刻的参数共享,实现了对时间序列的信息提取
循环核表示为下面结构,中间圆柱是记忆体,可以设定记忆体的个数,改变记忆容量,当记忆体个数被指定时,输入xt、输出yt维度被指定,周围这些待训练参数(Why,Whh,Wxh)的维度也就被限定了。
记忆体内存储着每个时刻的状态信息ht,记忆体当前时刻存储的状态信息ht,等于下式:
当前时刻循环核的输出特征yt,等于下式:
- 前向传播时,记忆体内存储的状态信息ht,在每个时刻都被刷新,三个参数矩阵wxh、whh、why自始至终都是固定不变的。
- 反向传播时,三个参数矩阵wxh、whh、why被梯度下降法更新。
二、循环核时间步展开
按照时间步展开,就是把循环核按照时间轴方向展开,表示图如下:
每个时刻记忆体状态信息ht被刷新,记忆体周围的参数矩阵wxh、whh、why是固定不变的,我们训练优化的就是这些参数矩阵,训练完成后,使用效果最好的参数矩阵,执行前向传播,输出预测结果。
循环神经网络:借助循环核提取时间特征后,送入全连接网络,实现连续数据的预测。
yt是整个循环网络的末层,从公式来看,就是一个全连接网络,实现连续数据预测。
三、循环计算层
每个循环核构成一层循环计算层,循环计算层的层数是向输出方向增长的,也就是循环核是纵向连接的,有几个循环核就是基层循环计算层,它们中的每个循环核中记忆体的个数,是根据需求任意指定的。
四、TF描述循环计算层
TF描述循环计算层的函数:
一般来讲,中间的层循环核用True,每个时间步都把ht输出给下一层,最后一层的循环核用False, 仅在最后一个时间步输出ht。
- True,每个时间步都把ht输出给下一层
- False, 仅在最后一个时间步输出ht
API对送入循环层的数据维度是有要求的,要求送入RNN的数据是三维的,格式如下:
例子如下: - 一共要送入RNN层两组数据,每组数据经过一个时间步就会得到输出结果,每个时间步送入三个数值,因此输入循环层的数据维度就是[2,1,3]
- 还有一组数据,分四个时间步送入循环层,每个时间步送入两个数值,因此输入循环层的数据维度就是[1,4,2]
五、循环计算过程
1、RNN实现单个字母预测
(1)过程
用字母预测的例子来展示循环计算过程,规则如下:
1)首先,因为网络输入的都是数字,因此将字母以独热码形式进行编码表示;
2)随机生成Wxh、Whh、Why三个参数矩阵,记忆体的个数选取3,结构如下:
3)ht的计算如下:
4)过tanh激活函数后,得到当前时刻的状态信息ht,因此需要刷新记忆体存储的状态信息,也就是替换ht-1:
5)然后计算输出yt,这里yt输出是把提取到的时间信息,通过全连接进行识别预测的过程:
(2)完整代码
# import相关模块
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, SimpleRNN
import matplotlib.pyplot as plt
import os# 用到的字母是abcde
input_word = "abcde"
# 为了送入神经网络,把字母表示为01234
w_to_id = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4} # 单词映射到数值id的词典
# 01234编码为独热码
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,标签y_train
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['e']]]
y_train = [w_to_id['b'], w_to_id['c'], w_to_id['d'], w_to_id['e'], w_to_id['a']]# 打乱训练集顺序
np.random.seed(7)
np.random.shuffle(x_train)
np.random.seed(7)
np.random.shuffle(y_train)
tf.random.set_seed(7)# 把输入特征变成RNN层期待的形状
# 使x_train符合SimpleRNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。
# 此处整个数据集送入,送入样本数为len(x_train);输入1个字母出结果,循环核时间展开步数为1; 表示为独热码有5个输入特征,每个时间步输入特征个数为5
x_train = np.reshape(x_train, (len(x_train), 1, 5))
# y_train变为numpy格式
y_train = np.array(y_train)# 搭建具有3个记忆体的循环层,3是自己随意设定的
model = tf.keras.Sequential([SimpleRNN(3),# 全连接层,实现了输出层yt的计算Dense(5, activation='softmax')
])# 配置训练参数
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_1pre1.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[alphabet1]]]# 使alphabet符合SimpleRNN输入要求:# [送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。此处验证效果送入了1个样本,送入样本数为1;输入1个字母出结果,所以循环核时间展开步数为1; 表示为独热码有5个输入特征,每个时间步输入特征个数为5alphabet = np.reshape(alphabet, (1, 1, 5))# predict输出预测结果result = model.predict(alphabet)# 选出预测结果最大的一个pred = tf.argmax(result, axis=1)pred = int(pred)tf.print(alphabet1 + '->' + input_word[pred])
2、RNN实现输入多个字母,预测一个字母
(1)过程
以连续输入四个字母,预测下一个字母的例子,来介绍循环核按时间展开后,循环计算过程。
1)使用三个记忆体,初始时刻,记忆体内的记忆是0,在这个过程中的每个时刻参数矩阵是固定的,记忆体会在每个时刻被更新。
2)在第一个时刻,b的独热码[0,1,0,0,0]输入,记忆体根据更新公式刷新为[-0.9,0.2,0.2]
3)在第二个时刻,c的独热码[0,0,1,0,0]输入,记忆体根据更新公式刷新为[0.8,1.0,0.8]
4)在第三个时刻,d的独热码[0,0,0,1,0]输入,记忆体根据更新公式刷新为[0.6,0.5,-0.1]
5)在第四个时刻,e的独热码[0,0,0,0,1]输入,记忆体根据更新公式刷新为[-1.0,-1.0,0.8]
6)输出预测通过全连接完成,代入yt计算公式,得到[0.71,0.14,0.10,0.05,0.00]
(2)完整代码
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, SimpleRNN
import matplotlib.pyplot as plt
import os# 用到的字母是abcde
input_word = "abcde"
# 为了送入神经网络,把字母表示为01234
w_to_id = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4} # 单词映射到数值id的词典
# 01234编码为独热码
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,标签y_train
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)# 把输入特征变成RNN层期待的形状
# 使x_train符合SimpleRNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]。
# 此处整个数据集送入,送入样本数为len(x_train);输入4个字母出结果,循环核时间展开步数为4; 表示为独热码有5个输入特征,每个时间步输入特征个数为5
x_train = np.reshape(x_train, (len(x_train), 4, 5))
# y_train变为numpy格式
y_train = np.array(y_train)# 搭建具有3个记忆体的循环层,3是自己随意设定的
model = tf.keras.Sequential([SimpleRNN(3),
# 全连接层,实现了输出层yt的计算Dense(5, activation='softmax')
])# 配置训练参数
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个输入特征,每个时间步输入特征个数为5alphabet = 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])
六、补充
1、AttributeError: ‘tuple’ object has no attribute ‘shape’
预测部分的原始代码是这样的:
result = model.predict([alphabet])
然后在运行的时候,可以正常训练,但是预测总是出错,指向上面这一行,问题是 AttributeError: 'tuple' object has no attribute 'shape'
,也没太看懂是什么意思,但是查资料看到predict里面好像直接写预测样本就可以,就尝试把[]去掉,然后成功解决哈哈哈
修改过后:
result = model.predict(alphabet)
TensorFlow学习笔记——(11)循环神经网络相关推荐
- 学习笔记TF053:循环神经网络,TensorFlow Model Zoo,强化学习,深度森林,深度学习艺术...
循环神经网络.https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/re ...
- 【深度学习笔记】循环神经网络和递归神经网络区别
1.循环神经网络(recurrent neural network)是时间上的展开,处理的是序列结构的信息,是有环图,模型结构如下: recurrent: 时间维度的展开,代表信息在时间维度从前往后的 ...
- TensorFlow学习笔记之三(神经网络的优化)
文章目录 1. 使用激活函数去线性化(为什么要用激活函数) 实验证明线性模型的局限性 常用激活函数 2. 神经网络复杂度:用网络层数和网络参数的个数表示 3. 损失函数(loss):预测值(y)与已知 ...
- tensorflow学习笔记七----------卷积神经网络
卷积神经网络比神经网络稍微复杂一些,因为其多了一个卷积层(convolutional layer)和池化层(pooling layer). 使用mnist数据集,n个数据,每个数据的像素为28*28* ...
- 神经网络学习笔记-02-循环神经网络
神经网络学习笔记-02-循环神经网络 本文是根据WildML的Recurrent Neural Networks Tutorial写的学习笔记. 循环神经网络 循环神经网络适用于处理序列化信息,比如: ...
- tensorflow学习笔记二——建立一个简单的神经网络拟合二次函数
tensorflow学习笔记二--建立一个简单的神经网络 2016-09-23 16:04 2973人阅读 评论(2) 收藏 举报 分类: tensorflow(4) 目录(?)[+] 本笔记目的 ...
- 深度学习笔记:卷积神经网络的Tensorflow实现
文章出处:深度学习笔记11:利用numpy搭建一个卷积神经网络 免费视频课程:Hellobi Live | 从数据分析师到机器学习(深度学习)工程师的进阶之路 在上一讲中,我们学习了如何利用 nump ...
- 深度学习与计算机视觉教程(11) | 循环神经网络及视觉应用(CV通关指南·完结)
作者:韩信子@ShowMeAI 教程地址:https://www.showmeai.tech/tutorials/37 本文地址:https://www.showmeai.tech/article-d ...
- tensorflow学习笔记——使用TensorFlow操作MNIST数据(1)
续集请点击我:tensorflow学习笔记--使用TensorFlow操作MNIST数据(2) 本节开始学习使用tensorflow教程,当然从最简单的MNIST开始.这怎么说呢,就好比编程入门有He ...
- tensorflow学习笔记1
tensorflow学习笔记1 本文主要记录我在慕课上观看北大曹建老师的<人工智能实践:Tensorflow笔记>,链接:https://www.icourse163.org/course ...
最新文章
- 人工智能是这样理解真正的活过了
- MySQL自增长主键探究
- 水平拉滑轮组计算机械效率的题,机械效率杠杆论文,关于中考物理机械效率计算题*相关参考文献资料-免费论文范文...
- WMI CIM studio无法连接解决 在XP下wmi取不到值可巧用wmic取值
- php+堆排序算法,排序算法-堆排序-php
- 小程序 textarea ios兼容解决
- Docker - 避免启动container后运行shell脚本执行完成后docker退出container
- 2020年度国家自然科学基金医学领域结果公布(9月27后可查)
- java 蓝桥杯 求先序排列
- ASP基础教程之ASP AdRotator 组件的使用
- 解决mysql“Access denied for user 'root'@'localhost'”
- 关于水晶报表打包的一些注意的地方!
- 13个Excel动图小技巧,快速提高工作效率?建议收藏!
- 鼠标单击变双击修正工具软件DoubleClickFix下载
- 带你玩转IntelliJ IDEA 使用教程(2019图文版)
- PHP进销存软件源代码ERP多仓储管理系统源码
- 金财助手 - 安装分析(一)
- pd对焦速度_自动对焦速度是由相机还是镜头决定的?
- CentOS7使用firewalld打开关闭防火墙与端口
- 没有配置resolv.conf