-
Notifications
You must be signed in to change notification settings - Fork 1
/
CEEMDAN.py
211 lines (168 loc) · 7.38 KB
/
CEEMDAN.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import numpy as np
import pandas as pd
from pandas import read_csv
from pandas import DataFrame
from datetime import datetime
from matplotlib import pyplot
from pylab import mpl
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import mean_squared_error
from pandas import concat
from PyEMD import CEEMDAN,EMD
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.layers import Dropout
from keras.layers import Activation
from scipy import interpolate, math
import matplotlib . pyplot as plt
from keras import Input, Model
from keras.layers import Dense
from keras.models import load_model
def data_split(data, train_len, lookback_window):
train = data [: train_len ] # mark the training set
test = data [ train_len :] # mark the test set
# X1[] represents 10 numbers in the moving window
# Y1[] represents the number of predictions that the corresponding moving window needs to predict
# X2, Y2 the same
X1 , Y1 = [], []
for i in range ( lookback_window , len ( train )):
X1.append(train[i - lookback_window:i])
Y1.append(train[i])
Y_train = np.array(Y1)
X_train = np.array(X1)
X2 , Y2 = [], []
for i in range ( lookback_window , len ( test )):
X2.append(test[i - lookback_window:i])
Y2.append(test[i])
y_test = np.array(Y2)
X_test = np.array(X2)
return (X_train, Y_train, X_test, y_test)
def data_split_LSTM(X_train, Y_train, X_test, y_test): # data split f
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
Y_train = Y_train.reshape(Y_train.shape[0], 1)
y_test = y_test.reshape(y_test.shape[0], 1)
return (X_train, Y_train, X_test, y_test)
def imf_data(data, lookback_window):
X1 = []
for i in range ( lookback_window , len ( data )):
X1.append(data[i - lookback_window:i])
X1.append(data[len(data) - 1:len(data)])
X_train = np.array(X1)
return X_train
def visualize(history):
plt.rcParams['figure.figsize'] = (10.0, 6.0)
# Plot training & validation loss values
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt . xlabel ( 'Epoch' )
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
def LSTM_Model(X_train, Y_train,i):
filepath = 'res/' + str(i) + '-{epoch:02d}-{val_acc:.2f}.h5'
checkpoint = ModelCheckpoint(filepath, monitor='loss',verbose=1,save_best_only=False,mode='auto',period=10)
callbacks_list = [checkpoint]
model = Sequential()
model . add ( LSTM ( 32 , input_shape = ( X_train . shape [ 1 ], X_train . shape [ 2 ]), return_sequences = True )) # 10 steps already determined
'''
If you set return_sequences = True, the LSTM layer will return h for each time step,
Then the layer returns a 2-dimensional array composed of multiple h, if the next layer is not able to receive a 2-dimensional array
layer, an error will be reported. So in general, if the LSTM layer is followed by the LSTM layer, set return_sequences = True,
If connecting to a fully connected layer, set return_sequences = False.
'''
model.add(LSTM(units=32))
model.add(Dense(1))
model.add(Activation('tanh'))
model.compile(loss='mse', optimizer='adam')
model.fit(X_train, Y_train, epochs=5, batch_size=16, validation_split=0.1, verbose=2, shuffle=True)
return (model)
def plot_curve(true_data, predicted):
rmse=format(RMSE(test,prediction),'.4f')
mape=format(MAPE(test,prediction),'.4f')
plt.plot(true_data, label='True data')
plt.plot(predicted, label='Predicted data')
plt . legend ()
plt.text(1, 1, 'RMSE:' + str(rmse)+' \n '+'MAPE:'+str(mape), color = "r",style='italic', wrap=True)
# plt.text(2, 2, "RMSE:" + str(format(RMSE(true_data,predicted),'.4f'))+" \n "+"MAPE:"+str(format(MAPE(true_data,predicted),'.4f')), style='italic', ha='center', wrap=True)
#plt.savefig('result_EEMD_LSTM_E5B16.png')
# plt.show()
def RMSE(test, predicted):
rmse = math.sqrt(mean_squared_error(test, predicted))
return rmse
def MAPE ( Y_true , Y_pred ):
Y_true , Y_pred = np . array ( Y_true ), np . array ( Y_pred )
return np.mean(np.fabs((Y_true - Y_pred) / Y_true)) * 100
if __name__ == '__main__':
plt.rcParams['figure.figsize'] = (10.0, 5.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
dataset = pd.read_csv('../csv/pricing.csv', header=0, index_col=0, parse_dates=True)
data = dataset.values.reshape(-1)
values = dataset.values
groups = [0, 1, 2, 3]
# fig, axs = plt.subplots(1)
df = pd . DataFrame ( dataset ) # full dictionary type of overall data
do = df [ 'ETHEREUM_CLOSE' ] # Return the column of ETHEREUM_CLOSE, in the form of a dictionary
DO = []
for i in range ( 0 , len ( do )):
DO.append([do[i]])
scaler_DO = MinMaxScaler(feature_range=(0, 1))
DO = scaler_DO.fit_transform(DO)
emd = CEEMDAN()
imfs = emd.emd(DO.reshape(-1),None,8)
c = int(len(do) * .9)
lookback_window = 10
imfs_prediction = []
# i = 1
# for imf in imfs:
# plt.subplot(len(imfs), 1, i)
# plt.plot(imf)
# i += 1
#
# plt.savefig('res/result_imf.png')
# plt.show()
test = np.zeros([len(do) - c - lookback_window, 1])
# i = 1
# for imf in imfs:
# print('-' * 45)
# print('This is ' + str(i) + ' time(s)')
# print('*' * 45)
# X1_train, Y1_train, X1_test, Y1_test = data_split(imf_data(imf, 1), c, lookback_window)
# X2_train, Y2_train, X2_test, Y2_test = data_split_LSTM(X1_train, Y1_train, X1_test, Y1_test)
# test += Y2_test
# model = load_model('EEMD-LSTM-B1-E100/EEMD-LSTM-imf' + str(i) + '-100.h5')
# prediction_Y = model.predict(X2_test)
# imfs_prediction.append(prediction_Y)
# i += 1;
i = 1
for imf in imfs:
print('-'*45)
print('This is ' + str(i) + ' time(s)')
print('*'*45)
X1_train, Y1_train, X1_test, Y1_test = data_split(imf_data(imf,1), c, lookback_window)
X2_train, Y2_train, X2_test, Y2_test = data_split_LSTM(X1_train, Y1_train, X1_test, Y1_test)
test += Y2_test
model = LSTM_Model(X2_train,Y2_train,i)
model.save('EEMD-LSTM-imf' + str(i) + '.h5')
prediction_Y = model.predict(X2_test)
imfs_prediction.append(prediction_Y)
i+=1;
imfs_prediction = np.array(imfs_prediction)
prediction = [0.0 for i in range(len(test))]
prediction = np.array(prediction)
for i in range ( len ( test )):
t = 0.0
for imf_prediction in imfs_prediction:
t += imf_prediction[i][0]
prediction[i] = t
prediction = prediction.reshape(prediction.shape[0], 1)
# test = scaler_DO.inverse_transform(test)
# prediction = scaler_DO.inverse_transform(prediction)
# plot_curve(test, prediction)
print(RMSE(test, prediction))
print(MAPE(test, prediction))