我们每天都在用支付宝,蚂蚁金服风险识别速度可达到100毫秒,比眨眼一次的时间还要快四倍。在全球数字经济时代,有一种金融优势,那就是基于消费者大数据的纯信用!
python信用卡评分模型_逻辑回归
我们不妨称之为数据信用,它比抵押更靠谱,它比担保更保险,它比监管更高明,它是一种面向未来的财产权,它是数字货币背后核心的抵押资产,它决定了数字货币时代信用创造的方向、速度和规模。一句话,谁掌握了数据信用,谁就控制了数字货币的发行权!数据信用判断依靠的就是金融风控模型。

谁能掌握风控模型知识,谁就掌握了数字货币的发行权!风控模型是怎么搭建的?风控模型应该采用什么算法?风控模型可以取代银行担保模式吗?风控模型是互联网大咖描述的那么无所不能吗?

欢迎各位同学学习python金融风控评分卡模型和数据分析微专业课
https://edu.51cto.com/sd/f2e9b
python信用卡评分模型_模型_02
python信用卡评分模型_python_03

python信用卡评分模型_python_04
python信用卡评分模型_算法_05

python信用卡评分模型_评分卡_06
python信用卡评分模型_模型_07
python信用卡评分模型_模型_08
python信用卡评分模型_逻辑回归_09
python信用卡评分模型_python_10

python信用卡评分模型_算法_11
课程目录

章节1前言
章节1Python环境搭建
课时1 建评分卡模型,python,R,SAS谁最好?
课时2 Anaconda快速入门指南
课时3 Anaconda下载和安装
课时4 canopy下载和安装
课时5 Anaconda Navigato导航器
课时6 python安装第三方包:pip和conda install
课时7 Python非官方扩展包下载地址
课时8 Anaconda安装不同版本python
课时9 jupyter1_为什么使用jupyter notebook?
课时10 jupyter2_jupyter基本文本编辑操作
课时11 如何用jupyter notebook打开指定文件夹内容?
课时12 jupyter4_jupyter转换PPT实操
课时13 jupyter notebook用matplotlib不显示图片解决方案

章节2 python编程基础知识
课时14 Python文件基本操作
课时15 变量_表达式_运算符_值
课时16 字符串string
课时17 列表list
课时18 程序的基本构架(条件,循环)
课时19 数据类型_函数_面向对象编程
课时20 python2和3的区别
课时21 编程技巧和学习方法

章节3 python机器学习基础
课时22 UCI机器学习常用数据库介绍
课时23 机器学习书籍推荐
课时24 如何选择算法
课时25 机器学习语法速查表
课时26 python数据科学常用的库
课时27 python数据科学入门介绍(选修)

章节4 德国信用评分数据下载和介绍
课时28 35德国信用评分数据下载和介绍

章节5信用评分卡开发流程(上)
课时29 评分卡开发流程概述
课时30 第一步:数据收集
课时31 第二步:数据准备
课时32 变量可视化分析
课时33 样本量需要多少?
课时34 坏客户定义
课时35 第三步:变量筛选
课时36 变量重要性评估_iv和信息增益混合方法
课时37 衍生变量05:01
课时38 第四步:变量分箱01:38

章节6信用评分卡开发流程(下)
课时39 第五步:建立逻辑回归模型
课时40 odds赔率
课时41 woe计算
课时42 变量系数
课时43 A和B计算
课时44 Excel手动计算坏客户概率
课时45 Python脚本计算坏客户概率
课时46 客户评分
课时47 评分卡诞生-变量分数计算
课时48 拒绝演绎reject inference
课时49 第六步:模型验证
课时50 第七步:模型部署
课时51 常见模型部署问题

新增章节 模型开发基础知识python脚本讲解
课时59数据读取read_excel和read_csv
课时60数据划分train_test_split
课时61LogisticRegression()模型构建和训练fit()
课时62模型预测predict和predict_proba区别
课时63模型验证的python脚本讲解
课时64pickle保存模型包

章节7 Python信用评分卡-逻辑回归脚本
课时52 Python信用评分卡脚本运行演示
课时53 描述性统计脚本_缺失率和共线性分析
课时54 woe脚本(kmean分箱)
课时55 iv计算独家脚本
课时56 Excel手动推导变量woe和iv值
课时57 评分卡脚本1(sklearn)
课时58 评分卡脚本2(statsmodel)
课时59 生成评分卡脚本
课时60 模型验证脚本

章节8PSI(population stability index)稳定指标
课时61 拿破仑远征欧洲失败/华尔街股灾真凶-PSI模型稳定指标揭秘
课时62 excel推导PSI的计算公式
课时63 PSI计算公式原理_独家秘密
课时64 PSI的python脚本讲解

章节9难点1_坏客户定义
课时65 坏客户定义错误,全盘皆输
课时66 不同场景坏客户定义不一样,坏客户定义具有反复性
课时67 坏客户占比不能太低
课时68 vintage源于葡萄酒酿造
课时69 vintage用于授信策略优化

章节10难点2_woe分箱
课时70 ln对数函数
课时71 excel手动计算woe值
课时72 python计算woe脚本
课时73 Iv计算推导
课时74 woe正负符号意义
课时75 WOE计算就这么简单?你想多了
课时76 Kmean算法原理
课时77 python kmean实现粗分箱脚本
课时78 自动化比较变量不同分箱的iv值
课时79 woe分箱第三方包脚本

章节11难点3_逻辑回归是最佳算法吗?
课时80 逻辑回归是最优算法吗?No
课时81 xgboost_支持脚本下载
课时82 随机森林randomForest_支持脚本下载
课时83 支持向量SVM_支持脚本下载
课时84 神经网络neural network_支持脚本下载
课时85 多算法比较重要性_模型竞赛,百万奖金任你拿

章节12难点4_变量缺失数据处理
课时86 imputer-缺失数据处理
课时87 xgboost简单处理缺失数据
课时88 catboost处理缺失数据最简单

章节13难点5.模型验证
课时89 模型需要验证码?
课时90 商业银行资本管理办法(试行)
课时91 模型验证_信用风险内部评级体系监管要求
课时92 模型验证主要指标概述
课时93 交叉验证cross validation
课时94 groupby分类统计函数
课时95 KS_模型区分能力指标
课时96 混淆矩阵(accuracy,precision,recall,f1 score)
新增课时   模型排序能力-lift提升图

章节14难点6.逻辑回归调参
课时97 菜鸟也能轻松调参
课时98 调参1_Penalty正则化选择参数
课时99 调参2_classWeight类别权重
课时100 调参3_solver优化算法选择参数
课时101 调参4_n_jobs
课时102 L-BFGS算法演化历史
课时103 次要参数一览

新增章节 难点7_非平衡样本数据imbalanced data
课时121非平衡数据是什么?对模型有什么坏处?
课时122解决非平衡数据方法(欠采样,过采样,SMOTE)
继续学习
课时123SMOTE非平衡数据处理python脚本讲解

章节16 风控管理和诈骗中介(选修)
课时104 网络信贷发展史
课时105 诈骗中介
课时106 风控管理
课时107 告别套路贷,高利贷,选择正确贷款方式

章节17 2018-2019消费金融市场行情
课时108 揭秘:近年消费金融火爆发展根本原因
课时109 持牌照消费金融公司盈利排行榜
课时110 消费金融,风控技术是瓶颈
课时111 谁能笑到最后:2018-2019消费金融公司注册资本
课时112 萝卜加大棒:中央政策监管趋势独家预测
课时113 信用是金融交易的基石_P2P倒闭潮秘密

章节18 2018-2019年全球宏观经济
课时114 专家不会告诉你的秘密:美元和黄金真实关系
课时115 宏观经济主要指标:债务率和失业率
课时116 2019年中国宏观经济分析_赠人民银行发布2018n年中国金融稳定报告
课时117 2019年G20国家宏观经济信息汇总_供下载
课时118 全球系统金融风险
课时119 基尼系数_贫富差异指标
课时120 GDP_利率_通货膨胀
课时121 失业率_债务率
课时122 贸易差额_中美贸易战根本原因
课时123 信用评级_阿根廷金融危机独家解读

为什么需要风控模型?

风控模型目的将银行风险最小化并将利润最大化。贷款有风险,如果用户借钱不还或故意骗贷,银行就会有损失。风控模型作用就是识别这些借钱不还用户,然后过滤掉这些坏用户。这样银行放款对象基本是优质客户,可以从中赚取利息,从而达到利润最大化,风险最小化。

