利用LM神經網絡和決策樹去分類


# -*- coding: utf-8 -*-
import pandas as pd
from scipy.interpolate import lagrange
from matplotlib import pyplot as plt
from random import shuffle
from keras.models import Sequential #導入神經網絡初始化函數
from keras.layers.core import Dense, Activation #導入神經網絡層函數、激活函數
# inputfile='F:\\python數據挖掘\\chapter6\\chapter6\\demo\\data\\missing_data.xls'
# outputfile='F:\\python數據挖掘\\chapter6\\chapter6\\demo\\tmp\\missing_data_sale.xls'
# data=pd.read_excel(inputfile,header=None)

datafile = 'F:\\python數據挖掘\\chapter6\\chapter6\\demo\\data\\model.xls'
data = pd.read_excel(datafile)
#print(data)
#print(type(data))
data = data.as_matrix()#轉換成矩陣或者是數組型,對數據進行操作。
shuffle(data)#隨機擾亂數據
#print(data)

p = 0.8 #設置訓練數據比例
train = data[:int(len(data)*p),:]
test = data[int(len(data)*p):,:]
#
#
netfile = 'F:\\python數據挖掘\\chapter6\\chapter6\\demo\\tmp\\net.model1' #構建的神經網絡模型存儲路徑
#
net = Sequential() #建立神經網絡
net.add(Dense(input_dim=3,output_dim=10)) #添加輸入層(3節點)到隱藏層(10節點)的連接
#net.add(Dense(32, input_dim=16))
net.add(Activation('relu')) #隱藏層使用relu激活函數
net.add(Dense(input_dim=10, output_dim=1)) #添加隱藏層(10節點)到輸出層(1節點)的連接
net.add(Activation('sigmoid')) #輸出層使用sigmoid激活函數
net.compile(loss = 'binary_crossentropy', optimizer = 'adam', class_mode = "binary") #編譯模型,使用adam方法求解

net.fit(train[:,:3], train[:,3], nb_epoch=2, batch_size=1) #訓練模型,循環1000次,Keras模塊中的batch_size指的就是小批量梯度下降法。
net.save_weights(netfile) #保存模型

#predict_result = net.predict_classes(train[:,:3]).reshape(len(train)) #預測結果變形
'''這里要提醒的是,keras用predict給出預測概率,predict_classes才是給出預測類別,而且兩者的預測結果都是n x 1維數組,而不是通常的 1 x n'''
#
# from cm_plot import * #導入自行編寫的混淆矩陣可視化函數
# cm_plot(train[:,3], predict_result).show() #顯示混淆矩陣可視化結果
#
from sklearn.metrics import roc_curve #導入ROC曲線函數
#
predict_result = net.predict(test[:,:3]).reshape(len(test))
fpr, tpr, thresholds = roc_curve(test[:,3], predict_result, pos_label=1)
print(fpr,tpr)
plt.plot(fpr, tpr, linewidth=2, label = 'ROC of LM') #作出ROC曲線
plt.xlabel('False Positive Rate') #坐標軸標簽
plt.ylabel('True Positive Rate') #坐標軸標簽
plt.ylim(0,1.05) #邊界范圍
plt.xlim(0,1.05) #邊界范圍
plt.legend(loc=4) #圖例
plt.show() #顯示作圖結果

結果畫出的圖如上面所示。

主要步驟為:

第一:從原始數據中隨機性的抽取數據,然后進行數據探索分析數據,數據探索分析包括:

1.數據清洗

2.缺失值處理

3.數據變換

第二:建模樣本數據

1.模型訓練

2.模型評價

第三:預處理后診斷數據

第四:自動診斷

第五:根據診斷結果進行模型的優化與重構

最后,再進行模型的訓練和評價。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM