电力需求预测挑战赛
理解赛题
【训练时序预测模型助力电力需求预测
赛题任务
给定多个房屋对应电力消耗历史N天的相关序列数据等信息,预测房屋对应电力的消耗。
赛题数据
赛题数据由训练集和测试集组成,为了保证比赛的公平性,将每日日期进行脱敏,用1-N进行标识。
即1为数据集最近一天,其中1-10为测试集数据。
数据集由字段id(房屋id)、 dt(日标识)、type(房屋类型)、target(实际电力消耗)组成。
注意时间穿越问题,不要用未来的数据预测过去
优化思路
0.特征优化
1.窗口从三个变成7,10个
2.除了均值,还有最值,中位数,方差
3.差分统计,增大减小的趋势
4.K值交叉验证(可能出现穿越问题)
5.模型融合
baseline代码
学习文件的输入与输出
# 1. 导入需要用到的相关库
# 导入 pandas 库,用于数据处理和分析
import pandas as pd
# 导入 numpy 库,用于科学计算和多维数组操作
import numpy as np
# 2. 读取训练集和测试集
# 使用 read_csv() 函数从文件中读取训练集数据,文件名为 'train.csv'
train = pd.read_csv('./data/train.csv')
# 使用 read_csv() 函数从文件中读取测试集数据,文件名为 'train.csv'
test = pd.read_csv('./data/test.csv')
# 3. 计算训练数据最近11-20单位时间内对应id的目标均值
target_mean = train[train['dt']<=20].groupby(['id'])['target'].mean().reset_index()
# 4. 将target_mean作为测试集结果进行合并
test = test.merge(target_mean, on=['id'], how='left')
# 5. 保存结果文件到本地
test[['id','dt','target']].to_csv('task01_submit.csv', index=None)
task02代码-lightgbm
1.数据可视化
2.在代码加入print语句,作为断点,便于调试
#安装lightgbm
!pip install lightgbm==3.3.0
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.metrics import mean_squared_log_error, mean_absolute_error, mean_squared_error
import tqdm
import sys
import os
import gc
import argparse
import warnings
warnings.filterwarnings('ignore')
# 读取训练数据和测试数据
train = pd.read_csv('./data/data283931/train.csv')
test = pd.read_csv('./data/data283931/test.csv')
# 不同type类型对应target的柱状图
import matplotlib.pyplot as plt
type_target_df = train.groupby('type')['target'].mean().reset_index()
plt.figure(figsize=(8, 4))
plt.bar(type_target_df['type'], type_target_df['target'], color=['blue',
'green'])
plt.xlabel('Type')
plt.ylabel('Average Target Value')
plt.title('Bar Chart of Target by Type')
plt.show()
print("0Look me!!!!!")
# id为00037f39cf的按dt为序列关于target的折线图
specific_id_df = train[train['id'] == '00037f39cf']
plt.figure(figsize=(10, 5))
plt.plot(specific_id_df['dt'], specific_id_df['target'], marker='o',
linestyle='-')
plt.xlabel('DateTime')
plt.ylabel('Target Value')
plt.title("Line Chart of Target for ID '00037f39cf'")
plt.show()
print("1Look me!!!!!")
# 合并训练数据和测试数据,并进⾏排序
data = pd.concat([test, train], axis=0, ignore_index=True)
data = data.sort_values(['id','dt'], ascending=False).reset_index(drop=True)
# 历史平移
for i in range(10,30):
data[f'last{i}_target'] = data.groupby(['id'])['target'].shift(i)
# 窗⼝统计
data[f'win3_sum_target'] = 0
for i in range(10,30):
data[f'win3_sum_target'] += data[f'last{i}_target']
data[f'win3_mean_target'] = data[f'win3_sum_target'] / 20.0
# data[f'win3_mean_target'] = (data['last10_target'] + data['last11_target'] + data['last12_target']) / 3
# 进⾏数据切分
train = data[data.target.notnull()].reset_index(drop=True)
test = data[data.target.isnull()].reset_index(drop=True)
# 确定输⼊特征
train_cols = [f for f in data.columns if f not in ['id','target']]
print("2Look me!!!!!")
#############
def time_model(lgb, train_df, test_df, cols):
# 训练集和验证集切分
print("3Look me!!!!!")
trn_x, trn_y = train_df[train_df.dt>=31][cols], train_df[train_df.dt>=31]['target']
val_x, val_y = train_df[train_df.dt<=30][cols], train_df[train_df.dt<=30]['target']
# 构建模型输⼊数据
print("4Look me!!!!!")
train_matrix = lgb.Dataset(trn_x, label=trn_y)
valid_matrix = lgb.Dataset(val_x, label=val_y)
# lightgbm参数
print("5Look me!!!!!")
lgb_params = {
'boosting_type': 'gbdt',
'objective': 'regression',
'metric': 'mse',
'min_child_weight': 5,
#'max_depth' : 25,
'num_leaves': 2 ** 4 + 2 ** 3,
# 2 ** 5
'lambda_l2': 10,
'feature_fraction': 0.8,
'bagging_fraction': 0.8,
'bagging_freq': 4,
'learning_rate': 0.05,
'seed': 2024,
'nthread' : 16,
'verbose' : -1,
}
print("5.1Look me!!!!!")
# 训练模型
model = lgb.train(lgb_params, train_matrix, 50000, valid_sets=
[train_matrix, valid_matrix], categorical_feature=[], verbose_eval=500, early_stopping_rounds=500)
print("5.2Look me!!!!!")
# 验证集和测试集结果预测
val_pred = model.predict(val_x, num_iteration=model.best_iteration)
test_pred = model.predict(test_df[cols],
num_iteration=model.best_iteration)
# 离线分数评估
score = mean_squared_error(val_pred, val_y)
print(score)
print("6Look me!!!!!")
return val_pred, test_pred
print("7Look me!!!!!")
print("8Look me!!!!!")
lgb_oof, lgb_test = time_model(lgb, train, test, train_cols)
print("9Look me!!!!!")
# 保存结果⽂件到本地
test['target'] = lgb_test
test[['id','dt','target']].to_csv('task02_submit_5.csv', index=None)
标签:plt,target,df,学习,train,import,data,夏令营,DatawhaleAI
From: https://www.cnblogs.com/kkkrran/p/18313253