资源简介
使用LSTM预测铁路客运时间序列,代码在tensorflow 1.3上调试运行通过,解决了网络相关资源的一些坑(很多资源不是tensorflow的版本太旧就是数据与铁路客运数据不太匹配,难以直接运行测试),不需要建立train模型和test模型(被绕了半天,这种测试应该毫无必要),可对不同的超参数组合比较训练误差和学习误差!
代码片段和文件信息
# coding: utf-8
“““
2017-8-20
使用最基本的LSTM神经网预测客运数据
HParams: 模型的超参数
TS_LSTM:时间序列训练的LSTM模型
train_test:训练和测试函数
@ 蒋秋华
“““
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import pandas as pd
from collections import namedtuple
“““
简单的时间序列LSTM模型!
“““
HParams = namedtuple(‘HParams‘
‘seq_size hidden_size learning_rate‘)
class TS_LSTM(object):
def __init__(self hps):
self._X = X = tf.placeholder(tf.float32 [None hps.seq_size 1])
self._Y = Y = tf.placeholder(tf.float32 [None hps.seq_size])
W = tf.Variable(tf.random_normal([hps.hidden_size 1]) name=‘W‘)
b = tf.Variable(tf.random_normal([1]) name=‘b‘)
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(hps.hidden_size) #测试cost 1.3809
# lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(config.hidden_sizeactivation=tf.nn.relu) #测试cost 261.078,性能太差
outputs states = tf.nn.dynamic_rnn(lstm_cell X dtype=tf.float32)
W_repeated = tf.tile(tf.expand_dims(W 0) [tf.shape(X)[0] 1 1])
output = tf.nn.xw_plus_b(outputs W_repeated b)
self._output = output = tf.squeeze(output)
self._cost = cost = tf.reduce_mean(tf.square(output - Y))
self._train_op = tf.train.AdamOptimizer(hps.learning_rate).minimize(cost)
@property
def X(self):
return self._X
@property
def Y(self):
return self._Y
@property
def cost(self):
return self._cost
@property
def output(self):
return self._output
@property
def train_op(self):
return self._train_op
def train_test(hps data):
#训练数据准备
train_data_len = len(data)*2//3
train_x train_y = [] []
for i in range(train_data_len - hps.seq_size - 1):
train_x.append(np.expand_dims(data[i : i + hps.seq_size] axis=1).tolist())
train_y.append(data[i + 1 : i + hps.seq_size + 1].tolist())
#测试数据准备
test_data_len = len(data)//3
test_x test_y = [] []
for i in range(train_data_len
train_data_len+test_data_len - hps.seq_size - 1):
test_x.append(np.expand_dims(data[i : i + hps.seq_size] axis=1).tolist())
test_y.append(data[i + 1 : i + hps.seq_size + 1].tolist())
with tf.Graph().as_default() tf.Session() as sess:
with tf.variable_scope(‘model‘reuse=None):
m_train = TS_LSTM(hps)
# with tf.variable_scope(‘model‘reuse=True): #建立的测试模型没有什么用!
# m_test = TS_LSTM(Falseconfig)
#训练
tf.global_variables_initializer().run()
for step in range(20000):
_ train_cost = sess.run([m_train.train_op m_train.cost]
feed_dict={m_train.X: train_x m_train.Y: train_y})
#预测
test_cost output = sess.run([m_train.cost m_train.output]
feed_dict={m_tra
评论
共有 条评论