import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.metrics import mean_absolute_error # 平方绝对误差
由于时间的维数是一维的,因此需要创建滞后特征,选定滞后的期数
此示例中选定滞后期数为3
data = pd.read_excel()
# 2. 创建滞后特征
lookback =3 # 滞后的期数
X = [] # 输入特征矩阵
y = [] # 目标值
for i in range(lookback, len(data)):
X.append(data.iloc[i-lookback:i, 0]) # 使用前lookback期的值作为特征
y.append(data.iloc[i, 0]) # 当前期作为目标值
X = np.array(X)
y = np.array(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
在使用支持向量机算法进行预测的基础上,再采用粒子群算法优化调整参数,建立调参后的SVR模型。
# 4. 创建和训练SVR模型
import PSO_SVR
svr_model = PSO_SVR.optimize_svm(X_train, y_train, X_test, y_test)
svr_model.fit(X_train, y_train)
x_next = [data[-lookback:].values[i, 0] for i in range(len(data[-lookback:]))]
y_next = svr_model.predict([x_next])
y_pred1 = svr_model.predict(X_train)
y_pred = svr_model.predict(X_test)
y_label_pre = list(y_pred1)
for i in y_pred:
y_label_pre.append(i)
y_label_pre.append(y_next[0])
y_label_tru = list(y_train)
for i in y_test:
y_label_tru.append(i)
mse = mean_squared_error(y_test, y_pred)
print(f'均方误差:{mse}')
print("R2 = ", metrics.r2_score(y_test, y_pred)) # R2
print("MAE = ", mean_absolute_error(y_test, y_pred)) # R2
import matplotlib.pyplot as plt
plt.plot(y_label_tru, "o-k")
plt.plot(y_label_pre, "P--")
plt.xlabel('Time')
plt.ylabel('Value')
plt.legend(['Actual', 'Predicted'])
plt.title('Actual vs Predicted')
plt.grid()
plt.show()