循环神经网络天气预测
python代码
import pandas as pd
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,GRU, Dropout
import matplotlib.pyplot as plt
def generator(data, lookback, delay, min_index, max_index,
shuffle=False, batch_size=128, step=6):
"""生成时间序列样本及其目标的生成器,要求传入一个二维的浮点型数组,
返回指定范围内的样本和标签"""
if max_index is None:
max_index = len(data) - delay - 1
i = min_index + lookback
while 1:
if shuffle:
rows = np.random.randint(min_index + lookback, max_index, size=batch_size)
else:
if i + batch_size >= max_index:
i = min_index + lookback
rows = np.arange(i, min(i + batch_size, max_index))
i += len(rows)
samples = np.zeros((len(rows), lookback // step, data.shape[-1]))
targets = np.zeros((len(rows),))
for j, row in enumerate(rows):
indices = range(rows[j] - lookback, rows[j], step)
samples[j] = data[indices]
targets[j] = data[rows[j] + delay][1]
yield samples, targets
np.set_printoptions(suppress=True)
df = pd.read_csv("D:/Desktop/jena_climate_2009_2016.csv")
a1 = df.iloc[:, 1:].to_numpy() # shape=(420451, 14) -1584
avg = np.mean(a1, axis=0)
std = np.std(a1, axis=0)
a1 = (a1 - avg) / std
g1 = generator(a1, 720, 144, 0, 200000, True, 128, 6)
g2 = generator(a1, 720, 144, 200001, 300000, True, 128, 6)
model = Sequential()
model.add(GRU(32, input_shape=(720//6,14)))
model.add(Dropout(0.5))
model.add(Dense(units=1))
model.compile(optimizer="rmsprop", loss="mse", metrics=["mae"])
# model.summary()
history = model.fit_generator(generator=g1, steps_per_epoch=(200000 - 0 - 144)// 128, epochs=10,
validation_data=g2, validation_steps=(300000 - 200001 - 144)// 128) # 128 * 500
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
mae = history.history['mae']
val_mae = history.history['val_mae']
epochs = range(1, len(mae)+1)
plt.plot(epochs, mae, label='训练精度', c = 'r')
plt.plot(epochs, val_mae, label='验证精度', c = 'b')
plt.xlabel('epochs')
plt.ylabel('mae')
plt.title('author:peiyuanman')
plt.legend()
plt.show()
文章出处登录后可见!
已经登录?立即刷新