【TensorFlow】循环神经网络

【LSTM】

# 定义一个LSTM结构,在TensorFlow中通过一个简单的命令就可以实现一个完整的LSTM结构,LSTM中使用的变量也会在该函数中自动被声明
lstm = tf.nn.rnn_cell.BasicLSTMCell(lstm_hidden_size)

# 将LSTM中的状态初始化为全0数组,BasicLSTMCell类提供了zero_state函数来生成全0的初始状态,state是一个包含两个张量的LSTMStateTuple类,state.c和state.h
state = lstm.zero_state(batch_size, tf.float32)

loss = 0.0

# 虽然在测试时循环神经网络可以处理任意长度的序列,但是在训练中为了将循环网络展开成前馈神经网络,我们需要知道训练数据的序列长度,用num_steps来表示这个长度

for i in range(num_steps):
	# 在第一个时刻声明LSTM中使用的变量,在之后的时刻都需要复用之前定义好的变量
	if i>0:
		tf.get_variable_scope.reuse_variables()

	# 每一步处理时间序列中的一个时刻,将当前输入current_input(x_t)和前一时刻状态state(h_t-1 和 c_t-1)出阿奴人定义的LSTM结构可以得到当前LSTM的输出lstm_output(h_t)和更新后的状态state(h_t和c_t)。lstm_output用于输出给其他层,state用于输出给下一时刻。
	lstm_output, state = lstm(current_input, state)

	# 将当前lstm结构的输出传入一个全连接层得到最后的输出
	final_output = fully_connected(lstm_output)

	loss += calc_loss(final_output, expected_outupt)

【深层循环神经网络】
深层循环神经网络时循环神经网络的一种变种。为了增强模型的表达能力,可以在网络中设置多个循环层,将每层循环网络的输出传给下一层处理。在单层循环神经网络中,每一时刻的输入x_t到输出o_t之间只有一个全连接层,因此在x_t到o_t的路径上是一个很浅的神经网络,从输入中提取抽象信息的能力将受到限制。对于深层循环神经网络,每一时刻的输入x_t到输出o_t之间有L个循环体,网络因此可以从输入中抽取更加高层的信息。和卷积神经网络类似,每一层的循环体中参数是一致的,而不同层中的参数可以不同,tensorflow中提供了MultiRNNCell类来实现深层循环神经网络的前向传播过程。

lstm_cell = tf.nn.rnn_cell.BasicLSTMCell
stacked_lstm = tf.nn.rnn_cell.MultiLSTMCell([lstm_cell(lstm_size) for _ in range(number_of_layers)])

state = stacked_lstm.zero_state(batch_size, tf.float32)

for i in range(len(num_steps)):
	if i>0: tf.get_variable_scope.reuse_variables()
	stacked_lstm_output, state = stacked_lstm(current_input, state)
	final_output = fully_connected(stacked_lstm_output)
	loss += calc_loss(final_output, expected_outupt)

# 从以上代码可以看出,在tensorflow中只需要在BasicLSTMCell的基础上再封装一层MultiRNNCell就可以实现深层循环神经网络

【循环神经网络样例应用】

import numpy as np
import tensorflow as tf

HIDDEN_SIZE = 30
NUM_LAYERS = 2
TIMESTEPS = 10  # 循环神经网络的训练序列长度
TRAINING_STEPS = 10000
BATCH_SIZE = 32

TRAINING_EXAMPLES = 10000
TESTING_EXAMPLES= 1000
SAMPLE_GAP = 0.01  # 采样间隔

def generate_data(seq):
	x=[]
	y=[]
	
def lstm_model(X, y, is_training):
	cell = tf.nn.rnn_cell.MultiRNNCell(
		[tf.nn.rnn_cell.BasicLSTMCell(HIDDEN_SIZE) for _ in range(NUM_LAYERS)])

	# 使用tensorflow接口将多层的LSTM结构连接成RNN网络并计算其前向传播结果
	outputs, _ = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
	# outputs是顶层lstm在每一步的输出结果,它的维度是[batch_size, time, hidden_size]. 本问题只关注最后一个时刻的输出结果
	output = outputs[:, -1, :]

	predictions = tf.contrib.layers.fully_connected(output, 1, activation_fn=None)

	# 只在训练时计算损失函数和优化步骤,测试时直接返回预测结果
	if not is_training:
		return predictions, None, None

	loss = tf.losses.mean_squared_error(labels=y, predictions=predictions)
	train_op = tf.contrib.layers.optimize_loss(loss, tf.train.get_global_step(), optimizer='Adagrad', learning_rate=0.1)
	return predicitions, loss, train_op

def train(sess, train_X, train_y):
	ds = tf.data.Dataset.from_tensor_slices((train_X, train_y))
	ds = ds.repeat().shuffle(1000).batch(BATCH_SIZE)
	X, y	= ds.make_one_shot_iterator().get_next()

	with tf.variable_scope("model"):
		predictions, loss, train_op = lstm_model(X, y, True)

	sess.run(tf.global_variables_initializer())
	for i in range(TRAINING_STEPS):
		_, l = sess.run([train_op, loss])

def run_eval(sess, test_X, test_y):
	ds = tf.data.Dataset.from_tensor_slices((test_X, test_y))
	ds = ds.batch(1)
	X, y	= ds.make_one_shot_iterator().get_next()

	with tf.variable_scope("model", reuse=True):
		prediction, _, _ = lstm_model(X, [0.0], False)

	predictions = []
	labels = []
	for i in range(TESTING_EXAMPLES):
		p, l = sess.run([predictions, y])
		predictions.append(p)
		labels.append(l)

	predictions = np.array(predictions).squeeze()
	labels = np.array(labels).squeeze()
	rmse = np.sqrt(((predictions-labels)**2).mean(axis=0))

with tf.Session() as sess:
	train(sess, train_X, train_y)
	run_eval(sess, test_X, test_y)
	

参考资料:
TensorFlow:实战Google深度学习框架-中国工信出版集团

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值