# -*- coding: utf-8 -*-
'''
Created on 2018年11月27日

@author: Zhukun Luo
Jiangxi university of finance and economics
'''
#自回归模型
from __future__ import print_function
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,CSVReader
#接着，利用np.sin生成一个实验用的时间序列数据，改时间序列数据实际上是在正弦曲线上加入了上升的趋势和一些随机的噪声
x=np.array(range(1000))
noise=np.random.uniform(-0.2,0.2,1000)
y=np.sin(np.pi*x/100)+x/200+noise
plt.plot(x,y)
plt.savefig('timeseries_y.jpg')
data={#以numpy的形式读入
    tf.contrib.timeseries.TrainEvalFeatures.TIMES:x,
    tf.contrib.timeseries.TrainEvalFeatures.VALUES:y
    }
reader=NumpyReader(data)
#建立batch数据集
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)
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)
#print(evaluation)\
(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('./predict_result.jpg')
