银行风控模型
一、决策树
代码如下:
# -*- coding: utf-8 -*- """ Created on Sun Mar 27 00:01:20 2022 @author: dd """ import pandas as pd # 参数初始化 filename ='D:/ISS/anaconda/bankloan.xls' data = pd.read_excel(filename) # 导入数据 x = data.iloc[:,:8].astype(int) y = data.iloc[:,8].astype(int) from sklearn.tree import DecisionTreeClassifier as DTC dtc = DTC(criterion='entropy') # 建立决策树模型,基于信息熵 dtc.fit(x, y) # 训练模型 # 导入相关函数,可视化决策树。 # 导出的结果是一个dot文件,需要安装Graphviz才能将它转换为pdf或png等格式。 from sklearn.tree import export_graphviz x = pd.DataFrame(x) """ string1 = ''' edge [fontname="NSimSun"]; node [ fontname="NSimSun" size="15,15"]; { ''' string2 = '}' """ with open("tree.dot", 'w') as f: export_graphviz(dtc, feature_names = x.columns, out_file = f) f.close() from IPython.display import Image from sklearn import tree import pydotplus dot_data = tree.export_graphviz(dtc, out_file=None, #regr_1 是对应分类器 feature_names=data.columns[:8], #对应特征的名字 class_names=data.columns[8], #对应类别的名字 filled=True, rounded=True, special_characters=True) dot_data = dot_data.replace('helvetica 14', 'MicrosoftYaHei 14') #修改字体 graph = pydotplus.graph_from_dot_data(dot_data) graph.write_png('D:/ISS/anaconda/tmp/banktree.png') #保存图像 Image(graph.create_png()) import matplotlib.pyplot as plt img = plt.imread('D:/ISS/anaconda/tmp/banktree.png') fig = plt.figure('show picture') plt.imshow(img)
结果如下:
二、神经网络
代码如下:
# -*- coding: utf-8 -*- """ Created on Sun Mar 27 00:04:18 2022 @author: dd """ import pandas as pd from tensorflow.python.keras.models import Sequential from tensorflow.python.keras.layers.core import Dense, Activation # 参数初始化 inputfile = 'D:/ISS/anaconda/bankloan.xls' data = pd.read_excel(inputfile) x_test = data.iloc[:,:8].values y_test = data.iloc[:,8].values model = Sequential() # 建立模型 model.add(Dense(input_dim = 8, units = 8)) model.add(Activation('relu')) # 用relu函数作为激活函数,能够大幅提供准确度 model.add(Dense(input_dim = 8, units = 1)) model.add(Activation('sigmoid')) # 由于是0-1输出,用sigmoid函数作为激活函数 model.compile(loss = 'mean_squared_error', optimizer = 'adam') # 编译模型。由于我们做的是二元分类,所以我们指定损失函数为binary_crossentropy,以及模式为binary # 另外常见的损失函数还有mean_squared_error、categorical_crossentropy等,请阅读帮助文件。 # 求解方法我们指定用adam,还有sgd、rmsprop等可选 model.fit(x_test, y_test, epochs = 1000, batch_size = 10) # 训练模型,学习一千次 import numpy as np predict_x=model.predict(x_test) classes_x=np.argmax(predict_x,axis=1) yp = classes_x.reshape(len(y_test)) score = model.evaluate(x_test, y_test, batch_size=128) #分类预测精确度 print(score) from cm_plot import * # 导入自行编写的混淆矩阵可视化函数 cm_plot(y_test,yp).show()
其中,绘制混淆矩阵的函数cm_plot.py具体代码如下:
#-*- coding: utf-8 -*- def cm_plot(y, yp): from sklearn.metrics import confusion_matrix cm = confusion_matrix(y, yp) import matplotlib.pyplot as plt plt.matshow(cm, cmap=plt.cm.Greens) plt.colorbar() for x in range(len(cm)): for y in range(len(cm)): plt.annotate(cm[x,y], xy=(x, y), horizontalalignment='center', verticalalignment='center') plt.ylabel('True label') plt.xlabel('Predicted label') return plt
结果如下:
混淆矩阵如下: