基于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

# 1. 创建LGBMClassifier对象
lg = lgb.LGBMClassifier()

# 2. 定义参数空间
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)}

# 3. 使用RandomizedSearchCV进行参数调优
rscv = RandomizedSearchCV(lg, param_distributions=params, cv=5, scoring='roc_auc', n_iter=10, n_jobs=-1)
rscv.fit(x, y)

# 4. 使用最优参数创建模型并训练
lg = lgb.LGBMClassifier(**rscv.best_params_)
lg.fit(x_train, y_train)

# 5. 预测和评估模型
# 训练集
y_train_pred = lg.predict(x_train)
y_train_prob = lg.predict_proba(x_train)[:, 1]
print('训练集 ROC score:', roc_auc_score(y_train, y_train_prob))
print('训练集 Classification report:
', classification_report(y_train, y_train_pred))
print('训练集 Confusion matrix:
', 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 score:', roc_auc_score(y_test, y_test_prob))
print('测试集 Classification report:
', classification_report(y_test, y_test_pred))
print('测试集 Confusion matrix:
', confusion_matrix(y_test, y_test_pred))

代码功能说明:

  1. 导入必要的库: 导入lightgbm, RandomizedSearchCV, roc_auc_score, classification_report, confusion_matrix等库。
  2. 创建模型: 创建一个LGBMClassifier对象作为模型的基础。
  3. 定义参数空间: 定义模型的参数params,包括'boosting_type', 'max_depth', 'learning_rate', 'n_estimators'等。
  4. 参数调优: 使用RandomizedSearchCV函数对模型进行参数调优,找到最优参数rscv.best_params_
  5. 模型训练: 使用最优参数创建新的LGBMClassifier对象,并使用训练集x_trainy_train对模型进行训练。
  6. 模型预测: 使用训练好的模型对训练集和测试集进行预测,并计算预测概率。
  7. 模型评估: 计算并打印训练集和测试集的ROC score、Classification report和Confusion matrix等指标,用于评估模型的性能。

总结

该代码展示了如何使用LightGBM模型进行信用卡使用意图预测,并通过RandomizedSearchCV进行参数调优,提升模型性能。同时,代码还展示了如何评估模型的性能,并对结果进行可视化展示。

基于LightGBM的信用卡使用意图预测模型

原文地址: https://www.cveoy.top/t/topic/fVPr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录