import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score inputfile = 'E:\\pydata\\data\\bankloan.xls' data = pd.read_excel(inputfile) X = data.drop(columns='违约') y = data['违约'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) model = LogisticRegression() model.fit(X_train, y_train) y_pred = model.predict(X_test) #print('预测值'+y_pred+'\n') score = accuracy_score(y_pred, y_test) #print('准确率'+score+'\n') def cm_plot(y, y_pred): from sklearn.metrics import confusion_matrix #导入混淆矩阵函数 cm = confusion_matrix(y, y_pred) #混淆矩阵 import matplotlib.pyplot as plt #导入作图库 plt.matshow(cm, cmap=plt.cm.Greens) #画混淆矩阵图,配色风格使用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') #坐标轴标签 plt.show() return plt cm_plot(y_test, y_pred) #画混淆矩阵
import pandas as pd from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.layers import Activation, Dense, Dropout inputfile = 'E:\\pydata\\data\\bankloan.xls' data = pd.read_excel(inputfile) X = data.drop(columns='违约') y = data['违约'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) model = Sequential() model.add(Dense(64,input_dim=8,activation='relu')) # Drop防止过拟合的数据处理方式 model.add(Dropout(0.5)) model.add(Dense(64,activation='relu')) model.add(Dropout(0.5)) model.add(Dense(1,activation='sigmoid')) # 编译模型,定义损失函数,优化函数,绩效评估函数 model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # 导入数据进行训练 model.fit(X_train,y_train,epochs=200,batch_size=128) # 模型评估 score = model.evaluate(X_test,y_test,batch_size=128) print(score) def cm_plot(y, y_pred): from sklearn.metrics import confusion_matrix #导入混淆矩阵函数 cm = confusion_matrix(y, y_pred) #混淆矩阵 import matplotlib.pyplot as plt #导入作图库 plt.matshow(cm, cmap=plt.cm.Greens) #画混淆矩阵图,配色风格使用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') #坐标轴标签 plt.show() return plt yp = model.predict(X_test) # 分类预测 yp[yp>0.5]=1 yp[yp<=0.5]=0 cm_plot(y_test, yp)