1.神经网络
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 = 'data/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) 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)
测试结果:
2.SVM
1 from sklearn import svm 2 from sklearn.metrics import accuracy_score 3 from sklearn.metrics import confusion_matrix 4 from matplotlib import pyplot as plt 5 import pandas as pd 6 import numpy as np 7 import seaborn as sns 8 from sklearn.model_selection import train_test_split 9 data_load = "data/bankloan.xls" 10 data = pd.read_excel(data_load) 11 data.describe() 12 data.columns 13 data.index 14 ## 转为np 数据切割 15 X = np.array(data.iloc[:,0:-1]) 16 y = np.array(data.iloc[:,-1]) 17 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) 18 svm = svm.SVC() 19 svm.fit(X_test,y_test) 20 y_pred = svm.predict(X_test) 21 accuracy_score(y_test, y_pred) 22 print(accuracy_score(y_test, y_pred)) 23 cm = confusion_matrix(y_test, y_pred) 24 heatmap = sns.heatmap(cm, annot=True, fmt='d') 25 heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right') 26 heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right') 27 plt.ylabel("true label") 28 plt.xlabel("predict label") 29 plt.show()
测试结果:
3.决策树
1 import pandas as pd 2 # 参数初始化 3 filename = 'data/bankloan.xls' 4 data = pd.read_excel(filename) # 导入数据 5 6 # 数据是类别标签,要将它转换为数据 8 9 x = data.iloc[:,:8].astype(int) 10 y = data.iloc[:,8].astype(int) 11 12 13 from sklearn.tree import DecisionTreeClassifier as DTC 14 dtc = DTC(criterion='entropy') # 建立决策树模型,基于信息熵 15 dtc.fit(x, y) # 训练模型 16 17 # 导入相关函数,可视化决策树。 18 # 导出的结果是一个dot文件,需要安装Graphviz才能将它转换为pdf或png等格式。 19 from sklearn.tree import export_graphviz 20 x = pd.DataFrame(x) 21 22 """ 23 string1 = ''' 24 edge [fontname="NSimSun"]; 25 node [ fontname="NSimSun" size="15,15"]; 26 { 27 ''' 28 string2 = '}' 29 """ 30 31 with open("data/tree.dot", 'w') as f: 32 export_graphviz(dtc, feature_names = x.columns, out_file = f) 33 f.close() 34 35 36 from IPython.display import Image 37 from sklearn import tree 38 import pydotplus 39 40 dot_data = tree.export_graphviz(dtc, out_file=None, #regr_1 是对应分类器 41 feature_names=data.columns[:8], #对应特征的名字 42 class_names=data.columns[8], #对应类别的名字 43 filled=True, rounded=True, 44 special_characters=True) 45 46 graph = pydotplus.graph_from_dot_data(dot_data) 47 graph.write_png('data/example.png') #保存图像 48 Image(graph.create_png())
测试结果: