神经网络分析代码如下
import pandas as pd filename = 'C:/Users/透心凉i/Desktop/data/data/bankloan.xls' data_tr = pd.read_excel(filename) #print(data_tr) # 导入数据 #读取数据 x_tr = data_tr.iloc[:,:8] y_tr = data_tr.iloc[:,8] #print(x_tr) #print(y_tr) from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Activation model = Sequential() # 建立模型 model.add(Dense(input_dim = 8, units = 16)) model.add(Activation('relu')) # 用relu函数作为激活函数,能够大幅提供准确度 model.add(Dense(input_dim = 16, units = 32)) model.add(Activation('sigmoid')) model.add(Dense(input_dim = 32, units = 1)) model.add(Activation('sigmoid')) # 由于是0-1输出,用sigmoid函数作为激活函数 model.compile(loss = 'binary_crossentropy', optimizer = 'adam') # 编译模型。由于我们做的是二元分类,所以我们指定损失函数为binary_crossentropy,以及模式为binary # 另外常见的损失函数还有mean_squared_error、categorical_crossentropy等,请阅读帮助文件。 # 求解方法我们指定用adam,还有sgd、rmsprop等可选 model.fit(x_tr, y_tr, epochs = 1000, batch_size = 10) # 训练模型,学习一千次 yp = model.predict(x_tr).reshape(len(y_tr)) # 分类预测 score = model.evaluate(x_tr, y_tr, batch_size=256) #分类预测损失值 print("分类预测损失值") print(score)
结果如图:
决策树分析代码如下:
import pandas as pd # 参数初始化 import pandas as pd import os os.chdir('C:/Users/透心凉i') data = pd.read_excel('bankloan.xls') x = data.iloc[:,:8].astype(int) y = data.iloc[:,8].astype(int) from sklearn.tree import DecisionTreeClassifier as DTC dtc = DTC(criterion='entropy') # 建立决策树模型,基于信息熵 dtc.fit(x, y) # 训练模型 # 导入相关函数,可视化决策树。 # 导出的结果是一个dot文件,需要安装Graphviz才能将它转换为pdf或png等格式。 from sklearn.tree import export_graphviz x = pd.DataFrame(x) with open(r"C:/Users/透心凉i/Desktop/data/tree3.dot", 'w',encoding="utf-8") 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 import os os.environ["PATH"] += os.pathsep + 'C:/Program Files/Graphviz/bin/' 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) dot_data = dot_data.replace('helvetica', 'MicrosoftYaHei') graph = pydotplus.graph_from_dot_data(dot_data) graph.write_png('C:/Users/透心凉i/Desktop/data/example.png') #保存图像 Image(graph.create_png())
结果如下: