You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
2.3 KiB
Python
69 lines
2.3 KiB
Python
import xgboost as xgb
|
|
import pandas as pd
|
|
import os
|
|
from sklearn.metrics import r2_score
|
|
from sklearn.model_selection import train_test_split
|
|
import matplotlib as mpl
|
|
import matplotlib.pyplot as plt
|
|
mpl.rcParams['font.sans-serif']=['kaiti']
|
|
|
|
|
|
pd.set_option('display.width',None)
|
|
|
|
|
|
df = pd.read_excel(r'C:\Users\鸽子\Desktop\入模数据\绍兴数据(1).xlsx')
|
|
df['dtdate'] = pd.to_datetime(df['dtdate'],format='%Y-%m-%d').astype('string')
|
|
df.set_index('dtdate',inplace=True)
|
|
plt.plot(range(len(df)),df['售电量'])
|
|
plt.show()
|
|
print(df.head())
|
|
|
|
|
|
df_eval = df[df.index.str[:7]=='2023-08']
|
|
# df_train = df[(df.index.str[:7]!='2023-08')&(df.index.str[:7]!='2023-09')]
|
|
df_train = df[400:850]
|
|
print(len(df_eval),len(df_train),len(df))
|
|
|
|
|
|
|
|
df_train = df_train[['tem_max','tem_min','holiday','24ST','rh','prs','售电量']]
|
|
|
|
|
|
# IQR = df['售电量'].describe()['75%'] - df['售电量'].describe()['25%']
|
|
# high = df['售电量'].describe()['75%'] + 1.5*IQR
|
|
# low = df['售电量'].describe()['25%'] - 1.5*IQR
|
|
# print('异常值数量:',len(df[(df['售电量'] >= high) | (df['售电量'] <= low)]))
|
|
#
|
|
# df_train = df_train[(df['售电量'] <= high) & (df['售电量'] >= low)]
|
|
|
|
|
|
X = df_train[['tem_max','tem_min','holiday','24ST','rh','prs']]
|
|
X_eval = df_eval[['tem_max','tem_min','holiday','24ST','rh','prs']]
|
|
y = df_train['售电量']
|
|
|
|
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
|
|
model = xgb.XGBRegressor(max_depth=6, learning_rate=0.05, n_estimators=150)
|
|
model.fit(x_train,y_train)
|
|
|
|
|
|
y_pred = model.predict(x_test)
|
|
result_test = pd.DataFrame({'test':y_test,'pred':y_pred},index=y_test.index)
|
|
|
|
# 指标打印
|
|
print(abs(y_test - y_pred).mean() / y_test.mean())
|
|
eval_pred = model.predict(X_eval)
|
|
|
|
result_eval = pd.DataFrame({'eval':df_eval['售电量'],'pred':eval_pred},index=df_eval['售电量'].index)
|
|
print(result_eval)
|
|
print((result_eval['eval'].sum()-result_eval['pred'].sum())/result_eval['eval'].sum())
|
|
print((result_eval['eval'].sum()-(result_eval['eval'][:-3].sum()+result_eval['pred'][-3:].sum()))/result_eval['eval'].sum())
|
|
|
|
result_eval.to_csv(r'C:\Users\鸽子\Desktop\各地市日电量预测结果\绍兴.csv')
|
|
|
|
# 保存模型
|
|
model.save_model('shaoxing.bin')
|
|
loaded_model = xgb.XGBRegressor()
|
|
loaded_model.load_model('shaoxing.bin')
|
|
model.predict(X_eval)
|
|
|