为了从银行的角度将损失降到最低,银行需要制定决策规则,确定谁批准贷款,谁不批准。 在决定贷款申请之前,贷款经理会考虑申请人的人口统计和社会经济概况。

德国信贷数据包含有关20个变量的数据,以及1000个贷款申请者被认为是好信用风险还是坏信用风险的分类。 这是指向德国信用数据的链接(右键单击并另存为)。 预期基于此数据开发的预测模型将为银行经理提供指导,以根据他/她的个人资料来决定是否批准准申请人的贷款。

风控历史

世界上最早的银行出现在意大利。 最早的银行是意大利1407年在威尼斯成立的银行。当然类似于银行的机构可能存更早存在。只要有银行,就会有风险控制和管理,即风控。早期风控包括对借贷人资质审核和账户核实。

python信用卡评分模型_模型_12

随着金融业发展,贷款流程逐渐完善,包括下图流程
python信用卡评分模型_算法_13
2000-2008后,全球逐步进入大数据时代,随着用户数据整合,诞生央行征信,公安人脸数据,芝麻信用分,同盾分,聚信立蜜罐分,百度黑中介分等参考数据。银行,消费金融公司,小额贷公司可以利用大数据建模,利用机器智能决策代替绝大部分人工审核,缩短信贷流程,减少贷款风险,实现利润最大化。
python信用卡评分模型_逻辑回归_14
现代大数据时代的风控部门主要分为贷前,贷中和贷后管理三个板块。
python信用卡评分模型_模型_15
信用危机时代的信用评分卡

20世纪后,银行业飞速发展。随着我国居民消费心理发生改变和各大商家诱导性消费,不少朋友越来越依赖超前消费了。我国14亿人口,消费群体庞大,各类产品也有着很大的市场,于是现在的消费信贷市场成了很多银行或者其他机构发力的方向。根据央行公布的数据来看,商业银行发行的信用卡数量继续扩张,但在“滥发”信用卡的背后,逾期坏账不断增加也成了银行头疼问题。

信用卡逾期半年以上坏账突破900亿

近日,央行公布了三季度支付体系的运行报告,从央行公布的数据来看,我国商业银行发行的信用卡数量、授信总额以及坏账总额均在保持增长。

数据显示,截至今年三季度末,我国商业银行发行的信用卡(包括借贷合一卡)的数量达到了7.66亿张,环比增加1.29%。总授信额度达到了18.59万亿元,环比增加3.80%。

下卡量在增加,加上授信总额在不断增长,说明银行依旧非常重视信用卡市场,但同时这也给银行带来了不小的麻烦。因为截至今年三季度末,信用卡逾期半年以上的坏账来到了906.63亿元,环比大涨6.13%。

信用卡下卡数量不断增加,说明在初审阶段银行并没有管理的太严格,因此坏账增加是客观会存在的问题。
python信用卡评分模型_评分卡_16
之前银行是当铺思想,把钱借给有偿还能力的人。这些人群算是优质客群。更糟糕的是但随着量化宽松,财政货币刺激,M2激增,银行,消费金融公司,小额贷公司纷纷把市场目标扩大到次级客户,即偿还能力不足或没有工作的人,这些人还钱风险很高,因此借钱利息也很高。作为小额贷,助贷,消费金融公司的贷前审批人员,是否经历过下图的场景?骗贷,黑中介,灰色产业链,他们无孔不入,搞得你们晕头转向,不好判断用户还要领导拍脑壳决定是否放贷。
python信用卡评分模型_python_17
国内黑产,灰产已经形成庞大产业链条。根据之前同盾公司统计,黑产团队至少上千个,多大为3人左右小团队,100人以上大团队也有几十上百个。这些黑产团队天天测试各大现金贷平台漏洞,可谓专业产品经理。下图是生产虚假号码的手机卡,来自东南亚,国内可用,可最大程度规避国内安全监控,专门为线上平台现金贷诈骗用户准备。,如果没有风控能力,就不要玩现金贷这行了。放款犹如肉包子打狗有去无回。
python信用卡评分模型_模型_18
举个身边熟悉例子,作者在之前某宝关键词搜索中,可以发现黑产和灰产身影。

关键词:

注册机,短信服务,短信接收,短信验证,app下单,智能终端代接m
python信用卡评分模型_python_19
python信用卡评分模型_模型_20

python信用卡评分模型_python_21
黑产市场风起云涌,银行风控负责人改如何应对持续上升信用卡坏账?作者认为识别坏客户(骗贷和还款能力不足人群)是关键。只有银行精准识别了坏客户,才能显著降低逾期和坏账率。如何精准识别坏客户,改课程会手把手教你大家Python信用评分卡模型,精准捕捉坏客户,此乃风控守护神。

信用评分卡可以成为贷款人和借款人计算借款人偿债能力的绝佳工具。对于贷方而言,评分卡可以帮助他们评估借款人的风险,识别是否是骗贷用户或还款能力不足用户,并帮公司维持健康的投资组合 - 这最终将影响整个经济。

模型就像一个黑箱,当用户申请贷款时,模型会根据用户信息,例如年龄,工作,职位,还款记录,借贷次数等维度自动计算客户坏客户概率。业务线如果用模型计算出某用户坏客户概率较高,例如0.8,就会拒绝改客户贷款申请。

因此风控模型就像信贷守护神,保护公司资产,免受黑产吞噬。评分卡模型自动化评分,1秒之内决定客户是否通过,贷前人员工作轻松多了!这样,大数据时代下的风控模型就此诞生。


python信用卡评分模型_评分卡_22

信用评分卡建模数据

http://archive.ics.uci.edu/ml/datasets/Statlog+(German+Credit+Data)
python信用卡评分模型_评分卡_23

部分关键变量翻译
account balance 账户余额

duration of credit持卡时长

python信用卡评分模型_逻辑回归_24

建模数据信息Data Set Information:

Two datasets are provided. the original dataset, in the form provided by Prof. Hofmann, contains categorical/symbolic attributes and is in the file "german.data".

For algorithms that need numerical attributes, Strathclyde University produced the file "german.data-numeric". This file has been edited and several indicator variables added to make it suitable for algorithms which cannot cope with categorical variables. Several attributes that are ordered categorical (such as attribute 17) have been coded as integer. This was the form used by StatLog.

This dataset requires use of a cost matrix (see below)

提供了两个数据集。 原始数据集以Hofmann教授提供的形式包含类别/符号属性,并且位于文件“ german.data”中。

对于需要数字属性的算法,斯特拉斯克莱德大学产生了文件“ german.data-numeric”。 该文件已经过编辑,并添加了一些指标变量,以使其适用于无法处理分类变量的算法。 几个按类别排序的属性(例如属性17)已编码为整数。 这是StatLog使用的形式。

该数据集需要使用成本矩阵(请参见下文)

..... 1 2


1 0 1


2 5 0

(1 = Good, 2 = Bad)

The rows represent the actual classification and the columns the predicted classification.

It is worse to class a customer as good when they are bad (5), than it is to class a customer as bad when they are good (1).

Attribute Information:

Attribute 1: (qualitative)
Status of existing checking account
A11 : ... < 0 DM
A12 : 0 <= ... < 200 DM
A13 : ... >= 200 DM / salary assignments for at least 1 year
A14 : no checking account

Attribute 2: (numerical)
Duration in month

Attribute 3: (qualitative)
Credit history
A30 : no credits taken/ all credits paid back duly
A31 : all credits at this bank paid back duly
A32 : existing credits paid back duly till now
A33 : delay in paying off in the past
A34 : critical account/ other credits existing (not at this bank)

Attribute 4: (qualitative)
Purpose
A40 : car (new)
A41 : car (used)
A42 : furniture/equipment
A43 : radio/television
A44 : domestic appliances
A45 : repairs
A46 : education
A47 : (vacation - does not exist?)
A48 : retraining
A49 : business
A410 : others

Attribute 5: (numerical)
Credit amount

Attibute 6: (qualitative)
Savings account/bonds
A61 : ... < 100 DM
A62 : 100 <= ... < 500 DM
A63 : 500 <= ... < 1000 DM
A64 : .. >= 1000 DM
A65 : unknown/ no savings account

Attribute 7: (qualitative)
Present employment since
A71 : unemployed
A72 : ... < 1 year
A73 : 1 <= ... < 4 years
A74 : 4 <= ... < 7 years
A75 : .. >= 7 years

Attribute 8: (numerical)
Installment rate in percentage of disposable income

Attribute 9: (qualitative)
Personal status and sex
A91 : male : divorced/separated
A92 : female : divorced/separated/married
A93 : male : single
A94 : male : married/widowed
A95 : female : single

Attribute 10: (qualitative)
Other debtors / guarantors
A101 : none
A102 : co-applicant
A103 : guarantor

Attribute 11: (numerical)
Present residence since

Attribute 12: (qualitative)
Property
A121 : real estate
A122 : if not A121 : building society savings agreement/ life insurance
A123 : if not A121/A122 : car or other, not in attribute 6
A124 : unknown / no property

Attribute 13: (numerical)
Age in years

Attribute 14: (qualitative)
Other installment plans
A141 : bank
A142 : stores
A143 : none

Attribute 15: (qualitative)
Housing
A151 : rent
A152 : own
A153 : for free

Attribute 16: (numerical)
Number of existing credits at this bank

Attribute 17: (qualitative)
Job
A171 : unemployed/ unskilled - non-resident
A172 : unskilled - resident
A173 : skilled employee / official
A174 : management/ self-employed/
highly qualified employee/ officer

Attribute 18: (numerical)
Number of people being liable to provide maintenance for

Attribute 19: (qualitative)
Telephone
A191 : none
A192 : yes, registered under the customers name

Attribute 20: (qualitative)
foreign worker
A201 : yes
A202 : no

It is worse to class a customer as good when they are bad (5),

than it is to class a customer as bad when they are good (1).

评分卡开发流程

本课程通俗易懂,深度解析评分卡模型的各个细节,犹如庖丁解牛,各个击破。
python信用卡评分模型_python_25

课程会横向讲解评分卡模型是如何一步一步搭建的。
python信用卡评分模型_算法_26
 数学原理

课程还会讲述逻辑回归的信用评分卡搭建背后的算法原理,数学公式。
python信用卡评分模型_逻辑回归_27

取数

课程教会学员如何取数,什么是vintage?什么是样本窗口期?
python信用卡评分模型_模型_28

变量筛选

课程教授如何筛选变量,如何构建衍生变量。
python信用卡评分模型_评分卡_29

模型变量重要性排序结果

通过变量重要性排序,我们可以观察到下图中条状越长的变量,重要性越高,反之亦然。例如credit amount信用额度在下图是最长的,因此是最重要的变量。信用额度是指银行承诺提供贷款人的最高额度。一般情况下借贷人信誉越好,违约记录越少,信用额度越高;如果用户经常借钱不还,信誉差,信用额度越低。银行喜欢把钱借给信用额度高的用户,从而赚取利息。反正,银行不喜欢把钱借给信用额度低用户,这些用户本金可能还不上,银行不仅赚不到利息,而且亏损。
python信用卡评分模型_逻辑回归_30

python信用卡评分模型_python_31
课程提供python脚本和数据下载

课程提供视频中展示脚本和建模数据,并定期更新优化。学员可以下载后跟着视频一起演练。
python信用卡评分模型_python_32

模型运行后输出详细信息,包括变量的统计分析。
python信用卡评分模型_python_33
评分卡生成(score card)

python脚本可以生成一个评分卡模块(score card),详细保存每个变量有哪些分箱,每个分箱如何计分。这方便业务方和领导参考决策。
python信用卡评分模型_逻辑回归_34

python信用卡评分模型_python_35
拒绝推断reject reference

课程讲述了拒绝推断reject reference重要概念
python信用卡评分模型_算法_36
模型验证

课程还讲述模型验证的概念,建模数据需要分为train训练数据,test测试数据,oot更远时间段验证数据。此教程是市面上最全面讲述评分卡教程。
python信用卡评分模型_评分卡_37

python信用卡评分模型_逻辑回归_38
(模型验证的部分指标展示)

python信用卡评分模型_逻辑回归_39
(模型验证方法论)

模型部署和监控

此教程还概述模型部署和监控知识。模型部署是存在众多问题的,模型具有操作风险,经常会遇到模型线上线下数据不一致情况,变量映射错误,数据传输丢包,脚本漏写等等各种复杂情况。

