Keras时序生成器

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/Yellow_python/article/details/86742440

TimeseriesGenerator

import numpy as np
from keras.preprocessing.sequence import TimeseriesGenerator
y = np.array(range(5))
tg = TimeseriesGenerator(y, y, length=3, sampling_rate=1)
for i in zip(*tg[0]):
    print(*i)
"""
[0 1 2] 3
[1 2 3] 4
"""
y = np.array(range(6))
tg = TimeseriesGenerator(y, y, length=3, sampling_rate=1, stride=2)
for i in zip(*tg[0]):
    print(*i)
"""
[0 1 2] 3
[2 3 4] 5
"""
y = np.array([[i] for i in range(5)])
tg = TimeseriesGenerator(y, y, length=3, sampling_rate=1)
for i in zip(*tg[0]):
    print(*i)
"""
[[0] [1] [2]] [3]
[[1] [2] [3]] [4]
"""
y = np.array([[i] for i in range(6)])
tg = TimeseriesGenerator(y, y, length=3, sampling_rate=1, stride=2)
for i in zip(*tg[0]):
    print(*i)
"""
[[0] [1] [2]] [3]
[[2] [3] [4]] [5]
"""
y = np.array([(i, i) for i in range(5)])
tg = TimeseriesGenerator(y, y, length=3, sampling_rate=1)
for i in zip(*tg[0]):
    print(*i)
"""
[[0 0] [1 1] [2 2]] [3 3]
[[1 1] [2 2] [3 3]] [4 4]
"""

示例1:余弦曲线预测

在这里插入图片描述

RNN版

import numpy as np, matplotlib.pyplot as mp
from keras.preprocessing.sequence import TimeseriesGenerator
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).reshape(-1, 1)
window = 75  # 时序滑窗大小
batch_size = 256
tg = TimeseriesGenerator(y, y, length=window, batch_size=batch_size)
print(tg[0][0].shape)  # (256, 75, 1)
print(tg[0][1].shape)  # (256, 1)
print(tg[3][0].shape)  # (232, 75, 1)
print(tg[3][1].shape)  # (232, 1)

"""建模"""
model = Sequential()
model.add(LSTM(units=50, input_shape=(window, 1),
               return_sequences=True))  # True返回输出序列的全部
model.add(LSTM(units=100,
               return_sequences=False))  # False返回输出序列的最后一个
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')  # 均方误差(Mean Square Error)
model.fit_generator(generator=tg, epochs=30, verbose=2)

"""预测"""
pred_len = 200  # 预测序列长度
for i in range(4):
    x_pred = x[i * batch_size + window: i * batch_size + window + pred_len]
    y_pred = []  # 存放拟合序列
    X_pred = tg[i][0][0]
    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()

CNN版

import numpy as np, matplotlib.pyplot as mp
from keras.preprocessing.sequence import TimeseriesGenerator
from keras.models import Sequential
from keras.layers import Dense, Conv1D, MaxPool1D, GlobalMaxPool1D

"""配置"""
x_len = 1075
window = 75  # 时序滑窗大小
filters = 64  # 滤波器数量
kernel_size = 9  # 滤波器大小
batch_size = 256
epochs = 99

"""创建样本"""
x = np.linspace(0, np.pi * 10.75, x_len, endpoint=False)
y = np.cos(x).reshape(-1, 1)
tg = TimeseriesGenerator(y, y, length=window, batch_size=batch_size)

"""建模"""
model = Sequential()
model.add(Conv1D(filters, kernel_size, activation='relu', input_shape=(window, 1)))
model.add(MaxPool1D())
model.add(Conv1D(filters, kernel_size, activation='relu'))
model.add(GlobalMaxPool1D())  # 对于时序数据的全局最大池化
model.add(Dense(1))
# 编译、训练
model.compile('adam', 'mse')
model.fit_generator(tg, epochs=epochs, verbose=2)

"""预测"""
pred_len = 200  # 预测序列长度
for i in range(4):
    x_pred = x[i * batch_size + window: i * batch_size + window + pred_len]
    y_pred = []  # 存放拟合序列
    X_pred = tg[i][0][0]
    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()

示例2:RNN+CNN

import numpy as np, matplotlib.pyplot as mp
from keras.preprocessing.sequence import TimeseriesGenerator
from keras.models import Sequential
from keras.layers import Dense, Conv1D, MaxPool1D, GRU

"""配置"""
x_len = 1075
window = 75  # 时序滑窗大小
filters = 64  # 滤波器数量
kernel_size = 9  # 滤波器大小
units = 64  # RNN神经元数量
batch_size = 256
epochs = 50

"""创建样本"""
x = np.linspace(0, np.pi * 10.75, x_len, endpoint=False)
y = (np.cos(x) + np.cos(x * 10) * .1).reshape(-1, 1)
tg = TimeseriesGenerator(y, y, length=window, batch_size=batch_size)

"""建模"""
model = Sequential()
model.add(Conv1D(filters, kernel_size, activation='relu', input_shape=(window, 1)))
model.add(MaxPool1D())
model.add(Conv1D(filters, kernel_size, activation='relu'))
model.add(GRU(units))  # 门限循环单元网络
model.add(Dense(1))

# 编译、训练
model.compile('adam', 'mse')
model.fit_generator(tg, epochs=epochs, verbose=2)

"""预测"""
pred_len = 200  # 预测序列长度
for i in range(4):
    x_pred = x[i * batch_size + window: i * batch_size + window + pred_len]
    y_pred = []  # 存放拟合序列
    X_pred = tg[i][0][0]
    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()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Yellow_python/article/details/86742440