银行分控模型的建立
1 '''神经网络测试''' 2 import pandas as pd 3 from keras.models import Sequential 4 from keras.layers.core import Dense, Activation 5 import numpy as np 6 7 # 参数初始化 8 inputfile = 'C:/Users/linji/Desktop/bankloan.xls' 9 data = pd.read_excel(inputfile) 10 x_test = data.iloc[:,:8].values 11 y_test = data.iloc[:,8].values 12 13 model = Sequential() # 建立模型 14 model.add(Dense(input_dim = 8, units = 8)) 15 model.add(Activation('relu')) # 用relu函数作为激活函数,能够大幅提供准确度 16 model.add(Dense(input_dim = 8, units = 1)) 17 model.add(Activation('sigmoid')) # 由于是0-1输出,用sigmoid函数作为激活函数 18 19 model.compile(loss = 'mean_squared_error', optimizer = 'adam') 20 # 编译模型。由于我们做的是二元分类,所以我们指定损失函数为binary_crossentropy,以及模式为binary 21 # 另外常见的损失函数还有mean_squared_error、categorical_crossentropy等,请阅读帮助文件。 22 # 求解方法我们指定用adam,还有sgd、rmsprop等可选 23 24 model.fit(x_test, y_test, epochs = 1000, batch_size = 10) 25 26 predict_x=model.predict(x_test) 27 classes_x=np.argmax(predict_x,axis=1) 28 yp = classes_x.reshape(len(y_test)) 29 30 def cm_plot(y, yp): 31 32 from sklearn.metrics import confusion_matrix #µ¼Èë»ìÏý¾ØÕóº¯Êý 33 34 cm = confusion_matrix(y, yp) #»ìÏý¾ØÕó 35 36 import matplotlib.pyplot as plt #µ¼Èë×÷ͼ¿â 37 plt.matshow(cm, cmap=plt.cm.Greens) #»»ìÏý¾ØÕóͼ£¬ÅäÉ«·ç¸ñʹÓÃcm.Greens£¬¸ü¶à·ç¸ñÇë²Î¿¼¹ÙÍø¡£ 38 plt.colorbar() #ÑÕÉ«±êÇ© 39 40 for x in range(len(cm)): #Êý¾Ý±êÇ© 41 for y in range(len(cm)): 42 plt.annotate(cm[x,y], xy=(x, y), horizontalalignment='center', verticalalignment='center') 43 44 plt.ylabel('True label') #×ø±êÖá±êÇ© 45 plt.xlabel('Predicted label') #×ø±êÖá±êÇ© 46 return plt 47 48 cm_plot(y_test,yp).show()# 显示混淆矩阵可视化结果 49 50 score = model.evaluate(x_test,y_test,batch_size=128) # 模型评估 51 print(score)
1 # -*- coding: utf-8 -*- 2 3 # 代码5-2 4 5 import pandas as pd 6 # 参数初始化 7 filename = 'C:/Users/linji/Desktop/bankloan.xls' 8 data = pd.read_excel(filename) # 导入数据 9 10 # 数据是类别标签,要将它转换为数据 11 # 用1来表示“好”“是”“高”这三个属性,用-1来表示“坏”“否”“低” 12 13 x = data.iloc[:,:8].astype(int) 14 y = data.iloc[:,8].astype(int) 15 16 17 from sklearn.tree import DecisionTreeClassifier as DTC 18 dtc = DTC(criterion='entropy') # 建立决策树模型,基于信息熵 19 dtc.fit(x, y) # 训练模型 20 21 # 导入相关函数,可视化决策树。 22 # 导出的结果是一个dot文件,需要安装Graphviz才能将它转换为pdf或png等格式。 23 from sklearn.tree import export_graphviz 24 x = pd.DataFrame(x) 25 26 """ 27 string1 = ''' 28 edge [fontname="NSimSun"]; 29 node [ fontname="NSimSun" size="15,15"]; 30 { 31 ''' 32 string2 = '}' 33 """ 34 35 with open("C:/Users/linji/Desktop/tree.dot", 'w') as f: 36 export_graphviz(dtc, feature_names = x.columns, out_file = f) 37 f.close() 38 39 40 from IPython.display import Image 41 from sklearn import tree 42 import pydotplus 43 44 dot_data = tree.export_graphviz(dtc, out_file=None, #regr_1 是对应分类器 45 feature_names=data.columns[:8], #对应特征的名字 46 class_names=data.columns[8], #对应类别的名字 47 filled=True, rounded=True, 48 special_characters=True) 49 50 graph = pydotplus.graph_from_dot_data(dot_data) 51 graph.write_png('C:/Users/linji/Desktop/example.png') #保存图像 52 Image(graph.create_png())