从模型训练,模型打包,模型验证,模型部署,模型监控,重新训练模型,最终形成了一个模型开发周期闭环。

python信用卡评分模型_算法_40
(模型开发周期流程图)

                                       **python部分建模脚本展示**

randomForest.py

random forest with 1000 trees:
accuracy on the training subset:1.000
accuracy on the test subset:0.772

准确性高于决策树
`# -- coding: utf-8 --
"""
博主python金融风控评分卡模型和数据分析微专业课:https://edu.51cto.com/sd/f2e9b
随机森林不需要预处理数据
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

trees=1000
#读取文件
readFileName="German_credit.xlsx"
#读取excel
df=pd.read_excel(readFileName)
list_columns=list(df.columns[:-1])
X=df.ix[:,:-1]
y=df.ix[:,-1]
names=X.columns
x_train,x_test,y_train,y_test=train_test_split(X,y,random_state=0)
#n_estimators表示树的个数,测试中100颗树足够
forest=RandomForestClassifier(n_estimators=trees,random_state=0)
forest.fit(x_train,y_train)
print("random forest with %d trees:"%trees)
print("accuracy on the training subset:{:.3f}".format(forest.score(x_train,y_train)))
print("accuracy on the test subset:{:.3f}".format(forest.score(x_test,y_test)))
print('Feature importances:{}'.format(forest.featureimportances))
n_features=X.shape[1]
plt.barh(range(n_features),forest.featureimportances,align='center')
plt.yticks(np.arange(n_features),names)
plt.title("random forest with %d trees:"%trees)
plt.xlabel('Feature Importance')
plt.ylabel('Feature')
plt.show()`

python信用卡评分模型_模型_41

决策树可视化
python信用卡评分模型_模型_42
准确率不高,且严重过度拟合

`import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
import numpy as np
import pydotplus
from IPython.display import Image
import graphviz
from sklearn.tree import export_graphviz
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split

trees=1000
#读取文件
readFileName="German_credit.xlsx"
#读取excel
df=pd.read_excel(readFileName)
list_columns=list(df.columns[:-1])
x=df.ix[:,:-1]
y=df.ix[:,-1]
names=x.columns
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=0)
#调参
list_average_accuracy=[]
depth=range(1,30)
for i in depth:
#max_depth=4限制决策树深度可以降低算法复杂度,获取更精确值
tree= DecisionTreeClassifier(max_depth=i,random_state=0)
tree.fit(x_train,y_train)
accuracy_training=tree.score(x_train,y_train)
accuracy_test=tree.score(x_test,y_test)
average_accuracy=(accuracy_training+accuracy_test)/2.0
#print("average_accuracy:",average_accuracy)
list_average_accuracy.append(average_accuracy)

max_value=max(list_average_accuracy)
#索引是0开头,结果要加1
best_depth=list_average_accuracy.index(max_value)+1
print("best_depth:",best_depth)
best_tree= DecisionTreeClassifier(max_depth=best_depth,random_state=0)
best_tree.fit(x_train,y_train)
accuracy_training=best_tree.score(x_train,y_train)
accuracy_test=best_tree.score(x_test,y_test)
print("decision tree:")  
print("accuracy on the training subset:{:.3f}".format(best_tree.score(x_train,y_train)))
print("accuracy on the test subset:{:.3f}".format(best_tree.score(x_test,y_test)))

n_features=x.shape[1]
plt.barh(range(n_features),best_tree.featureimportances,align='center')
plt.yticks(np.arange(n_features),names)
plt.title("Decision Tree:")
plt.xlabel('Feature Importance')
plt.ylabel('Feature')
plt.show()

#生成一个dot文件,以后用cmd形式生成图片
export_graphviz(best_tree,out_file="creditTree.dot",class_names=['bad','good'],feature_names=names,impurity=False,filled=True)
'''
best_depth: 12
decision tree:
accuracy on the training subset:0.991
accuracy on the test subset:0.680
'''`

