python气温预测rnn
时间: 2023-12-02 12:43:10 浏览: 503
以下是使用RNN模型进行气温预测的Python代码示例:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, SimpleRNN
# 读取数据
data = pd.read_csv('/data/jena_climate_2009_2016.csv', engine='python')
# 取出温度数据
temp = data['T (degC)'].values
# 数据标准化
mean = temp[:200000].mean()
std = temp[:200000].std()
temp = (temp - mean) / std
# 定义生成时间序列样本的函数
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 True:
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]
yield samples, targets
# 定义训练集、验证集和测试集的生成器
lookback = 1440
step = 6
delay = 144
batch_size = 128
train_gen = generator(temp, lookback=lookback, delay=delay, min_index=0, max_index=200000, shuffle=True, step=step, batch_size=batch_size)
val_gen = generator(temp, lookback=lookback, delay=delay, min_index=200001, max_index=300000, step=step, batch_size=batch_size)
test_gen = generator(temp, lookback=lookback, delay=delay, min_index=300001, max_index=None, step=step, batch_size=batch_size)
val_steps = (300000 - 200001 - lookback) // batch_size
test_steps = (len(temp) - 300001 - lookback) // batch_size
# 定义RNN模型
model = Sequential()
model.add(SimpleRNN(32, input_shape=(None, temp.shape[-1])))
model.add(Dense(1))
model.compile(optimizer='rmsprop', loss='mae')
# 训练模型
history = model.fit_generator(train_gen, steps_per_epoch=500, epochs=20, validation_data=val_gen, validation_steps=val_steps)
# 绘制损失曲线
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(loss) + 1)
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
# 在测试集上评估模型
test_loss = model.evaluate_generator(test_gen, steps=test_steps)
print('test loss:', test_loss)
# 预测未来24小时的温度
lookback = 1440
step = 6
delay = 144
batch_size = 128
test_gen = generator(temp, lookback=lookback, delay=delay, min_index=300001, max_index=None, step=step, batch_size=batch_size)
test_steps = (len(temp) - 300001 - lookback) // batch_size
preds = model.predict_generator(test_gen, steps=test_steps)
preds = preds.reshape(-1)
preds = preds * std + mean
```
阅读全文