Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.00 KB | None | 0 0
  1. from __future__ import print_function
  2. from keras.models import Sequential
  3. from keras.layers import Dense, LSTM
  4. import numpy as np
  5. import statsmodels.api as sm
  6. import matplotlib.pyplot as plt
  7. import pandas as pd
  8.  
  9. from statsmodels.tsa.arima_process import arma_generate_sample
  10. # from statsmodels.tsa.arima_model import _arma_predict_out_of_sample
  11. np.random.seed(11111)
  12. nobs = 1000
  13. dates = sm.tsa.datetools.dates_from_range('1980m1', length=nobs)
  14. ar_params=[0.5]
  15. ma_params=[0.5]
  16.  
  17. def sqerror(predicted,actual):
  18. return (actual-predicted).pow(2)
  19.  
  20. tsteps = 1
  21. batch_size = 5
  22. epochs = 20
  23. # number of elements ahead that are used to make the prediction
  24. # lahead = 1
  25.  
  26. print('Creating Model')
  27. model = Sequential()
  28. model.add(LSTM(10,
  29. batch_input_shape=(batch_size, tsteps, 1),
  30. return_sequences=True,
  31. stateful=False))
  32. model.add(LSTM(10,
  33. return_sequences=False,
  34. stateful=True))
  35. model.add(Dense(1))
  36. model.compile(loss='mse', optimizer='rmsprop')
  37.  
  38. print('Training')
  39. for i in range(epochs):
  40. print('Epoch', i, '/', epochs)
  41. y=arma_generate_sample(np.r_[1, -np.array(ar_params)],
  42. np.r_[1, np.array(ma_params)],
  43. nsample=nobs,
  44. sigma=1)
  45. y=y/y.std()
  46. yexp=np.expand_dims(np.expand_dims(y,axis=1),axis=1)
  47. resexp=np.expand_dims(np.roll(y,shift=-1),axis=1)
  48. model.fit(yexp,
  49. resexp,
  50. batch_size=batch_size,
  51. verbose=0,
  52. nb_epoch=1,
  53. shuffle=False)
  54. model.reset_states()
  55.  
  56. # generate unseen one for predicting
  57. y=arma_generate_sample(np.r_[1, -np.array(ar_params)],
  58. np.r_[1, np.array(ma_params)],
  59. nsample=nobs,
  60. sigma=1)
  61. y=y/y.std()
  62. ys = pd.Series(y, index=dates)
  63. yexp=np.expand_dims(np.expand_dims(y,axis=1),axis=1)
  64.  
  65. print('LSTM Predicting')
  66. predicted_output = model.predict(yexp, batch_size=batch_size)
  67. lstmerr=sqerror(predicted_output[:,0],ys)
  68.  
  69. print('ARMA Model and predicting')
  70. arma_mod = sm.tsa.ARMA(ys, order=(len(ar_params),len(ar_params)))
  71. arma_res = arma_mod.fit(trend='nc', disp=-1)
  72. armapred=arma_res.predict(start=0,end=nobs-1)
  73. # BIGGEST HACK HERE: shift ahead by one
  74. # I'm giving it a perhaps an unfair boost
  75. # I suspect not properly forecasting
  76. armapred=armapred.shift(-1)
  77. armaerr=sqerror(armapred,ys)
  78.  
  79. # Zero model
  80. zeroerr=sqerror(np.zeros(armapred.shape),ys)
  81. # Perfect model
  82. perfecterr=sqerror(ys,ys)
  83.  
  84. print(lstmerr.mean())
  85. print(armaerr.mean())
  86.  
  87. plot_limit=200
  88. plt.subplot(2,1,1)
  89. plt.plot(yexp[:plot_limit,0,0],'o-',alpha=0.7,label='actual')
  90. plt.plot(predicted_output[:plot_limit,0],'o-',alpha=0.7,label='lstm')
  91. plt.plot(armapred[:plot_limit],'o-',alpha=0.7,label='arma')
  92. plt.legend()
  93. plt.title('time series')
  94. plt.subplot(2,1,2)
  95. plt.plot((perfecterr).cumsum()[:plot_limit],label='perfect')
  96. plt.plot((lstmerr).cumsum()[:plot_limit],label='lstm')
  97. plt.plot((armaerr).cumsum()[:plot_limit],label='arma')
  98. plt.legend()
  99. plt.title('Accumulated square errors (lower is better)')
  100. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement