import pandas as pd
from keras.models import Sequential
from keras.layers.core import Dense, Activation
inputfile = ‘bankloan.xls’
data = pd.read_excel(inputfile) # 导入数据
x = data.iloc[:,:8].values
y = 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’)
model.fit(x, y, epochs = 1000, batch_size = 10) # 训练模型,学习一千次
#yp = model.predict_classes(x).reshape(len(y)) # 分类预测
import numpy as np
predict_x=model.predict(x)
classes_x=np.argmax(predict_x,axis=1)
yp = classes_x.reshape(len(y))
score = model.evaluate(x, y, batch_size=128) #分类预测精确度
print(score)
from cm_plot import * # 导入自行编写的混淆矩阵可视化函数
cm_plot(y,yp).show() # 显示混淆矩阵可视化结果
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
import pandas as pd
filename = ‘bankloan.xls’
data_tr = pd.read_excel(filename)
#print(data_tr) # 导入数据
#训练数据
#读取数据
x_tr = data_tr.iloc[:,:8].astype(int)
y_tr = data_tr.iloc[:,8].astype(int)
from sklearn.tree import DecisionTreeClassifier as DTC
dtc = DTC(criterion=‘entropy’) # 建立决策树模型,基于信息熵
dtc.fit(x_tr, y_tr) # 训练模型
from sklearn.tree import export_graphviz
x = pd.DataFrame(x_tr)
string1 = ‘’’
edge [fontname=“NSimSun”];
node [ fontname=“NSimSun” size=“15,15”];
{
‘’’
string2 = ‘}’
with open(“dt1.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_tr.columns[:8], #对应特征的名字
class_names=data_tr.columns[8], #对应类别的名字
filled=True, rounded=True,
special_characters=True)
#手动修改树结构的字体类型,以免出来的图片出现中文乱码
dot_data = dot_data.replace(‘helvetica’, ‘MicrosoftYaHei’)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_png(‘p.png’) #保存图像
Image(graph.create_png())
#显示决策树图片
import matplotlib.pyplot as plt
img = plt.imread(‘p.png’)
fig = plt.figure(‘show picture’)
plt.imshow(img)