支持向量最高预测率
`#标准化数据
from sklearn import preprocessing
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import pandas as pd

#读取文件
readFileName="German_credit.xlsx"
#读取excel
df=pd.read_excel(readFileName)
list_columns=list(df.columns[:-1])
x=df.ix[:,:-1]
y=df.ix[:,-1]
names=x.columns
#random_state 相当于随机数种子
X_train,x_test,y_train,y_test=train_test_split(x,y,stratify=y,random_state=42)
svm=SVC()
svm.fit(X_train,y_train)
print("accuracy on the training subset:{:.3f}".format(svm.score(X_train,y_train)))
print("accuracy on the test subset:{:.3f}".format(svm.score(x_test,y_test)))
'''
accuracy on the training subset:1.000
accuracy on the test subset:0.700

'''
#观察数据是否标准化
plt.plot(X_train.min(axis=0),'o',label='Min')
plt.plot(X_train.max(axis=0),'v',label='Max')
plt.xlabel('Feature Index')
plt.ylabel('Feature magnitude in log scale')
plt.yscale('log')
plt.legend(loc='upper right')

#标准化数据
X_train_scaled = preprocessing.scale(X_train)
x_test_scaled = preprocessing.scale(x_test)
svm1=SVC()
svm1.fit(X_train_scaled,y_train)
print("accuracy on the scaled training subset:{:.3f}".format(svm1.score(X_train_scaled,y_train)))
print("accuracy on the scaled test subset:{:.3f}".format(svm1.score(x_test_scaled,y_test)))
'''
accuracy on the scaled training subset:0.867
accuracy on the scaled test subset:0.800
'''
#改变C参数,调优,kernel表示核函数,用于平面转换,probability表示是否需要计算概率
svm2=SVC(C=10,gamma="auto",kernel='rbf',probability=True)
svm2.fit(X_train_scaled,y_train)
print("after c parameter=10,accuracy on the scaled training subset:{:.3f}".format(svm2.score(X_train_scaled,y_train)))
print("after c parameter=10,accuracy on the scaled test subset:{:.3f}".format(svm2.score(x_test_scaled,y_test)))
'''
after c parameter=10,accuracy on the scaled training subset:0.972
after c parameter=10,accuracy on the scaled test subset:0.716
'''
#计算样本点到分割超平面的函数距离
#print (svm2.decision_function(X_train_scaled))
#print (svm2.decision_function(X_trainscaled)[:20]>0)
#支持向量机分类
#print(svm2.classes
)
#malignant和bening概率计算,输出结果包括恶性概率和良性概率
#print(svm2.predict_proba(x_test_scaled))
#判断数据属于哪一类,0或1表示
#print(svm2.predict(x_test_scaled))`

神经网络
效果不如支持向量和随机森林
最好概率


python信用卡评分模型_评分卡_43

#Multi-layer Perceptron 多层感知机from sklearn.neural_network import MLPClassifier#标准化数据,否则神经网络结果不准确,和SVM类似from sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_splitimport mglearnimport matplotlib.pyplot as pltimport numpy as npimport pandas as pd#读取文件readFileName="German_credit.xlsx"#读取exceldf=pd.read_excel(readFileName)
list_columns=list(df.columns[:-1])
x=df.ix[:,:-1]
y=df.ix[:,-1]
names=x.columns#random_state 相当于随机数种子x_train,x_test,y_train,y_test=train_test_split(x,y,stratify=y,random_state=42)
mlp=MLPClassifier(random_state=42)
mlp.fit(x_train,y_train)
print("neural network:")   
print("accuracy on the training subset:{:.3f}".format(mlp.score(x_train,y_train)))
print("accuracy on the test subset:{:.3f}".format(mlp.score(x_test,y_test)))

scaler=StandardScaler()
x_train_scaled=scaler.fit(x_train).transform(x_train)
x_test_scaled=scaler.fit(x_test).transform(x_test)

mlp_scaled=MLPClassifier(max_iter=1000,random_state=42)
mlp_scaled.fit(x_train_scaled,y_train)
print("neural network after scaled:")   
print("accuracy on the training subset:{:.3f}".format(mlp_scaled.score(x_train_scaled,y_train)))
print("accuracy on the test subset:{:.3f}".format(mlp_scaled.score(x_test_scaled,y_test)))

