输出预测结果

main
鸽子 1 year ago
parent 9112c8177e
commit e44baf610f

@ -15,29 +15,38 @@ df = pd.read_csv('区县400v入模数据.csv',encoding='gbk',index_col='dtdate')
df.index = pd.to_datetime(df.index)
print(df.head())
# org_name = df['org_name'].values[0]
org_name = ' 国网温岭市供电公司 '
data = df[df['org_name']==org_name]
data = data.loc[normal(data['0.4kv及以下']).index]
print(data)
X = data.drop(columns=['city_name','org_name','0.4kv及以下'])
x = X.loc['2022-1':'2023-7']
x_eval = X.loc['2023-8']
y = data['0.4kv及以下'].loc['2022-1':'2023-7']
y_eval = data['0.4kv及以下'].loc['2023-8']
plt.plot(range(len(y)),y)
plt.show()
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3,random_state=42)
model = xgb.XGBRegressor(max_depth=6,learning_rate=0.05,n_estimators=150)
model.fit(x_train,y_train)
pred = model.predict(x_test)
print(r2_score(pred,y_test))
predict = model.predict(x_eval)
result = pd.DataFrame({'real':y_eval,'pred':predict},index=y_eval.index)
print(result)
print((result['real'][-3:]-result['pred'][-3:]).sum()/result['real'].sum())
list_org = []
list_fl = []
list_sc = []
for org_name in df['org_name'].drop_duplicates():
data = df[df['org_name']==org_name]
if org_name.strip()[-4:] != '供电公司':
continue
data = data.loc[normal(data['0.4kv及以下']).index]
X = data.drop(columns=['city_name','org_name','0.4kv及以下'])
x = X.loc['2022-1':'2023-7'][:-3]
x_eval = X.loc['2023-7']
y = data['0.4kv及以下'].loc['2022-1':'2023-7'][:-3]
y_eval = data['0.4kv及以下'].loc['2023-7']
# plt.plot(range(len(y)),y)
# plt.show()
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3,random_state=42)
model = xgb.XGBRegressor(max_depth=6,learning_rate=0.05,n_estimators=150)
model.fit(x_train,y_train)
pred = model.predict(x_test)
# print(org_name)
list_org.append(org_name)
# print(r2_score(pred,y_test))
list_sc.append(r2_score(pred,y_test))
predict = model.predict(x_eval)
result = pd.DataFrame({'real':y_eval,'pred':predict},index=y_eval.index)
# print(result)
# print((result['real'][-3:]-result['pred'][-3:]).sum()/result['real'].sum())
list_fl.append((result['real'][-3:]-result['pred'][-3:]).sum()/result['real'].sum())
df = pd.DataFrame({'org':list_org,'sc':list_sc,'goal':list_fl})
print(df)
print(df['goal'].value_counts(bins=[-0.05,-0.01,-0.005,0, 0.005, 0.01, 0.02,0.05],sort=False))

@ -19,10 +19,12 @@ print(df.columns)
print(dict(zip(df.columns,[(df[x]==0).sum()/len(df) for x in df.columns])))
yc_org_list = []
list_fl = []
list_org = []
for city in df[''].drop_duplicates():
df_ct = df[df['']==city]
wb = Workbook()
wb.save(fr'C:\Users\鸽子\Desktop\9月0.4kv区县预测\{city}.xlsx')
# wb = Workbook()
# wb.save(fr'C:\Users\鸽子\Desktop\9月0.4kv区县预测\{city}.xlsx')
for org in df_ct['org_name'].drop_duplicates():
if org.strip()[-4:] != '供电公司':
continue
@ -42,12 +44,12 @@ for city in df['市'].drop_duplicates():
dd['ds'] = pd.to_datetime(dd['ds'])
# 划分数据划分为训练集和验证集预测的数据设置为未来3天
df_train = dd[(dd['ds']>='2022-01-01')&(dd['ds']<='2023-09-30')][:-3]
df_train = dd[(dd['ds']>='2022-01-01')&(dd['ds']<='2023-07-31')][:-3]
df_train = df_train.loc[normal(df_train['y']).index]
if df_train.shape[0] <= 180:
yc_org_list.append(org)
continue
df_test = dd[(dd['ds']>='2022-01-01')&(dd['ds']<='2023-09-30')][-3:]
df_test = dd[(dd['ds']>='2022-01-01')&(dd['ds']<='2023-07-31')][-3:]
# 数据的变动会受到季节、周、天的影响存在一定的规律性因此我们将这三个参数设置为True
model = Prophet(yearly_seasonality=True, weekly_seasonality=True, daily_seasonality=True)
# 采用中国的假期模式,其余参数均保持默认
@ -78,15 +80,22 @@ for city in df['市'].drop_duplicates():
df_all['偏差率'] = (df_all['y'] - df_all['yhat'])/df_all['y']
df_all.rename(columns={'y':'真实值','yhat':'预测值'},inplace=True)
df_all = df_all[['org_name','真实值','预测值','偏差率']]
list_org.append(org)
try:
result = df_all.loc['2023-9']
result = df_all.loc['2023-7']
result['goal'] = (result['真实值'] - result['预测值'])[-3:].sum()/result['真实值'].sum()
with pd.ExcelWriter(fr'C:\Users\鸽子\Desktop\9月0.4kv区县预测\{city}.xlsx',mode='a',engine='openpyxl',if_sheet_exists='replace') as writer:
result.to_excel(writer,sheet_name=f'{org}')
list_fl.append((result['真实值'] - result['预测值'])[-3:].sum()/result['真实值'].sum())
# with pd.ExcelWriter(fr'C:\Users\鸽子\Desktop\9月0.4kv区县预测\{city}.xlsx',mode='a',engine='openpyxl',if_sheet_exists='replace') as writer:
# result.to_excel(writer,sheet_name=f'{org}')
except:
yc_org_list.append(org)
print(yc_org_list)
df = pd.DataFrame({'org':list_org,'goal':list_fl})
print(df)
print(df['goal'].value_counts(bins=[-0.05,-0.01,-0.005,0, 0.005, 0.01, 0.02,0.05],sort=False))
# print(yc_org_list)
# # 创建一个ExcelWriter对象
# with pd.ExcelWriter(r'C:\Users\鸽子\Desktop\output.xlsx',mode='a',if_sheet_exists='replace') as writer:
# # 将不同的子文件写入同一个Excel文件的不同工作表

@ -165,6 +165,7 @@ for excel in os.listdir(file_dir):
df_city.drop(columns=[i for i in df_city.columns if (df_city[i] == 0).sum() / len(df_city) >= 0.5], inplace=True)
city = df_city['地市'].iloc[0]
result_dict = {}
for level in df_city.columns[1:]:
x, y = create_dataset(df_city[level], 10)

@ -0,0 +1,9 @@
from prophet import Prophet
import pandas as pd
import os
import datetime
file_dir = './浙江各地市行业电量数据'
city = os.listdir(file_dir)[0]
df_city = pd.read_excel(os.path.join(file_dir,city))
print(df_city.columns)
Loading…
Cancel
Save