TensorFlow(二)AR 时间序列

AR

# 代码引用自
#《21个项目玩转深度学习:Tensorflow的实践详解》
# 代码包含少量修改

# 导入依赖包
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib.timeseries.python.timeseries import NumpyReader
# 生成带上升趋势和随机噪声的正弦序列
x = np.array(range(1000))
noise = np.random.uniform(-0.2, 0.2, 1000)
y = np.sin(x) + x/200. + noise
# 数据封装
data = {
    tf.contrib.timeseries.TrainEvalFeatures.TIMES: x,
    tf.contrib.timeseries.TrainEvalFeatures.VALUES: y
}
# 读取数据
reader = NumpyReader(data)
train_input_fn = tf.contrib.timeseries.RandomWindowInputFn(
    reader, batch_size=16, window_size=40
)
# 建模训练
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
)
# periodicities 规律性周期
# input_window_size + output_window_size = window_size
# num_feathers  VALUES 的维度
# loss 有两种方案可选:NORMAL_LIKELIHOOD_LOSS 和 SQUARED_LOSS
ar.train(input_fn=train_input_fn, steps=6000)
# 模型检验和预测
evaluation_input_fn = tf.contrib.timeseries.WholeDatasetInputFn(reader)
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
        )
    )
)
# 绘图
plt.figure(figsize=(15, 5))
plt.plot(data['times'].reshape(-1), data['values'].reshape(-1), label='origin')
plt.plot(evaluation['times'].reshape(-1), evaluation['mean'].reshape(-1), label='evaluation')
plt.plot(predictions['times'].reshape(-1), predictions['mean'].reshape(-1), label='predictions')
plt.xlabel('time_step')
plt.ylabel('values')
plt.legend(loc=4)
plt.savefig('ar.jpg')

ar.jpg

猜你喜欢

转载自blog.csdn.net/lolimostlovely/article/details/81984585