如何通过网格搜索在一张图表中绘制多个预测?

时间:2019-06-27 07:03:05

标签: python

我正在针对我的机器学习问题进行网格搜索,并希望在一张图表中查看每个预测,以便可视化差异。

我要保存每个模型(具有不同超参数的LSTM)以及每个时期(带有“ ModelCheckpoint”)。现在,我可以只显示一个模型的预测,但是我想在一个图表中查看每个模型。希望您能帮助我,谢谢。

主要代码:

path = 'model_1.h5'

from keras.models import load_model
model = load_model(path)
start = 60*0
n_minutes = 60*1
ts_offset = (5+5) #5min lookback + 5min prediction
pred = own_function_to_get_prediction(model, scaler, test_x, test_y, n_start_minutes=start, n_mintes=start+n_minutes-ts_offset)

plt.figure(figsize=(16,4))
for p in pred['period'].unique():
    plt.plot(pred['Predicted'][pred['period']==p])
plt.plot(pred['Actual'])
plt.show()

附加代码:

def own_function_to_get_prediction(model, scaler, test_x, test_y, n_start_minutes=0, n_mintes=60*4):
    '''
    n_start_minutes: Starting point of set.
    n_minutes: minutes to be predicted.
    '''
    n_samples = int(n_mintes*60/3)
    n_start = int(n_start_minutes*60/3)
    step = test_y.shape[1]
    res = pd.DataFrame()
    #print((n_start, n_samples, step))
    for i in range(n_start, n_samples, step):
        #print('Sample',i)
        test_x_rescaled, test_y_rescaled, yhat_rescaled, rmse = plot_prediction(model, scaler, test_x, test_y, sample=i)
        time = test_x_rescaled[-1][1]
        hour = int(time)
        minute = int((time % hour) * 60)
        second = int(((time % hour) * 60 - minute) * 60)
        start_time = pd.to_datetime(datetime.datetime(2019, 1, 1, hour, minute, second))
        #plt.plot(test_y_rescaled)
        #plt.plot(yhat_rescaled)
        #plt.show()
        #print(start_time)
        for ts in range(len(test_y_rescaled)):
            res.loc[i+ts, 'date_time'] = start_time + pd.DateOffset(seconds=3*(ts))
            #print(start_time + pd.DateOffset(seconds=3*(i+ts)))
            res.loc[i+ts, 'Actual'] = test_y_rescaled[ts]
            res.loc[i+ts, 'Predicted'] = yhat_rescaled[ts]
            res.loc[i+ts, 'period'] = i
    res.index = res['date_time']
    del res['date_time']
    return res

def plot_prediction(model, scaler, test_x, test_y, sample=0):
    test_x = np.array(test_x[sample:(sample+1)])
    test_y = np.array(test_y[sample:(sample+1)])
    yhat = np.transpose(model.predict(test_x))
    yhat = np.append(yhat, np.empty([test_y.shape[1],test_x.shape[2]-1+1]), 1)
    yhat = scaler.inverse_transform(yhat)[:,0]
    test_y = np.append(test_y.reshape(test_y.shape[1],1), np.empty([test_y.shape[1],test_x.shape[2]-1+1]), 1)
    test_y = scaler.inverse_transform(test_y)[:,0]
    rmse = np.sqrt(mean_squared_error(yhat, test_y))
    test_x = scaler.inverse_transform(np.append(test_x[0], np.empty([test_x.shape[1],1]), 1))
    return test_x, test_y, yhat, rmse

0 个答案:

没有答案