基于xgboost 的贷款风险预测

本文通过使用XGBoost算法处理贷款安全性预测问题,展示了从数据预处理到模型训练及评估的全过程,并通过准确率和AUC指标验证了模型的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    
    现在我们用传说中的xgboost 对这个数据集进行计算

 
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 19 13:19:26 2017

@author: luogan
"""

import pandas as pd
df = pd.read_csv('loans.csv')

from sklearn.preprocessing import LabelEncoder
from collections import defaultdict
d = defaultdict(LabelEncoder)
dff =df.apply(lambda df: d[df.name].fit_transform(df))
dff.to_excel('dff.xls')



import pandas as pd
import numpy as np
import xgboost as xgb
from xgboost.sklearn import XGBClassifier
from sklearn import cross_validation, metrics   #Additional     scklearn functions
from sklearn.grid_search import GridSearchCV   #Perforing grid search
 
import matplotlib.pylab as plt
#%matplotlib inline
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 12, 4
 
train = pd.read_excel('dff.xls')
target = 'safe_loans'
IDcol = 'id'


def modelfit(alg, dtrain, predictors,useTrainCV=True, cv_folds=5, early_stopping_rounds=50):
    
    if useTrainCV:
        xgb_param = alg.get_xgb_params()
        xgtrain = xgb.DMatrix(dtrain[predictors].values, label=dtrain[target].values)
        cvresult = xgb.cv(xgb_param, xgtrain, num_boost_round=alg.get_params()['n_estimators'], nfold=cv_folds,
            metrics='auc', early_stopping_rounds=early_stopping_rounds)
        alg.set_params(n_estimators=cvresult.shape[0])
    
    #Fit the algorithm on the data
    alg.fit(dtrain[predictors], dtrain['safe_loans'],eval_metric='auc')
        
    #Predict training set:
    dtrain_predictions = alg.predict(dtrain[predictors])
    dtrain_predprob = alg.predict_proba(dtrain[predictors])[:,1]
    from pandas import DataFrame
    '''
    gg=DataFrame(dtrain_predictions)
    gg.to_excel('dtrain_predictions.xls')   
    
    tt=DataFrame(dtrain_predprob)
    tt.to_excel('dtrain_predprob.xls')
    '''
    
    print(alg)
    #Print model report:
    print ("\nModel Report")
    print ("Accuracy : %.4g" % metrics.accuracy_score(dtrain['safe_loans'].values, dtrain_predictions))
    print ("AUC Score (Train): %f" % metrics.roc_auc_score(dtrain['safe_loans'], dtrain_predprob))
    
    ww=(alg.feature_importances_)
    print(ww)            
    feat_imp = pd.Series(ww).sort_values(ascending=False)
    
    #print(feat_imp)
    
    feat_imp.plot(kind='bar', title='Feature Importances')
    plt.ylabel('Feature Importance Score')
    
    """
    model=alg
    featureImportance = model.get_score() 
    features = pd.DataFrame() 
    features['features'] = featureImportance.keys() 
    features['importance'] = featureImportance.values() 
    features.sort_values(by=['importance'],ascending=False,inplace=True) 
    fig,ax= plt.subplots() 
    fig.set_size_inches(20,10) 
    plt.xticks(rotation=60) 
    #sn.barplot(data=features.head(30),x="features",y="importance",ax=ax,orient="v") 
    """
    
    
#Choose all predictors except target & IDcols
predictors = [x for x in train.columns if x not in [target, IDcol]]
xgb1 = XGBClassifier(
                learning_rate =0.1,
                n_estimators=1000,
                max_depth=18,
                min_child_weight=1,
                gamma=0,
                subsample=0.8,
                colsample_bytree=0.8,
                objective= 'binary:logistic',
                nthread=4,
                scale_pos_weight=1,
                seed=27)
modelfit(xgb1, train, predictors)     




 

Model Report
Accuracy : 0.9533
AUC Score (Train): 0.990971

    正确率95%,甩决策树和BP网几条街啊!
可见传说中的xgboost果然厉害,难怪工业实践中xgboost 应用如痴的广泛
下图显示了每个 feature的重要性,里面有两个文件,请运行xgboost.py

这里写图片描述

代码文件下载

github代码

### 安装LibreOffice于无外网连接的Linux系统 #### 准备工作 对于在没有互联网连接的情况下安装LibreOffice,在离线环境中操作前需确认目标系统的具体发行版,例如CentOS、Ubuntu或Debian等[^1]。这一步骤至关重要,因为不同版本的操作系统可能需要特定配置或是依赖库。 #### 下载所需文件 为了顺利完成安装过程,建议先在一个有网络访问权限的机器上登录LibreOffice官方网站,依据所使用的操作系统环境挑选相匹配的软件包组合。通常情况下,除了主要的应用程序包之外,还需要额外获取中文语言支持以及帮助文档的相关资源,并将这些压缩文件传输至待部署的目标设备上的`/opt`目录下[^3]。 #### 解压并设置环境变量 一旦所有必需的数据都被安全转移过来之后,则可利用命令行工具解压缩已下载好的档案: ```bash tar -xvf LibreOffice_*.tar.gz -C /opt/ ``` 接着创建指向新安装位置的链接以便后续调用更加便捷: ```bash ln -s /opt/LibreOffice_* /opt/libreoffice ``` 最后更新共享库缓存使新增加的内容生效: ```bash ldconfig ``` #### 配置桌面集成 为了让应用程序更好地融入现有的图形界面当中去,还需执行如下指令来完成最终设定: ```bash /opt/libreoffice/program/setup.bin --nodefaultlinktarget --nologo --norestore ``` 通过上述一系列措施即可实现在不具备公网接入条件下的Linux平台上成功部署LibreOffice办公套件的目的。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值