文章目录
- 1、序言
- 2、仅用时序y进行预测
- 3、使用全部时序进行预测
1、序言
-
样本介绍
-
现有一样本,含3个时序【y、y1、y2】,其中【y】受【y1、y2】影响
-
目标
-
对【时序y】进行预测
import numpy as np, matplotlib.pyplot as mp
x_len = 1075
x = np.linspace(0, np.pi * 10.75, x_len, endpoint=False)
y = np.cos(x) + np.sin(x * 5) * .2
y1 = np.sin(x) + 2.6
y2 = np.cos(x * 5) * .2 + 1.4
mp.plot(x, y1, 'y', label='y1')
mp.plot(x, y2, label='y2')
mp.plot(x, y, 'g', label='y', linewidth=2)
mp.legend()
mp.show()
2、仅用时序y进行预测
import numpy as np, matplotlib.pyplot as mp
from keras.models import Sequential
from keras.layers import Dense, LSTM
"""创建样本"""
x_len = 1075
x = np.linspace(0, np.pi * 10.75, x_len, endpoint=False)
y = np.cos(x) + np.sin(x * 5) * .2
y = (y - min(y)) / (max(y) - min(y))
window = 75
X = np.reshape([y[i: i + window] for i in range(x_len - window)],
(-1, window, 1))
Y = y[window:].reshape(-1, 1)
"""建模"""
model = Sequential()
model.add(LSTM(50, input_shape=(window, 1), return_sequences=True))
model.add(LSTM(100))
model.add(Dense(1))
model.compile('adam', 'mse')
model.fit(X, Y, batch_size=100, epochs=20, verbose=2)
"""预测"""
pred_len = 200
for start in (0, 333, 666, 999):
x_pred = np.linspace(np.pi * (window + start) / 100,
np.pi * (window + start + pred_len) / 100,
pred_len, endpoint=False)
y_pred = []
X_pred = X[start]
for i in range(pred_len):
Y_pred = model.predict(X_pred.reshape(-1, window, 1))
y_pred.append(Y_pred[0])
X_pred = np.concatenate((X_pred, Y_pred))[1:]
mp.scatter(x_pred[0], y_pred[0], c='r', s=9)
mp.plot(x_pred, y_pred, 'r')
mp.plot(x, y, 'y', linewidth=5, alpha=0.3)
mp.show()
3、使用全部时序进行预测
import numpy as np, matplotlib.pyplot as mp
from keras.models import Sequential
from keras.layers import Dense, LSTM
from sklearn.preprocessing import MinMaxScaler
"""创建样本"""
x_len = 1075
x = np.linspace(0, np.pi * 10.75, x_len, endpoint=False)
y = np.array([[np.sin(x[i] * 5) * .2 + np.cos(x[i]),
np.cos(x[i] * 5) * .2,
np.sin(x[i])] for i in range(x_len)])
y = MinMaxScaler().fit_transform(y)
d = y.shape[1]
window = 75
X = np.array([[[y[j, k] for k in range(d)] for j in range(i, i + window)]
for i in range(x_len - window)])
Y = np.array([[y[i, k] for k in range(d)]
for i in range(window, x_len)])
"""建模"""
model = Sequential()
model.add(LSTM(50, input_shape=(window, d), return_sequences=True))
model.add(LSTM(100))
model.add(Dense(d))
model.compile('adam', 'mse')
model.fit(X, Y, batch_size=100, epochs=10, verbose=2)
"""预测"""
pred_len = 200
for start in (0, 333, 666, 999):
x_pred = np.linspace(np.pi * (window + start) / 100,
np.pi * (window + start + pred_len) / 100,
pred_len, endpoint=False)
y_pred = []
X_pred = X[start]
for i in range(pred_len):
Y_pred = model.predict(X_pred.reshape(1, window, d))
y_pred.append(Y_pred[0][0])
X_pred = np.concatenate((X_pred, Y_pred))[1:]
mp.scatter(x_pred[0], y_pred[0], c='r', s=9)
mp.plot(x_pred, y_pred, 'r')
mp.plot(x, y[:, 0], 'y', linewidth=4, alpha=.3)
mp.show()