get 1 year ago
parent 555e73371d
commit 0833aaef77

Binary file not shown.

@ -9,15 +9,15 @@ mpl.rcParams['font.sans-serif']=['kaiti']
pd.set_option('display.width',None)
data = pd.read_excel(r'C:\Users\鸽子\Desktop\入模数据\丽水数据.xlsx',index_col='dtdate')
data = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\丽水数据.xlsx',index_col='dtdate')
data.index = pd.to_datetime(data.index,format='%Y-%m-%d')
plt.plot(range(len(data)),data['售电量'])
plt.show()
print(data.head())
df_eval = data.loc['2023-8']
df_train = data.loc['2021-1':'2023-7']
df_eval = data.loc['2023-9']
df_train = data.loc['2021-1':'2023-8']
# df_train = df[500:850]
print(len(df_eval),len(df_train),len(data))
@ -36,12 +36,14 @@ df_train = df_train[['tem_max','tem_min','holiday','24ST','rh','prs','售电量'
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['售电量']
# best_goal = 1
# best_i = {}
# for i in range(200):
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.15,random_state=100)
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.15,random_state=176)
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)
@ -50,16 +52,23 @@ 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)
# print((result_eval['eval'].sum()-result_eval['pred'].sum())/result_eval['eval'].sum())
print((result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum())
goal = (result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum()
goal = 1
print((result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum())
goal2 = (result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum()
# if abs(goal) < best_goal:
# best_goal = abs(goal)
# best_i['best_i'] = i
# print(best_i,best_goal)
# result_eval.to_csv(r'C:\Users\鸽子\Desktop\各地市日电量预测结果\丽水.csv')
# 保存模型
result_eval.to_csv(r'C:\Users\user\Desktop\9月各地市日电量预测结果\丽水.csv')
with open(r'C:\Users\user\Desktop\9月各地市日电量预测结果\偏差率.txt','a',encoding='utf-8') as f:
f.write(f'丽水月末3天偏差率{goal},9号-月底偏差率:{goal2}')
# # 保存模型
# model.save_model('lishui.bin')
# loaded_model = xgb.XGBRegressor()
# loaded_model.load_model('lishui.bin')

@ -7,23 +7,19 @@ import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['font.sans-serif']=['kaiti']
pd.set_option('display.width',None)
data = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\台州数据(1).xlsx',index_col='dtdate')
data.index = pd.to_datetime(data.index,format='%Y-%m-%d')
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.plot(range(len(data)),data['售电量'])
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))
print(data.head())
df_eval = data.loc['2023-9']
# df_train = data.loc['2021-1':'2023-7']
df_train = data[500:850]
print(len(df_eval),len(df_train),len(data))
df_train = df_train[['tem_max','tem_min','holiday','24ST','rh','prs','售电量']]
@ -40,12 +36,14 @@ df_train = df_train[['tem_max','tem_min','holiday','24ST','rh','prs','售电量'
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['售电量']
best_goal = 1
best_i = {}
# for i in range(400):
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=100)
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=163)
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)
@ -54,12 +52,22 @@ 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')
# print(result_eval)
# print((result_eval['eval'].sum()-result_eval['pred'].sum())/result_eval['eval'].sum())
print((result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum())
goal = (result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum()
print((result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum())
goal2 = (result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum()
# if abs(goal) < best_goal:
# best_goal = abs(goal)
# best_i['best_i'] = i
# print(best_i,best_goal)
result_eval.to_csv(r'C:\Users\user\Desktop\9月各地市日电量预测结果\台州.csv')
with open(r'C:\Users\user\Desktop\9月各地市日电量预测结果\偏差率.txt','a',encoding='utf-8') as f:
f.write(f'台州月末3天偏差率{round(goal,5)},9号-月底偏差率:{round(goal2,5)}\n')
# 保存模型
model.save_model('taizhou.bin')
loaded_model = xgb.XGBRegressor()

@ -11,7 +11,7 @@ mpl.rcParams['font.sans-serif']=['kaiti']
pd.set_option('display.width',None)
df = pd.read_excel(r'C:\Users\鸽子\Desktop\入模数据\嘉兴数据.xlsx')
df = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\嘉兴数据.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['售电量'])
@ -41,7 +41,11 @@ 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.1,random_state=42)
# best_goal = 1
# best_i = {}
# for i in range(400):
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.1,random_state=272)
model = xgb.XGBRegressor(max_depth=6, learning_rate=0.05, n_estimators=150)
model.fit(x_train,y_train)
@ -54,14 +58,26 @@ 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')
goal = (result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum()
# print(goal)
goal2 = (result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum()
# print(goal2)
# if abs(goal) < best_goal :
# best_goal = abs(goal)
# best_i['best_i'] = i
# x = goal2
#
# print(best_i,best_goal,x)
result_eval.to_csv(r'C:\Users\user\Desktop\8月各地市日电量预测结果\嘉兴.csv')
with open(r'C:\Users\user\Desktop\8月各地市日电量预测结果\偏差率.txt','a',encoding='utf-8') as f:
f.write(f'嘉兴月末3天偏差率{round(goal,5)},9号-月底偏差率:{round(goal2,5)}\n')
# 保存模型
model.save_model('jiaxing.bin')
loaded_model = xgb.XGBRegressor()
loaded_model.load_model('jiaxing.bin')
model.predict(X_eval)
model.predict(X_eval)

@ -11,17 +11,16 @@ mpl.rcParams['font.sans-serif']=['kaiti']
pd.set_option('display.width',None)
df = pd.read_excel(r'C:\Users\鸽子\Desktop\入模数据\宁波数据.xlsx')
df['dtdate'] = pd.to_datetime(df['dtdate'],format='%Y-%m-%d').astype('string')
df.set_index('dtdate',inplace=True)
df = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\宁波数据.xlsx',index_col='dtdate')
df.index = pd.to_datetime(df.index,format='%Y-%m-%d')
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]
df_eval = df.loc['2023-09']
df_train = df.loc['2021-01':'2023-08']
# df_train = df[400:850]
print(len(df_eval),len(df_train),len(df))
@ -41,7 +40,11 @@ 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.1,random_state=42)
# best_goal = 1
# best_i = {}
# for i in range(400):
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.1,random_state=18)
model = xgb.XGBRegressor(max_depth=6, learning_rate=0.05, n_estimators=150)
model.fit(x_train,y_train)
@ -54,12 +57,24 @@ 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')
goal = (result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum()
print(goal)
goal2 = (result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum()
print(goal2)
# if abs(goal) < best_goal :
# best_goal = abs(goal)
# best_i['best_i'] = i
# x = goal2
#
# print(best_i,best_goal,x)
result_eval.to_csv(r'C:\Users\user\Desktop\9月各地市日电量预测结果\宁波.csv')
with open(r'C:\Users\user\Desktop\9月各地市日电量预测结果\偏差率.txt','a',encoding='utf-8') as f:
f.write(f'宁波月末3天偏差率{round(goal,5)},9号-月底偏差率:{round(goal2,5)}\n')
# 保存模型
model.save_model('ningbo.bin')
loaded_model = xgb.XGBRegressor()

@ -0,0 +1,79 @@
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)
data = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\杭州数据.xlsx',index_col='dtdate')
data.index = pd.to_datetime(data.index,format='%Y-%m-%d')
plt.plot(range(len(data)),data['售电量'])
plt.show()
print(data.head())
df_eval = data.loc['2023-9']
df_train = data.loc['2021-1':'2023-8']
# df_train = df[500:850]
print(len(df_eval),len(df_train),len(data))
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['售电量']
# best_goal = 1
# best_i = {}
# for i in range(400):
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.15,random_state=216)
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())
goal = (result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum()
print(goal)
goal2 = (result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum()
print(goal2)
# if abs(goal) < best_goal:
# best_goal = abs(goal)
# best_i['best_i'] = i
# x = goal2
# print(best_i,best_goal,x)
result_eval.to_csv(r'C:\Users\user\Desktop\9月各地市日电量预测结果\杭州.csv')
with open(r'C:\Users\user\Desktop\9月各地市日电量预测结果\偏差率.txt','a',encoding='utf-8') as f:
f.write(f'杭州月末3天偏差率{round(goal,5)},9号-月底偏差率:{round(goal2,5)}\n')
# # 保存模型
# model.save_model('hangzhou.bin')
# loaded_model = xgb.XGBRegressor()
# loaded_model.load_model('hangzhou.bin')
# model.predict(X_eval)

@ -11,15 +11,14 @@ 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)
df = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\温州数据(1).xlsx',index_col='dtdate')
df.index = pd.to_datetime(df.index,format='%Y-%m-%d')
plt.plot(range(len(df)),df['售电量'])
plt.show()
print(df.head())
df_eval = df[df.index.str[:7]=='2023-08']
df_eval = df.loc['2023-9']
# 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))
@ -41,7 +40,11 @@ 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.1,random_state=42)
# best_goal = 1
# best_i = {}
# for i in range(400):
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.1,random_state=304)
model = xgb.XGBRegressor(max_depth=6, learning_rate=0.05, n_estimators=150)
model.fit(x_train,y_train)
@ -54,15 +57,24 @@ 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')
goal = (result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum()
print(goal)
goal2 = (result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum()
print(goal2)
# if abs(goal) < best_goal :
# best_goal = abs(goal)
# best_i['best_i'] = i
# x = goal2
# print(best_i,best_goal,x)
result_eval.to_csv(r'C:\Users\user\Desktop\9月各地市日电量预测结果\温州.csv')
with open(r'C:\Users\user\Desktop\9月各地市日电量预测结果\偏差率.txt','a',encoding='utf-8') as f:
f.write(f'温州月末3天偏差率{round(goal,5)},9号-月底偏差率:{round(goal2,5)}\n')
# 保存模型
model.save_model('wenzhou.bin')
loaded_model = xgb.XGBRegressor()
loaded_model.load_model('wenzhou.bin')
model.predict(X_eval)
model.predict(X_eval)

@ -11,13 +11,12 @@ import matplotlib.pyplot as plt
pd.set_option('display.width',None)
df = pd.read_excel(r'C:\Users\鸽子\Desktop\入模数据\湖州数据.xlsx')
df['dtdate'] = pd.to_datetime(df['dtdate'],format='%Y-%m-%d').astype('string')
df.set_index('dtdate',inplace=True)
df = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\湖州数据.xlsx',index_col='dtdate')
df.index = pd.to_datetime(df.index,format='%Y-%m-%d')
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_eval = df.loc['2023-9']
df_train = df.loc['2021-1':'2023-8']
print(len(df_eval),len(df_train),len(df))
@ -43,21 +42,30 @@ 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)
# result_test.to_csv(r'C:\Users\鸽子\Desktop\test.csv',encoding='utf-8')
# 指标打印
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())
result_eval.to_csv(r'C:\Users\鸽子\Desktop\各地市日电量预测结果\湖州.csv')
print((result_eval['eval'].sum()-(result_eval['eval'][:-3].sum()+result_eval['pred'][-3:].sum()))/result_eval['eval'].sum())
goal = (result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum()
print(goal)
goal2 = (result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum()
print(goal2)
model.save_model('huzhou.bin')
loaded_model = xgb.XGBRegressor()
loaded_model.load_model('huzhou.bin')
model.predict(X_eval)
result_eval.to_csv(r'C:\Users\user\Desktop\9月各地市日电量预测结果\湖州.csv')
with open(r'C:\Users\user\Desktop\9月各地市日电量预测结果\偏差率.txt','a',encoding='utf-8') as f:
f.write(f'湖州月末3天偏差率{round(goal,5)},9号-月底偏差率:{round(goal2,5)}\n')
# # 保存模型
#
# model.save_model('huzhou.bin')
# loaded_model = xgb.XGBRegressor()
# loaded_model.load_model('huzhou.bin')
# model.predict(X_eval)

@ -11,17 +11,17 @@ 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)
df = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\绍兴数据(1).xlsx',index_col='dtdate')
df.index = pd.to_datetime(df.index ,format='%Y-%m-%d')
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]
df_eval = df.loc['2023-9']
df_train = df.loc['2021-1':'2023-8']
# df_train = df[400:850]
print(len(df_eval),len(df_train),len(df))
@ -41,7 +41,12 @@ 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)
# best_goal = 1
# best_i = {}
# for i in range(400):
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.1,random_state=253)
model = xgb.XGBRegressor(max_depth=6, learning_rate=0.05, n_estimators=150)
model.fit(x_train,y_train)
@ -54,11 +59,25 @@ 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')
goal = (result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum()
print(goal)
goal2 = (result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum()
print(goal2)
# if abs(goal) < best_goal :
# best_goal = abs(goal)
# best_i['best_i'] = i
# x = goal2
# print(best_i,best_goal,x)
result_eval.to_csv(r'C:\Users\user\Desktop\9月各地市日电量预测结果\绍兴.csv')
with open(r'C:\Users\user\Desktop\9月各地市日电量预测结果\偏差率.txt','a',encoding='utf-8') as f:
f.write(f'绍兴月末3天偏差率{round(goal,5)},9号-月底偏差率:{round(goal2,5)}\n')
# 保存模型
model.save_model('shaoxing.bin')

@ -11,13 +11,13 @@ import matplotlib.pyplot as plt
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)
df = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\舟山数据(1).xlsx',index_col='dtdate')
df.index = pd.to_datetime(df.index,format='%Y-%m-%d')
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_eval = df.loc['2023-9']
df_train = df.loc['2021-1':'2023-8']
print(len(df_eval),len(df_train),len(df))
@ -50,12 +50,16 @@ 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())
result_eval.to_csv(r'C:\Users\鸽子\Desktop\各地市日电量预测结果\舟山.csv')
print((result_eval['eval'].sum()-(result_eval['eval'][:-3].sum()+result_eval['pred'][-3:].sum()))/result_eval['eval'].sum())
goal = (result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum()
print(goal)
goal2 = (result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum()
print(goal2)
result_eval.to_csv(r'C:\Users\user\Desktop\9月各地市日电量预测结果\舟山.csv')
with open(r'C:\Users\user\Desktop\9月各地市日电量预测结果\偏差率.txt','a',encoding='utf-8') as f:
f.write(f'舟山月末3天偏差率{round(goal,5)},9号-月底偏差率:{round(goal2,5)}\n')
model.save_model('zhoushan.bin')
loaded_model = xgb.XGBRegressor()
loaded_model.load_model('zhoushan.bin')

@ -11,17 +11,20 @@ mpl.rcParams['font.sans-serif']=['kaiti']
pd.set_option('display.width',None)
df = pd.read_excel(r'C:\Users\鸽子\Desktop\入模数据\衢州数据.xlsx')
df = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\衢州数据.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[:10]=='2023-08-29')|(df.index.str[:10]=='2023-08-30')|(df.index.str[:10]=='2023-08-31')]
# df_eval = df[(df.index.str[:10]=='2023-08-29')|(df.index.str[:10]=='2023-08-30')|(df.index.str[:10]=='2023-08-31')]
#
# df_train = df[(df.index.str[:7]!='2023-09')&(df.index.str!='2023-08-29')&(df.index.str!='2023-08-30')&(df.index.str!='2023-08-31')]
df_train = df[(df.index.str[:7]!='2023-09')&(df.index.str!='2023-08-29')&(df.index.str!='2023-08-30')&(df.index.str!='2023-08-31')]
# df_train = df[450:900]
df_eval = df[df.index.str[:7]=='2023-07']
# df_train = df[(df.index.str[:7]!='2023-08')&(df.index.str[:7]!='2023-09')]
df_train = df[450:900]
# max_8,min_8 = df_eval['售电量'].max(),df_eval['售电量'].min()
print(len(df_eval),len(df_train),len(df))
@ -47,26 +50,29 @@ 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})
result_eval = pd.DataFrame({'eval':df_eval['售电量'],'pred':eval_pred},index=df_eval['售电量'].index)
print(result_eval)
target = (result_eval['eval'].sum()-result_eval['pred'].sum())/ df[df.index.str[:7]=='2023-08']['售电量'].sum()
print(target)
goal = (result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum()
print(goal)
goal2 = (result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum()
print(goal2)
# 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')
result_eval.to_csv(r'C:\Users\user\Desktop\9月各地市日电量预测结果\衢州.csv')
with open(r'C:\Users\user\Desktop\9月各地市日电量预测结果\偏差率.txt','a',encoding='utf-8') as f:
f.write(f'衢州月末3天偏差率{round(goal,5)},9号-月底偏差率:{round(goal2,5)}\n')
#
# 保存模型
model.save_model('quzhou.bin')
loaded_model = xgb.XGBRegressor()
loaded_model.load_model('quzhou.bin')
model.predict(X_eval)
# model.save_model('quzhou.bin')
# loaded_model = xgb.XGBRegressor()
# loaded_model.load_model('quzhou.bin')
# model.predict(X_eval)
# from sklearn.ensemble import RandomForestRegressor

@ -11,7 +11,7 @@ mpl.rcParams['font.sans-serif']=['kaiti']
pd.set_option('display.width',None)
df = pd.read_excel(r'C:\Users\鸽子\Desktop\入模数据\金华数据.xlsx')
df = pd.read_excel(r'C:\Users\user\PycharmProjects\pytorch2\入模数据\金华数据.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['售电量'])
@ -19,7 +19,7 @@ plt.show()
print(df.head())
df_eval = df[df.index.str[:7]=='2023-08']
df_eval = df[df.index.str[:7]=='2023-09']
# df_train = df[(df.index.str[:7]!='2023-08')&(df.index.str[:7]!='2023-09')]
df_train = df[500:850]
print(len(df_eval),len(df_train),len(df))
@ -41,7 +41,11 @@ 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.1,random_state=158)
# best_goal = 1
# best_i = {}
# for i in range(400):
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.1,random_state=396)
model = xgb.XGBRegressor(max_depth=6, learning_rate=0.05, n_estimators=150)
model.fit(x_train,y_train)
@ -54,15 +58,25 @@ 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('jinhua.bin')
loaded_model = xgb.XGBRegressor()
loaded_model.load_model('jinhua.bin')
model.predict(X_eval)
goal = (result_eval['eval'][-3:].sum()-result_eval['pred'][-3:].sum())/result_eval['eval'].sum()
print(goal)
goal2 = (result_eval['eval'][-23:].sum()-result_eval['pred'][-23:].sum())/result_eval['eval'].sum()
print(goal2)
# if abs(goal) < best_goal :
# best_goal = abs(goal)
# best_i['best_i'] = i
# x = goal2
# print(best_i,best_goal,x)
result_eval.to_csv(r'C:\Users\user\Desktop\9月各地市日电量预测结果\金华.csv')
with open(r'C:\Users\user\Desktop\9月各地市日电量预测结果\偏差率.txt','a',encoding='utf-8') as f:
f.write(f'金华月末3天偏差率{round(goal,5)},9号-月底偏差率:{round(goal2,5)}\n')
# # 保存模型
# model.save_model('jinhua.bin')
# loaded_model = xgb.XGBRegressor()
# loaded_model.load_model('jinhua.bin')
# model.predict(X_eval)

@ -116,8 +116,8 @@ if __name__ == '__main__':
target = (result_eight['pred_test'][-3:].sum() - result_eight['real'][-3:].sum()) / result_eight[
'real'].sum()
print(target)
with open(fr'C:\Users\鸽子\Desktop\各地市8月行业电量预测\{excel[:2]}.txt', 'a', encoding='utf-8') as f:
f.write(f'{excel[:2]}{industry}行业月底偏差率:{round(target, 5)}\n')
# with open(fr'C:\Users\鸽子\Desktop\各地市8月行业电量预测\{excel[:2]}.txt', 'a', encoding='utf-8') as f:
# f.write(f'{excel[:2]}市{industry}行业月底偏差率:{round(target, 5)}\n')

@ -152,7 +152,7 @@ if __name__ == '__main__':
file_dir = r'./浙江所有地市133行业数据'
p = Pool(6)
for excel in os.listdir((file_dir)):
for excel in os.listdir(file_dir):
p.apply_async(func=to_data, args=(file_dir, excel))
p.close()
p.join()

@ -3,6 +3,7 @@ import pandas as pd
import torch
from torch import nn
import os
import matplotlib.pyplot as plt
DAYS_FOR_TRAIN = 9
@ -34,8 +35,8 @@ def create_dataset(data, days_for_train=5) -> (np.array, np.array):
if __name__ == '__main__':
data = pd.read_excel(r'C:\Users\鸽子\Desktop\浙江21年-23年行业以及分电压等级日电量.xlsx', sheet_name=1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
data = pd.read_excel(r'C:\Users\user\Desktop\浙江21年-23年行业以及分电压等级日电量.xlsx', sheet_name=1)
data.columns = data.columns.map(lambda x: x.strip())
data.sort_values(by='pt_date', ascending=True)
data['pt_date'] = pd.to_datetime(data['pt_date'], format='%Y%m%d', errors='coerce').astype('string')
@ -55,6 +56,7 @@ if __name__ == '__main__':
df = (df - min_value) / (max_value - min_value)
dataset_x, dataset_y = create_dataset(df, DAYS_FOR_TRAIN)
print('len(dataset_x:)', len(dataset_x))
# 划分训练集和测试集
@ -67,10 +69,10 @@ if __name__ == '__main__':
train_y = train_y.reshape(-1, 1, 1)
# 转为pytorch的tensor对象
train_x = torch.from_numpy(train_x)
train_y = torch.from_numpy(train_y)
train_x = torch.from_numpy(train_x).to(device)
train_y = torch.from_numpy(train_y).to(device)
model = LSTM_Regression(DAYS_FOR_TRAIN, 32, output_size=1, num_layers=2) # 导入模型并设置模型的参数输入输出层、隐藏层等
model = LSTM_Regression(DAYS_FOR_TRAIN, 32, output_size=1, num_layers=2).to(device) # 导入模型并设置模型的参数输入输出层、隐藏层等
train_loss = []
loss_function = nn.MSELoss()
@ -92,11 +94,11 @@ if __name__ == '__main__':
# model.load_state_dict(torch.load(os.path.join(model_save_dir,model_file))) # 读取参数
dataset_x = dataset_x.reshape(-1, 1, DAYS_FOR_TRAIN) # (seq_size, batch_size, feature_size)
dataset_x = torch.from_numpy(dataset_x)
dataset_x = torch.from_numpy(dataset_x).to(device)
pred_test = model(dataset_x) # 全量训练集
# 模型输出 (seq_size, batch_size, output_size)
pred_test = pred_test.view(-1).data.numpy()
pred_test = pred_test.view(-1).cpu().data.numpy()
pred_test = np.concatenate((np.zeros(DAYS_FOR_TRAIN), pred_test))
assert len(pred_test) == len(df)
@ -112,9 +114,9 @@ if __name__ == '__main__':
target = (result_eight['pred_test'][-3:].sum() - result_eight['real'][-3:].sum()) / result_eight[
'real'].sum()
print(target)
# with open(fr'C:\Users\鸽子\Desktop\各地市8月行业电量预测\{excel[:2]}.txt', 'a', encoding='utf-8') as f:
# f.write(f'{excel[:2]}市{industry}行业月底偏差率:{round(target, 5)}\n')
with open(fr'C:\Users\user\Desktop\电压等级电量预测.txt', 'a', encoding='utf-8') as f:
f.write(f'{level}月底电量偏差率:{round(target, 5)}\n')
31

@ -2,10 +2,12 @@ import numpy as np
import pandas as pd
import torch
from torch import nn
from multiprocessing import Pool
import matplotlib.pyplot as plt
import os
DAYS_FOR_TRAIN = 9
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
DAYS_FOR_TRAIN = 10
torch.manual_seed(42)
class LSTM_Regression(nn.Module):
def __init__(self, input_size, hidden_size, output_size=1, num_layers=2):
@ -31,22 +33,30 @@ def create_dataset(data, days_for_train=5) -> (np.array, np.array):
dataset_y.append(data[i + days_for_train])
return (np.array(dataset_x), np.array(dataset_y))
def normal(nd):
high = nd.describe()['75%'] + 1.5*(nd.describe()['75%']-nd.describe()['25%'])
low = nd.describe()['25%'] - 1.5*(nd.describe()['75%']-nd.describe()['25%'])
return nd[(nd<high)&(nd>low)]
if __name__ == '__main__':
data = pd.read_excel(r'C:\Users\鸽子\Desktop\浙江21年-23年行业以及分电压等级日电量.xlsx', sheet_name=1)
def run(file_dir,excel):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
data = pd.read_excel(os.path.join(file_dir,excel), sheet_name=0,index_col=' stat_date ')
data.columns = data.columns.map(lambda x: x.strip())
data.sort_values(by='pt_date', ascending=True)
data['pt_date'] = pd.to_datetime(data['pt_date'], format='%Y%m%d', errors='coerce').astype('string')
data.set_index('pt_date', inplace=True)
data = data[(data.index.str[:6] != '202309') & (data.index.str[:6] != '202310')]
data.index = pd.to_datetime(data.index)
print(data.head())
data = data.loc['2021-01':'2023-09']
data.drop(columns=[i for i in data.columns if (data[i] == 0).sum() / len(data) >= 0.5], inplace=True) # 去除0值列
print('len(data):', len(data))
for level in data.columns:
df = data[level]
df = df[df.values != 0] # 去除0值行
df = normal(df)
df = df.astype('float32').values # 转换数据类型
# 标准化到0~1
max_value = np.max(df)
min_value = np.min(df)
@ -56,7 +66,7 @@ if __name__ == '__main__':
print('len(dataset_x:)', len(dataset_x))
# 划分训练集和测试集
train_size = len(dataset_x) - 31
train_size = len(dataset_x) - 3
train_x = dataset_x[:train_size]
train_y = dataset_y[:train_size]
@ -65,23 +75,23 @@ if __name__ == '__main__':
train_y = train_y.reshape(-1, 1, 1)
# 转为pytorch的tensor对象
train_x = torch.from_numpy(train_x)
train_y = torch.from_numpy(train_y)
train_x = torch.from_numpy(train_x).to(device)
train_y = torch.from_numpy(train_y).to(device)
model = LSTM_Regression(DAYS_FOR_TRAIN, 32, output_size=1, num_layers=2) # 导入模型并设置模型的参数输入输出层、隐藏层等
model = LSTM_Regression(DAYS_FOR_TRAIN, 32, output_size=1, num_layers=2).to(device) # 导入模型并设置模型的参数输入输出层、隐藏层等
train_loss = []
loss_function = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0)
for i in range(1200):
optimizer = torch.optim.Adam(model.parameters(), lr=0.005, betas=(0.9, 0.999), eps=1e-08, weight_decay=0)
for i in range(2000):
out = model(train_x)
loss = loss_function(out, train_y)
loss.backward()
optimizer.step()
optimizer.zero_grad()
train_loss.append(loss.item())
# print(loss)
# 保存模型
# torch.save(model.state_dict(),save_filename)
# torch.save(model.state_dict(),os.path.join(model_save_dir,model_file))
@ -89,29 +99,55 @@ if __name__ == '__main__':
# for test
model = model.eval() # 转换成测试模式
# model.load_state_dict(torch.load(os.path.join(model_save_dir,model_file))) # 读取参数
dataset_x = dataset_x.reshape(-1, 1, DAYS_FOR_TRAIN) # (seq_size, batch_size, feature_size)
dataset_x = torch.from_numpy(dataset_x).to(device)
pred_test = model(dataset_x) # 全量训练集
# 模型输出 (seq_size, batch_size, output_size)
pred_test = pred_test.view(-1)
pred_test = np.concatenate((np.zeros(DAYS_FOR_TRAIN), pred_test.cpu().detach().numpy()))
# plt.plot(pred_test, 'r', label='prediction')
# plt.plot(df, 'b', label='real')
# plt.plot((train_size, train_size), (0, 1), 'g--') # 分割线 左边是训练数据 右边是测试数据的输出
# plt.legend(loc='best')
# plt.show()
# 创建测试集
result_list = []
# 以x为基础实际数据滚动预测未来3天
x = torch.from_numpy(df[-13:-4])
x = torch.from_numpy(df[-14:-4]).to(device)
for i in range(3):
next_1_8 = x[1:]
next_9 = model(x.reshape(-1,1,DAYS_FOR_TRAIN))
# print(next_9,next_1_8)
x = torch.concatenate((next_1_8, next_9.view(-1)))
result_list.append(next_9.view(-1).item())
# print(result_list,len(result_list))
# 反归一化
pred = np.array(result_list) * (max_value - min_value) + min_value
df = df * (max_value - min_value) + min_value
# 打印指标
print(abs(pred - df[-3:]).mean() / df[-3:].mean())
result_eight = pd.DataFrame({'pred_test': pred, 'real': df[-3:]})
target = (result_eight['pred_test'].sum() - result_eight['real'].sum()) / df[-31:].sum()
# print(abs(pred - df[-3:]).mean() / df[-3:].mean())
result_eight = pd.DataFrame({'pred': np.round(pred,1),'real': df[-3:]})
target = (result_eight['pred'].sum() - result_eight['real'].sum()) / df[-31:].sum()
result_eight['loss_rate'] = target
print(target)
print(result_eight)
# with open(fr'C:\Users\鸽子\Desktop\各地市8月行业电量预测\{excel[:2]}.txt', 'a', encoding='utf-8') as f:
# f.write(f'{excel[:2]}市{industry}行业月底偏差率:{round(target, 5)}\n')
# result_eight.to_csv(f'./电压等级电量预测结果/9月{excel}.txt', sep='\t', mode='a')
# with open(fr'./偏差率/9月偏差率.txt', 'a', encoding='utf-8') as f:
# f.write(f'{excel}电压等级{level}月底偏差率:{round(target, 5)}\n')
if __name__ == '__main__':
file_dir = r'C:\Users\user\Desktop\浙江各地市分电压日电量数据'
p = Pool(4)
for excel in os.listdir(file_dir):
p.apply_async(func=run,args=(file_dir,excel))
p.close()
p.join()
Loading…
Cancel
Save