Python数据挖掘----银行分控模型的建立
2022/3/30 1:56:24
本文主要是介绍Python数据挖掘----银行分控模型的建立,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
数据初始化
import pandas as pd from keras.models import Sequential from keras.layers.core import Dense, Activation import numpy as np # 参数初始化 inputfile = 'E:\\the_6_school_year\\python\\data\\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) predict_x=model.predict(x_test) classes_x=np.argmax(predict_x,axis=1) yp = classes_x.reshape(len(y_test)) 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 cm_plot(y_test,yp).show()# 显示混淆矩阵可视化结果 score = model.evaluate(x_test,y_test,batch_size=128) # 模型评估 print(score)
模型评估结果
混淆矩阵可视化结果
SVM支持向量机
import pandas as pd import numpy as np from sklearn import svm from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from matplotlib import pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split data_load = "E:\\the_6_school_year\\python\\data\\bankloan.xls" data = pd.read_excel(data_load) data.describe() data.columns data.index ## 转为np 数据切割 X = np.array(data.iloc[:,0:-1]) y = np.array(data.iloc[:,-1]) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, train_size=0.8, test_size=0.2, shuffle=True) svm = svm.SVC() svm.fit(X_test,y_test) y_pred = svm.predict(X_test) accuracy_score(y_test, y_pred) print(accuracy_score(y_test, y_pred)) cm = confusion_matrix(y_test, y_pred) heatmap = sns.heatmap(cm, annot=True, fmt='d') heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right') heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right') plt.ylabel("true label") plt.xlabel("predict label") plt.show()
可视化结果
决策树
# -*- coding: utf-8 -*- """ Created on Wed Mar 30 01:21:35 2022 @author: Tong Liu """ import pandas as pd from sklearn.tree import DecisionTreeClassifier as DTC from sklearn.tree import export_graphviz from IPython.display import Image from sklearn import tree import pydotplus # 参数初始化 filename = 'E:\\the_6_school_year\\python\\data\\bankloan.xls' data = pd.read_excel(filename) # 导入数据 # 数据是类别标签,要将它转换为数据 x = data.iloc[:,:8].astype(int) y = data.iloc[:,8].astype(int) dtc = DTC(criterion='entropy') # 建立决策树模型,基于信息熵 dtc.fit(x, y) # 训练模型 # 导入相关函数,可视化决策树。 x = pd.DataFrame(x) with open("E:\\the_6_school_year\\python\\data\\tree.dot", 'w') as f: export_graphviz(dtc, feature_names = x.columns, out_file = f) f.close() 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) graph = pydotplus.graph_from_dot_data(dot_data) graph.write_png('E:\\the_6_school_year\\python\\data\\example2.png') #保存图像 Image(graph.create_png())
这篇关于Python数据挖掘----银行分控模型的建立的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型
- 2024-12-23使用python部署一个usdt合约,部署自己的usdt稳定币
- 2024-12-20Python编程入门指南
- 2024-12-20Python编程基础与进阶
- 2024-12-19Python基础编程教程
- 2024-12-19python 文件的后缀名是什么 怎么运行一个python文件?-icode9专业技术文章分享
- 2024-12-19使用python 把docx转为pdf文件有哪些方法?-icode9专业技术文章分享
- 2024-12-19python怎么更换换pip的源镜像?-icode9专业技术文章分享