该段代码主要使用支持向量回归(SVR)模型进行时间序列预测。首先将数据进行划分,使用create_dateback函数将原始数据转换成训练数据和测试数据。然后使用GridSearchCV函数对SVR模型进行调参,对'gamma'和'C'进行网格搜索,找到最优参数。接着使用最优参数构建SVR模型,对测试数据进行预测,并将预测结果进行反归一化处理,最后评估预测结果的准确性。如果'draw'参数为True,则绘制预测结果的图像。

代码分析:

  1. 数据划分:

    • 使用'create_dateback'函数将原始数据'data'转换为训练数据'trainX'、'trainY'和测试数据'next_trainX'。
    • 将训练数据'trainX' reshape 成二维矩阵。
    • 将训练数据和测试数据分别划分为'x_train'、'x_test'和'y_train'、'y_test'。
  2. 网格搜索调参:

    • 使用'GridSearchCV'函数进行网格搜索,对'gamma'和'C'参数进行组合尝试,找到最优参数。
    • 使用'logspace'函数生成参数范围。
    • 通过循环迭代,不断调整参数范围,找到最佳参数组合。
  3. 模型训练和预测:

    • 使用最优参数构建SVR模型'clf'。
    • 使用训练数据'x_train'和'y_train'训练模型。
    • 使用测试数据'x_test'进行预测,得到'y_pred'。
  4. 结果反归一化和评估:

    • 使用'scalarY.inverse_transform'函数对预测结果'y_pred'进行反归一化。
    • 使用'evl'函数评估预测结果的准确性。
  5. 可视化结果:

    • 如果'draw'参数为True,则使用matplotlib绘制预测结果的图像。

代码片段:

def SVR_pred(data=None,gstimes=5,draw=True,ahead=1):
    # Divide the training and test set
    start = time.time()
    trainX,trainY,scalarY,next_trainX = create_dateback(data,ahead=ahead)
    trainX = trainX.reshape((trainX.shape[0], trainX.shape[1]))
    x_train,x_test = trainX[:-PERIODS],trainX[-PERIODS:]
    y_train,y_test = trainY[:-PERIODS],trainY[-PERIODS:]

    # Grid Search of K-Fold CV
    # logspace(a,b,N)Divide the interval from the a power of 10 to the b power of 10 into N parts
    C_range = np.logspace(-2, 10, 13)
    gamma_range = np.logspace(-9, 3, 13)
    best_gamma,best_C = 0,0
    for i in range(gstimes):
        param_grid = dict(gamma=gamma_range, C=C_range)
        grid = GridSearchCV(SVR(), param_grid=param_grid, cv=10)
        grid.fit(x_train, y_train)
        print('Iteration',i)
        print('Best parameters:', grid.best_params_)
        if best_gamma == grid.best_params_['gamma'] and best_C == grid.best_params_['C']: break
        best_gamma=grid.best_params_['gamma']
        best_C=grid.best_params_['C']
        gamma_range = np.append(np.linspace(best_gamma/10,best_gamma*0.9,9),np.linspace(best_gamma,best_gamma*10,10)).ravel()
        C_range = np.append(np.linspace(best_C/10,best_C*0.9,9),np.linspace(best_C,best_C*10,10)).ravel()

    # Predict
    clf = SVR(kernel='rbf', gamma=best_gamma ,C=best_C)
    clf.fit(x_train, y_train)
    y_pred = clf.predict(x_test)
    end = time.time()

    # De-normalize and Evaluate
    test_pred = scalarY.inverse_transform(y_pred.reshape(y_pred.shape[0],1))
    test_y = scalarY.inverse_transform(y_test)
    evl(test_pred, test_y)
    print('Running time: %.3fs'%(end-start))

    # Plot observation figures
    if draw:
        fig = plt.figure(figsize=(5,2))
        plt.plot(test_y)
        plt.plot(test_pred)
        plt.title('SVR forecasting result')
        #plt.savefig(FIGURE_PATH+fig_name+' LSTM forecasting result.svg', bbox_inches='tight')
        plt.show()
Python SVR 时间序列预测代码解析

原文地址: http://www.cveoy.top/t/topic/mGpD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录