mlp_scaled2=MLPClassifier(max_iter=1000,alpha=1,random_state=42)
mlp_scaled2.fit(x_train_scaled,y_train)
print("neural network after scaled and alpha change to 1:")   
print("accuracy on the training subset:{:.3f}".format(mlp_scaled2.score(x_train_scaled,y_train)))
print("accuracy on the test subset:{:.3f}".format(mlp_scaled2.score(x_test_scaled,y_test)))#绘制颜色图,热图plt.figure(figsize=(20,5))
plt.imshow(mlp_scaled.coefs_[0],interpolation="None",cmap="GnBu")
plt.yticks(range(30),names)
plt.xlabel("columns in weight matrix")
plt.ylabel("input feature")
plt.colorbar()'''
neural network:
accuracy on the training subset:0.700
accuracy on the test subset:0.700
neural network after scaled:
accuracy on the training subset:1.000
accuracy on the test subset:0.704
neural network after scaled and alpha change to 1:
accuracy on the training subset:0.916
accuracy on the test subset:0.720
'''

xgboost

区分能力还可以

AUC: 0.8134
ACC: 0.7720
Recall: 0.9521
F1-score: 0.8480
Precesion: 0.7644

import xgboost as xgb
from sklearn.cross_validation import train_test_split
import pandas as pd
import matplotlib.pylab as plt#读取文件readFileName="German_credit.xlsx"#读取exceldf=pd.read_excel(readFileName)
list_columns=list(df.columns[:-1])
x=df.ix[:,:-1]
y=df.ix[:,-1]
names=x.columns

train_x, test_x, train_y, test_y=train_test_split(x,y,random_state=0)

dtrain=xgb.DMatrix(train_x,label=train_y)
dtest=xgb.DMatrix(test_x)

params={'booster':'gbtree',    #'objective': 'reg:linear',
    'objective': 'binary:logistic',    'eval_metric': 'auc',    'max_depth':4,    'lambda':10,    'subsample':0.75,    'colsample_bytree':0.75,    'min_child_weight':2,    'eta': 0.025,    'seed':0,    'nthread':8,     'silent':1}

watchlist = [(dtrain,'train')]

bst=xgb.train(params,dtrain,num_boost_round=100,evals=watchlist)

ypred=bst.predict(dtest)# 设置阈值, 输出一些评价指标y_pred = (ypred >= 0.5)*1#模型校验from sklearn import metricsprint ('AUC: %.4f' % metrics.roc_auc_score(test_y,ypred))print ('ACC: %.4f' % metrics.accuracy_score(test_y,y_pred))print ('Recall: %.4f' % metrics.recall_score(test_y,y_pred))print ('F1-score: %.4f' %metrics.f1_score(test_y,y_pred))print ('Precesion: %.4f' %metrics.precision_score(test_y,y_pred))
metrics.confusion_matrix(test_y,y_pred)print("xgboost:") 
#print("accuracy on the training subset:{:.3f}".format(bst.get_score(train_x,train_y)))#print("accuracy on the test subset:{:.3f}".format(bst.get_score(test_x,test_y)))print('Feature importances:{}'.format(bst.get_fscore()))'''
AUC: 0.8135
ACC: 0.7640
Recall: 0.9641
F1-score: 0.8451
Precesion: 0.7523

#特征重要性和随机森林差不多
Feature importances:{'Account Balance': 80, 'Duration of Credit (month)': 119,
 'Most valuable available asset': 54, 'Payment Status of Previous Credit': 84,
 'Value Savings/Stocks': 66, 'Age (years)': 94, 'Credit Amount': 149,
 'Type of apartment': 20, 'Instalment per cent': 37,
 'Length of current employment': 70, 'Sex & Marital Status': 29,
 'Purpose': 67, 'Occupation': 13, 'Duration in Current address': 25,
 'Telephone': 15, 'Concurrent Credits': 23, 'No of Credits at this Bank': 7,
 'Guarantors': 28, 'No of dependents': 6}
'''

xgboost 有时候特征重要性分析比随机森林还准确,可见其强大之处

随机森林重要因子排序    xgboost权重指数
Credit amount信用保证金  149
age 年龄                            94
account balance 账户余额 80
duration of credit持卡时间 119 (信用卡逾期时间,每个银行有所不同,以招商银行为例,两个月就会被停卡)

欢迎各位同学学习python信用评分卡建模视频系列教程(附代码, 博主录制)
https://edu.51cto.com/sd/edde1
python信用卡评分模型_模型_44