KAGGLE竞赛实战2-捷信金融违约预测竞赛-part2-用lightgbm建立baseline

接着上一篇,用lightgbm建立baseline,发现模型效果得到了很大优化(模型分提升为0.73)

In211:

from sklearn.model_selection import cross_val_score,KFold

In228:

import lightgbm as lgb

In229:

from lightgbm import LGBMClassifier

In232:

from lightgbm import early_stopping

In237:

from sklearn.metrics import roc_auc_score

In215:

bad_chars=':','""','\\\\',''

for feature in application_train.columns:

if any(bad_char in feature for bad_char in bad_chars):

print(f"Feature '{feature}'包含非法字符。")

In216:

#去掉特殊字符import pandas as pd

import re

def clean_column_names(df):

"""

清理DataFrame列名,去除特殊字符,使其符合JSON格式要求。

参数:

df (pd.DataFrame): 输入的DataFrame。

返回:

pd.DataFrame: 列名已清理的DataFrame。

"""

定义一个函数,用于替换单个列名中的特殊字符

def replace_chars(col_name):

替换掉所有非字母数字和下划线的字符

return re.sub(r'\W+', '_', col_name)

应用替换函数到所有列名

df.columns = replace_chars(col) for col in df.columns

return df

In217:

application_train=clean_column_names(application_train)

application_test=clean_column_names(application_test)

In218:

bad_chars=':','""','\\\\',''

for feature in application_train.columns:

if any(bad_char in feature for bad_char in bad_chars):

print(f"Feature '{feature}'包含非法字符。")

In238:

def fit(train=application_train, valid=application_test):

"""

模型训练函数,

参数:train训练集

valid测试集

返回值:

valid_auc:验证集上AUC指标

feature_importances:特征重要性

test_results:测试集结果

"""

test = valid.copy()

x_train = train.drop('SK_ID_CURR', 'TARGET', axis=1)

y_train = train'TARGET'

五折交叉验证

folds = KFold(n_splits=5, shuffle=True, random_state=1412)

定义变量保存预测结果

oof_preds = np.zeros(y_train.shape0)

test_preds = np.zeros(test.shape0)

提取特征名

feature_names = list(x_train.columns)

空数组用于存储特征重要性值

feature_importance_values = np.zeros(len(feature_names))

实例化模型

lgb = LGBMClassifier(n_estimators=10000, early_stopping_round=200, random_state=24)

for fold_idx, (train_idx, valid_idx) in enumerate(folds.split(x_train)):

X = x_train.iloctrain_idx

y = y_train.iloctrain_idx

valid_X = x_train.ilocvalid_idx

valid_y = y_train.ilocvalid_idx

定义早停回调函数

callbacks = early_stopping(stopping_rounds=200)

拟合模型

lgb.fit(X, y, eval_set=(X, y), (valid_X, valid_y), callbacks=callbacks)

记录特征重要性

feature_importance_values += lgb.feature_importances_ / folds.n_splits

在验证集上进行预测

proba = lgb.predict_proba(valid_X, num_iteration=lgb.best_iteration_)

oof_predsvalid_idx = proba:, 1 # 选择正类概率

test_preds += lgb.predict_proba(testfeature_names, num_iteration=lgb.best_iteration_):, 1

valid_auc = roc_auc_score(y_train, oof_preds)

feature_importances = pd.DataFrame({'feature': feature_names, 'importance': feature_importance_values})

test'TARGET' = test_preds

return valid_auc, feature_importances, test\['SK_ID_CURR', 'TARGET']

In246:

valid_auc,feature_importance,submission=fit(application_train:50000,application_test)

#发现报错了Do not support special JSON characters in feature name,原因是有些列名里有特殊的字符,这是get_dummies时产生的

In247:

valid_auc #0.7421786519800682

In248:

#看下特征重要性

feature_importance.sort_values(by='importance',ascending=False)

In250:

submission.to_csv('baseline_model_lightgbm.csv',index=False)#提交后成绩0.73

In251:

application_train.to_csv('original_application_train.csv')#保存下结果

application_test.to_csv('original_application_test.csv')

相关推荐
怪奇云呼军1 天前
从声音特征到 CRM 回流:闪电智能 Voice Agent 沟通策略自适应系统 v1 实战
android·人工智能·python·音视频·语音识别
jufeng13071 天前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 6 篇】
python·ai agent·记忆系统
kevinnett1 天前
别再把模型地址写死了:用 Python 设计一个可切换的 LLM 调用层
python
天天进步20151 天前
Python全栈项目--协同办公平台
开发语言·python
leoZ2311 天前
Vue3 还原一个企业级后台-06-主布局设计
人工智能·opencv·机器学习·计算机视觉·数据挖掘·语音识别·caffe
GEOshijie1231 天前
GEO服务商算法适配承诺怎么验收?48小时响应的合同化考核方案
人工智能·python
卷无止境1 天前
FastAPI 前端托管全攻略:从静态文件到大型全栈项目架构
后端·python
QQ5416451211 天前
【驿帮查件助手python开源】开源聚合查件机器人,实现 24 类驿站批量查件取代短信通知。技术方案分享
python·机器人·开源·驿站查件机器人
卷无止境1 天前
当FastAPI项目开始"膨胀",代码该往哪儿放
后端·python
用户8356290780511 天前
Python设置PowerPoint幻灯片背景的方法
后端·python