赞
踩
时序预测是一个经典的话题,应用面也很广; 结合LSTM来做也是一个效果比较好的方式.
这次准备使用TF来进行时序预测,计划写两篇:
1. 使用Tensorflow Time Series模块
2. 使用底层点的LSTM Cell
这就是第一篇啦,Time Series Prediction via TFTS.
来源于此: TFTS介绍,略有加工整理,侵删!
Tensorflow Time Series(TFTS)模块是TF1.3版本中引入的,官方是这么介绍的:
TensorFlow Time Series (TFTS) is a collection of ready-to-use classic models (state space, autoregressive), and flexible infrastructure for building high-performance time series models with custom architectures.
地址: https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/timeseries,
里面给出了相关的examples.
主要提供三种预测模型:
AR、Anomaly Mixture AR、LSTM
你的数据可以是两种:
1. numpy array
2. from a CSV file
对于第一种: TFTS中可以使用NumpyReader
x = np.array(range(1000))
noise = np.random.uniform(-0.2, 0.2, 1000)
y = np.sin(np.pi * x / 100) + x / 200. + noise
data = {
tf.contrib.timeseries.TrainEvalFeatures.TIMES: x,
tf.contrib.timeseries.TrainEvalFeatures.VALUES: y,
}
reader = NumpyReader(data)
data是一个dict,’TIMES’和’VALUES’就是字符串的’times’和’values’,所以理论上你写成:
data = {'times':x, 'values':y}
,也是可以的.
对于第二种: TFTS中提供了CSVReader
csv_file_name = './data/period_trend.csv'
reader = tf.contrib.timeseries.CSVReader(csv_file_name)
对于以上两种Reader(CSVReader和NumpyReader),TFTS提供了对应的read_full()方法,返回的是时间序列的Tensor,read_full()产生读取队列,所以需要启动queue_runner然后才能run出值.
with tf.Session() as sess:
data = reader.read_full()
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
print(sess.run(data))
coord.request_stop()
获取batch数据也很简单: TFTS提供RandomWindowInputFn
train_input_fn = tf.contrib.timeseries.RandomWindowInputFn(reader, batch_size=4, window_size=16)
tf.contrib.timeseries.RandomWindowInputFn会在reader的所有数据中,随机选取窗口长度为window_size的序列,并包装成batch_size大小的batch数据。换句话说,一个batch内共有batch_size个序列,每个序列的长度为window_size.
AR(Auto Regression)是统计学上的方法,可以参考wiki: https://en.wikipedia.org/wiki/Autoregressive_model,主要的思想是假设当前值与前面出现的值是线性关系.
autoregressive model specifies that the output variable depends linearly on its own previous values and on a stochastic term (an imperfectly predictable term).
对于AR模型:TFTS提供了ARRegrerssior
ar = tf.contrib.timeseries.ARRegressor(
periodicities=200, input_window_size=30, output_window_size=10,
num_features=1,
loss=tf.contrib.timeseries.ARModel.NORMAL_LIKELIHOOD_LOSS)
在这里,我们总的window_size为40,input_window_size为30,output_window_size为10,也就是说,一个batch内每个序列的长度为40,其中前30个数被当作模型的输入值,后面10个数为这些输入对应的目标输出值。最后一个参数loss指定采取哪一种损失,一共有两种损失可以选择,分别是NORMAL_LIKELIHOOD_LOSS和SQUARED_LOSS. num_features参数表示在一个时间点上观察到的数的维度。我们这里每一步都是一个单独的值,所以num_features=1。
还有一个比较重要的参数是model_dir,它表示模型训练好后保存的地址,如果不指定的话,就会随机分配一个临时地址.
训练、验证(对训练集进行)、测试:
ar.train(input_fn=train_input_fn, steps=1000)
evaluation_input_fn = tf.contrib.timeseries.WholeDatasetInputFn(reader)
# keys of evaluation: ['covariance', 'loss', 'mean', 'observed', 'start_tuple', 'times', 'global_step']
evaluation = ar.evaluate(input_fn=evaluation_input_fn, steps=1)
(predictions,) = tuple(ar.predict(
input_fn=tf.contrib.timeseries.predict_continuation_input_fn(
evaluation, steps=250))) #预测之后的250步
结果大概是这样:
红色是预测的那一段.
必须使用TF最新的开发版的代码,就是要保证’rom tensorflow.contrib.timeseries.python.timeseries.estimators import TimeSeriesRegressor’可以导入成功.
estimator = ts_estimators.TimeSeriesRegressor(
model=_LSTMModel(num_features=1, num_units=128),
optimizer=tf.train.AdamOptimizer(0.001))
_LSTMModel
是一个class,可以直接copy官方给的代码.
接下来的训练、验证、测试和上面的AR模型是一样的.
结果大概是这样的:
自己只把关键点写出来了,有需要的可以去看原文,原文比较详细.
代码地址: https://github.com/hzy46/TensorFlow-Time-Series-Examples
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。