思考:
1.No 行数 2.year 年 3.month 月 4.day 日 5.hour 小时 6.pm2.5 PM2.5浓度 7.DEWP 露点 8.TEMP 温度 9.PRES 大气压 10.cbwd 风向 11.lws 风速 12.ls 累积雪量 13.lr 累积雨量
1. 数据清洗
导入包
#导入用到的包
import pandas as pd
from datetime import datetime
from matplotlib import pyplot
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM, Dropout
from numpy import concatenate
from math import sqrt
from keras.callbacks import ReduceLROnPlateau
数据清洗(详细注释):
def parse(x):
return datetime.strptime(x, '%Y %m %d %H')
def read_raw():
dataset = pd.read_csv('raw.csv', parse_dates=[['year', 'month', 'day', 'hour']], index_col=0, date_parser=parse) #将日期合并
dataset.drop('No', axis=1, inplace=True) #删除no列(无意义)
# manually specify column names
dataset.columns = ['pollution', 'dew', 'temp', 'press', 'wnd_dir', 'wnd_spd', 'snow', 'rain'] #给每列换个好理解的名
dataset.index.name = 'date' #行的索引名为name,解析得到的日期格式列会作为DataFrame的第一列。则此时会以新生成的time_date列而不是name作为Index。因此保险的方法是指定列名,如index_col = 'name'
# mark all NA values with 0
dataset['pollution'].fillna(0, inplace=True)
# drop the first 24 hours
dataset = dataset[24:] #删除第一天的数据,取列表24行之后的数据
# summarize first 5 rows
print(dataset.head(5))
# save to file
dataset.to_csv('pollution.csv')
2.对每列数据进行绘图观测(5年数据),除了日期。
绘图代码:
def drow_pollution():
dataset = pd.read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values #取文件中的值
# specify columns to plot
groups = [0, 1, 2, 3, 5, 6, 7]
i = 1
# plot each column
pyplot.figure(figsize=(10, 10))
for group in groups:
pyplot.subplot(len(groups), 1, i)
pyplot.plot(values[:, group])
pyplot.title(dataset.columns[group], y=0.5, loc='right')
i += 1
pyplot.show()
def series_to_supervised(data, n_in=5, n_out=5, dropnan=True):
# convert series to supervised learning
n_vars = 1 if type(data) is list else data.shape[1]
df = pd.DataFrame(data)
cols, names = list(), list()
# input sequence (t-n, ... t-1)
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
names += [('var%d(t-%d)' % (j + 1, i)) for j in range(n_vars)]
# forecast sequence (t, t+1, ... t+n)
for i in range(0, n_out):
cols.append(df.shift(-i))
if i == 0:
names += [('var%d(t)' % (j + 1)) for j in range(n_vars)]
else:
names += [('var%d(t+%d)' % (j + 1, i)) for j in range(n_vars)]
# put it all together
agg = pd.concat(cols, axis=1)
agg.columns = names
# drop rows with NaN values
if dropnan:
agg.dropna(inplace=True)
# normalize features
return agg #shape:(43791, 64)
提取需要的输入:
def cs_to_sl():
# load dataset
dataset = pd.read_csv('pollution.csv', header=0, index_col=0)
values = dataset.values
# integer encode direction
encoder = LabelEncoder() #先构造encoder,通过fit函数传入需要编码的数据,在内部生成对应的key-value,然后encoder 用于需要转化的数据,用transform函数
values[:, 4] = encoder.fit_transform(values[:, 4]) #先将object对象转化为硬编码
# ensure all data is float
values = values.astype('float32')
# frame as supervised learning
reframed = series_to_supervised(values, 5, 5)
# drop columns we don't want to predict 删掉我们不想要的输出,留下40,48,56,64,72(5天的数据)
reframed.drop(reframed.columns[[41,42,43,44,45,46,47,49,50,51,52,53,54,55,57,58,59,60,61,62,63,65,66,67,68,69,70,71,73, 74, 75, 76, 77, 78, 79]], axis=1, inplace=True)
print(reframed.head())
return reframed #reframed.shape:(43791, 45)
def train_test(reframed):
# split into train and test sets
values = reframed.values
scaler11 = MinMaxScaler(feature_range=(0, 1))
values = scaler11.fit_transform(values)
n_train_hours = 365 * 24*3 #
train = values[:n_train_hours, :]
test = values[n_train_hours:, :]
# split into input and outputs
train_X, train_y = train[:, :-5],train[:, -5:]
test_X, test_y = test[:, :-5], test[:, -5:]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1])) #train_X开始2维,(26280,40)变成三维(26280, 1, 40)train_y:(26280,5)
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)
return train_X, train_y, test_X, test_y, scaler11
def fit_network(train_X, train_y, test_X, test_y, scaler):
model = Sequential()
model.add(LSTM(50, return_sequences=True,input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(Dropout(0.3))
model.add(LSTM(50,return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(50))
model.add(Dense(5))
model.compile(loss='mae', optimizer='adam')
# fit network
reduce_lr = ReduceLROnPlateau(monitor='val_loss', patience=10, mode='auto')
# model.fit返回一个对象,对象有history属性,记录训练的数据的损失
history = model.fit(train_X, train_y, epochs=100, batch_size=72, validation_data=(test_X, test_y), verbose=2,
shuffle=False, callbacks=[reduce_lr])
# plot history
pyplot.plot(history.history['loss'], label='train1')
pyplot.plot(history.history['val_loss'], label='test2345')
pyplot.legend()
pyplot.show()
# make a prediction
yhat = model.predict(test_X)
test_X = test_X.reshape((test_X.shape[0], test_X.shape[2]))
inv_yhat = concatenate((test_X,yhat), axis=1)
# invert scaling for forecast
#inv_yhat = concatenate((yhat, test_X[:, 5:]), axis=1)
inv_yhat = scaler.inverse_transform(inv_yhat)
print(type(inv_yhat))
print(inv_yhat[-1])
print(inv_yhat[-1][-5:])
print(inv_yhat[-1:,-5:]) #多一个括号
inv_yhat = inv_yhat[:, -5:]
print(inv_yhat[-1])
print(inv_yhat[-1:])
# invert scaling for actual
inv1_yhat1 = concatenate((test_X,test_y), axis=1)
inv_y = scaler.inverse_transform(inv1_yhat1)
inv_y = inv_y[:, -5:]
# calculate RMSE
rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
print('Test RMSE: %.3f' % rmse)
return inv_yhat, inv_y
参考:
1.使用Keras进行LSTM实战