python 时间序列预测——Elman循环神经网络

数据集

COE 下载参见 python 时间序列预测——简单神经网络

设定输入输出变量并归一化

from sklearn import preprocessing
import pandas as pd

loc= "COE.csv "
temp = pd.read_csv ( loc )
data= temp . drop ( temp . columns [ [ 0 , 1 ] ] , axis=1)

x=data.drop ( data . columns [ [ 0 , 4 ] ] , axis =1)
x=x.apply(np.log )
x=pd.concat ( [ x , data ['Open?' ] ] , axis=1)

scaler_x = preprocessing . MinMaxScaler (feature_range=(0 , 1) )
x = np .array ( x ) . reshape ( ( len ( x ) ,4 ) )
x = scaler_x . fit_transform ( x )

y=data ['COE$']
scaler_y = preprocessing . MinMaxScaler (feature_range=(0 , 1) )
y = np . array ( y ) . reshape ( ( len ( y ) , 1) )
y = np . log ( y )
y = scaler_y . fit_transform ( y )

y = y.tolist ( )
x = x.tolist ( )

ElmanRecurrent

python 时间序列预测——Elman循环神经网络_第1张图片
python 时间序列预测——Elman循环神经网络_第2张图片

import random
from pyneurgen.neuralnet import NeuralNet
from pyneurgen.recurrent import ElmanSimpleRecurrent 

random.seed (2019)
model = NeuralNet ()
input_nodes = 4
hidden_nodes = 7
output_nodes = 1
model.init_layers ( input_nodes ,
                    [ hidden_nodes ],
                    output_nodes ,
                    ElmanSimpleRecurrent ())
model.randomize_network ()
model.layers [1]. set_activation_type ('sigmoid')
model.set_learnrate (0.05)
model.set_all_inputs (x)
model.set_all_targets (y)

length = len(x)
learn_end_point = int( length * 0.95)
model .set_learn_range (0, learn_end_point )
model .set_test_range ( learn_end_point + 1, length -1)
model . learn ( epochs =100 , show_epoch_results=True , random_testing=False)

mse = model. test ()
print(" test set MSE =",np.round(mse ,6))

target = np.array([ item [0][0] for item in fit1.test_targets_activations ])
pred = [ item [1][0] for item in fit1.test_targets_activations ]
# pred1 = scaler_y.inverse_transform (np.array( pred ). reshape((len(pred), 1)))  # 恢复
# pred1 = np.exp(pred1)

plt.plot(target)
plt.plot(pred)
plt.plot(target*1.05,'--g',target*0.95,'--g')
plt.legend(['target','prediction','CI'])

python 时间序列预测——Elman循环神经网络_第3张图片

你可能感兴趣的:(时间序列,#,编程语言)