数据预处理
该部分包含生成差分数据,归一化,数据缩放,生成监督数据集等。
将数据转换成有监督数据
from pandas import read_csv
from datetime import datetime
from pandas import DataFrame
from pandas import concat
def parser(x):
return datetime.strptime(x, '%Y/%m/%d')
series = read_csv("data_set\shampoo-sales.csv", header=0, parse_dates=[0], index_col=0, squeeze=True,
date_parser=parser)
'''
将数据转换成有监督数据
即包含input output
训练的目的就是找到训练数据input和output的关系
此处的input是t时间步的数据,output为t+1时间步的数据
具体实现就是将整体的时间数据向后滑动一格,和原始数据拼接,就是有监督的数据
'''
def timeseries_to_supervised(data, lag=1):
df = DataFrame(data)
colums = [df.shift(i) for i in range(1, lag + 1)]
colums.append(df)
df = concat(colums, axis=1)
df.fillna(0, inplace=True)
return df
X = series.values
supervised = timeseries_to_supervised(X, 1)
print(supervised.head())
原数据: 转换为监督数据后:
数据缩放
from pandas import read_csv
from pandas import datetime
from pandas import Series
from sklearn.preprocessing import MinMaxScaler
def parser(x):
return datetime.strptime(x, '%Y/%m/%d')
series = read_csv('data_set/shampoo-sales.csv', header=0, parse_dates=[0], index_col=0, squeeze=True,
date_parser=parser)
print (series.head())
X = series.values
X = X.reshape(len(X), 1)
scaler = MinMaxScaler(feature_range=(-1, 1))
scaler = scaler.fit(X)
scalered_X = scaler.transform(X)
scalered_series = Series(scalered_X[:, 0])
print (scalered_series)
inverted_X = scaler.inverse_transform(scalered_X)
inverted_series = Series(inverted_X[:, 0])
print (inverted_series.head())
搭建网络
从0开始实现深度学习网络
我们搭建网络并训练的流程为:
读取数据,如读取时间序列,图片等 数据预处理,如将其转换为监督数据,数据归一化,缩放等,划分数据集 搭建模型,设置网络层结构,设置参数,神经元个数等 编译模型,设置批次大小,损失函数,优化器等 训练模型,设置迭代次数,批次大小传入数据等 保存模型,如参数权值等 模型预测数据,使用已保存模型进行数据预测 模型评估,设置评估函数 结果分析,如通过图像。
数据读取,使用的是numpy的read_csv
def parser(x):
return datetime.strptime(x, '%Y/%m/%d')
series = read_csv('data_set/shampoo-sales.csv',
header=0, parse_dates=[0], index_col=0, squeeze=True,
date_parser=parser)
转换为差分数据,即将数据变为稳定的
def difference(dataset, interval=1):
diff = list()
for i in range(interval, len(dataset)):
value = dataset[i] - dataset[i - interval]
diff.append(value)
return Series(diff)
diff_values = difference(raw_values, 1)
转换为有监督数据,即input,output形式
def timeseries_to_supervised(data, lag=1):
df = DataFrame(data)
columns = [df.shift(i) for i in range(1, lag + 1)]
columns.append(df)
df = concat(columns, axis=1)
df.fillna(0, inplace=True)
return df
supervised = timeseries_to_supervised(diff_values, 1)
划分训练集测试集
train, test = supervised_values[0:-12], supervised_values[-12:]
数据缩放至-1到1之间
def scale(train, test):
scaler = MinMaxScaler(feature_range=(-1, 1))
scaler = scaler.fit(train)
train = train.reshape(train.shape[0], train.shape[1])
train_scaled = scaler.transform(train)
test = test.reshape(test.shape[0], test.shape[1])
test_scaled = scaler.transform(test)
return scaler, train_scaled, test_scaled
scaler, train_scaled, test_scaled = scale(train, test)
模型训练,这里批次大小设置为1,即每次训练一个数据,使用手写循环调用fit,从而没训练一次数据便完成一次权值更新
def fit_lstm(train, batch_size, nb_epoch, neurons):
X, y = train[:, 0:-1], train[:, -1]
X = X.reshape(X.shape[0], 1, X.shape[1])
model = Sequential()
model.add(LSTM(neurons, batch_input_shape=(batch_size, X.shape[1], X.shape[2]), stateful=True))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
for i in range(nb_epoch):
model.fit(X, y, epochs=1, batch_size=batch_size, verbose=0, shuffle=False)
model.reset_states()
print("当前计算次数:"+str(i))
return model
lstm_model = fit_lstm(train_scaled, 1, 1500, 1)
预测数据
train_reshaped = train_scaled[:, 0].reshape(len(train_scaled), 1, 1)
lstm_model.predict(train_reshaped, batch_size=1)
预测数据并完成性能分析
predictions = list()
for i in range(len(test_scaled)):
X, y = test_scaled[i, 0:-1], test_scaled[i, -1]
yhat = forcast_lstm(lstm_model, 1, X)
yhat = invert_scale(scaler, X, yhat)
yhat = inverse_difference(raw_values, yhat, len(test_scaled) + 1 - i)
predictions.append(yhat)
expected = raw_values[len(train) + i + 1]
print('Moth=%d, Predicted=%f, Expected=%f' % (i + 1, yhat, expected))
print(predictions)
rmse = sqrt(mean_squared_error(raw_values[-12:], predictions))
print('Test RMSE:%.3f' % rmse)
pyplot.plot(raw_values[-12:])
pyplot.plot(predictions)
pyplot.show()
|