as_matrix、保存訓練模型


#-*- coding: utf-8 -*-
#構建並測試CART決策樹模型

import pandas as pd #導入數據分析庫
from random import shuffle #導入隨機函數shuffle,用來打亂數據
import matplotlib.pyplot as plt #導入Matplotlib

datafile = '../data/model.xls' #數據名
data = pd.read_excel(datafile) #讀取數據,數據的前三列是特征,第四列是標簽
#print(data)
#      電量趨勢下降指標  線損指標  告警類指標  是否竊漏電
# 0           4     1      1      1
# 1           4     0      4      1
# 2           2     1      1      1
# 3           9     0      0      0
data = data.as_matrix() #將表格轉換為矩陣
#print(data)
# [[4 1 1 1]
#  [4 0 4 1]
#  [2 1 1 1]
shuffle(data) #隨機打亂數據

p = 0.8 #設置訓練數據比例
train = data[:int(len(data)*p),:] #前80%為訓練集
test = data[int(len(data)*p):,:] #后20%為測試集


#構建CART決策樹模型
from sklearn.tree import DecisionTreeClassifier #導入決策樹模型

treefile = '../tmp/tree.pkl' #模型輸出名字
tree = DecisionTreeClassifier() #建立決策樹模型
tree.fit(train[:,:3], train[:,3]) #訓練

#保存模型
from sklearn.externals import joblib
joblib.dump(tree, treefile)

# from cm_plot import * #導入自行編寫的混淆矩陣可視化函數
# cm_plot(train[:,3], tree.predict(train[:,:3])).show() #顯示混淆矩陣可視化結果
#注意到Scikit-Learn使用predict方法直接給出預測結果。


from sklearn.metrics import roc_curve #導入ROC曲線函數

fpr, tpr, thresholds = roc_curve(test[:,3], tree.predict_proba(test[:,:3])[:,1], pos_label=1)
plt.plot(fpr, tpr, linewidth=2, label = 'ROC of CART', color = 'green') #作出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() #顯示作圖結果

 


免責聲明!

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



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