行分控模型的建立

数据预处理:

# -*- coding: utf-8 -*-
"""
Created on Tue Mar 29 18:52:22 2022

@author: 86150
"""

#-*- coding: utf-8 -*-
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) #画混淆矩阵图,配色风格使用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
Vie
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 29 18:52:22 2022

@author: 86150
"""

#-*- coding: utf-8 -*-
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) #画混淆矩阵图,配色风格使用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

 

w Code

 

二、神经网络算法建立模型

 

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Tue Mar 29 18:55:21 2022
 4 
 5 @author: 86150
 6 """
 7 
 8 import pandas as pd
 9 import numpy as np
10 #导入划分数据集函数
11 from sklearn.linear_model import LogisticRegression as LR
12 from sklearn.model_selection import train_test_split
13 #读取数据
14 datafile = 'data5/bankloan.xls'#文件路径
15 data = pd.read_excel(datafile)
16 x = data.iloc[:,:8]
17 y = data.iloc[:,8]
18 #划分数据集
19 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=100)
20 #导入模型和函数
21 from tensorflow.keras.models import Sequential
22 from tensorflow.keras.layers import Dense,Dropout
23 #导入指标
24 from tensorflow.keras.metrics import BinaryAccuracy
25 #导入时间库计时
26 import time
27 start_time = time.time()
28 #-------------------------------------------------------#
29 model = Sequential()
30 model.add(Dense(input_dim=8,units=800,activation='relu'))#激活函数relu
31 model.add(Dropout(0.5))#防止过拟合的掉落函数
32 model.add(Dense(input_dim=800,units=400,activation='relu'))
33 model.add(Dropout(0.5))
34 model.add(Dense(input_dim=400,units=1,activation='sigmoid'))
35  
36 model.compile(loss='binary_crossentropy', optimizer='adam',metrics=[BinaryAccuracy()])
37 model.fit(x_train,y_train,epochs=100,batch_size=128)    #调参 epochs:训练次数,此处为100次
38 loss,binary_accuracy = model.evaluate(x,y,batch_size=128)
39 #--------------------------------------------------------#
40 end_time = time.time()
41 run_time = end_time-start_time#运行时间
42  
43 print('模型运行时间:{}'.format(run_time))
44 print('模型损失值:{}'.format(loss))
45 print('模型精度:{}'.format(binary_accuracy))
46  
47 yp = model.predict(x).reshape(len(y))
48 yp = np.around(yp,0).astype(int) #转换为整型
49 from cm_plot import *  # 导入自行编写的混淆矩阵可视化函数
50  
51 cm_plot(y,yp).show()  # 显示混淆矩阵可视化结果

 

 

三、SVM支持向量机算法模型

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Tue Mar 29 19:08:49 2022
 4 
 5 @author: 86150
 6 """
 7 
 8 from sklearn import svm
 9 from sklearn.metrics import accuracy_score
10 from sklearn.metrics import confusion_matrix
11 from matplotlib import pyplot as plt
12 import seaborn as sns
13 import pandas as pd
14 import numpy as np
15 from sklearn.model_selection import train_test_split
16 data_load = "data5/bankloan.xls"
17 data = pd.read_excel(data_load)
18 data.describe()
19 data.columns
20 data.index
21 ## 转为np 数据切割
22 X = np.array(data.iloc[:,0:-1])
23 y = np.array(data.iloc[:,-1])
24 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)
25 svm = svm.SVC()
26 svm.fit(X_test,y_test)
27 y_pred = svm.predict(X_test)
28 accuracy_score(y_test, y_pred)
29 print(accuracy_score(y_test, y_pred))
30 cm = confusion_matrix(y_test, y_pred)
31 heatmap = sns.heatmap(cm, annot=True, fmt='d')
32 heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right')
33 heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right')
34 plt.ylabel("true label")
35 plt.xlabel("predict label")
36 plt.show()

 

posted @ 2022-03-29 19:19  菜鸟小陈狠菜  阅读(36)  评论(0)    收藏  举报