基于LightGBM的信用卡使用意图预测模型
基于LightGBM的信用卡使用意图预测模型
本文介绍如何使用LightGBM模型对已有数据进行训练和测试,以预测信用卡使用意图。
代码解析
import lightgbm as lgb
from sklearn.model_selection import RandomizedSearchCV
from sklearn.metrics import roc_auc_score, classification_report, confusion_matrix
from scipy.stats import randint as sp_randint
# 创建LGBMClassifier对象
lg = lgb.LGBMClassifier()
# 定义参数范围
params = {'boosting_type': ['gdbt', 'dart', 'rf'],
'max_depth': sp_randint(-1, 20),
'learning_rate': [0.1, 0.2, 0.3, 0.4, 0.5],
'n_estimators': sp_randint(50, 400)}
# 使用RandomizedSearchCV进行参数调优
rscv = RandomizedSearchCV(lg, param_distributions=params, cv=5, scoring='roc_auc', n_iter=10, n_jobs=-1)
rscv.fit(x, y)
# 输出最佳参数组合
print('最佳参数组合:', rscv.best_params_)
# 使用最佳参数创建LGBMClassifier对象
lg = lgb.LGBMClassifier(**rscv.best_params_)
# 使用训练数据训练模型
lg.fit(x_train, y_train)
# 预测训练数据
y_train_pred = lg.predict(x_train)
y_train_prob = lg.predict_proba(x_train)[:, 1]
# 评估训练结果
print('训练集 ROC 分数:', roc_auc_score(y_train, y_train_prob))
print('训练集分类报告:
', classification_report(y_train, y_train_pred))
print('训练集混淆矩阵:
', confusion_matrix(y_train, y_train_pred))
# 预测测试数据
y_test_pred = lg.predict(x_test)
y_test_prob = lg.predict_proba(x_test)[:, 1]
# 评估测试结果
print('测试集 ROC 分数:', roc_auc_score(y_test, y_test_prob))
print('测试集分类报告:
', classification_report(y_test, y_test_pred))
print('测试集混淆矩阵:
', confusion_matrix(y_test, y_test_pred))
代码步骤详解
- 导入必要的库: 包括
lightgbm,RandomizedSearchCV,roc_auc_score,classification_report,confusion_matrix和sp_randint。 - 创建LGBMClassifier对象: 初始化一个LightGBM分类器对象。
- 定义参数范围: 为
RandomizedSearchCV指定LightGBM模型的参数搜索空间,包括boosting_type,max_depth,learning_rate和n_estimators等关键参数。 - 使用RandomizedSearchCV进行参数调优: 使用交叉验证和指定的评分函数(
roc_auc),在定义的参数空间中搜索最佳参数组合,并输出最佳参数组合。 - 使用最佳参数创建LGBMClassifier对象: 利用找到的最佳参数创建一个新的LightGBM分类器对象。
- 使用训练数据训练模型: 使用训练集数据对模型进行训练。
- 预测训练数据: 使用训练好的模型对训练集进行预测,并计算预测结果的ROC分数、分类报告和混淆矩阵,评估模型在训练集上的性能。
- 预测测试数据: 使用训练好的模型对测试集进行预测,并计算预测结果的ROC分数、分类报告和混淆矩阵,评估模型在测试集上的泛化性能。
总结
该代码利用LightGBM强大的模型训练能力和RandomizedSearchCV高效的参数优化功能,实现了信用卡使用意图的预测,并通过多种评估指标全面评估模型性能。
原文地址: https://www.cveoy.top/t/topic/fVPq 著作权归作者所有。请勿转载和采集!