Python決策樹和隨機(jī)森林算法實例詳解
本文實例講述了Python決策樹和隨機(jī)森林算法。分享給大家供大家參考,具體如下:
決策樹和隨機(jī)森林都是常用的分類算法,它們的判斷邏輯和人的思維方式非常類似,人們常常在遇到多個條件組合問題的時候,也通??梢援嫵鲆活w決策樹來幫助決策判斷。本文簡要介紹了決策樹和隨機(jī)森林的算法以及實現(xiàn),并使用隨機(jī)森林算法和決策樹算法來檢測FTP暴力破解和POP3暴力破解,詳細(xì)代碼可以參考:
https://github.com/traviszeng/MLWithWebSecurity
決策樹算法
決策樹表現(xiàn)了對象屬性和屬性值之間的一種映射關(guān)系。決策樹中的每個節(jié)點表示某個對象,而每個分叉路徑則表示某個可能的屬性值,而每個葉節(jié)點則對應(yīng)從根節(jié)點到該葉節(jié)點所經(jīng)歷的路徑所表現(xiàn)的對象值。在數(shù)據(jù)挖掘中,我們常常使用決策樹來進(jìn)行數(shù)據(jù)分類和預(yù)測。
決策樹的helloworld
在這一小節(jié),我們簡單使用決策樹來對iris數(shù)據(jù)集進(jìn)行數(shù)據(jù)分類和預(yù)測。這里我們要使用sklearn下的tree的graphviz來幫助我們導(dǎo)出決策樹,并以pdf的形式存儲。具體代碼如下:
#決策樹的helloworld 使用決策樹對iris數(shù)據(jù)集進(jìn)行分類
from sklearn.datasets import load_iris
from sklearn import tree
import pydotplus
#導(dǎo)入iris數(shù)據(jù)集
iris = load_iris()
#初始化DecisionTreeClassifier
clf = tree.DecisionTreeClassifier()
#適配數(shù)據(jù)
clf = clf.fit(iris.data, iris.target)
#將決策樹以pdf格式可視化
dot_data = tree.export_graphviz(clf, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("iris.pdf")
iris數(shù)據(jù)集得到的可視化決策樹如下圖所示:

通過這個小例子,我們可以初步感受到?jīng)Q策樹的工作過程和特點。相較于其他的分類算法,決策樹產(chǎn)生的結(jié)果更加直觀也更加符合人類的思維方式。
使用決策樹檢測POP3暴力破解
在這里我們是用KDD99數(shù)據(jù)集中POP3相關(guān)的數(shù)據(jù)來使用決策樹算法來學(xué)習(xí)如何識別數(shù)據(jù)集中和POP3暴力破解相關(guān)的信息。關(guān)于KDD99數(shù)據(jù)集的相關(guān)內(nèi)容可以自行g(shù)oogle一下。下面是使用決策樹算法的源碼:
#使用決策樹算法檢測POP3暴力破解
import re
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import cross_val_score
import os
from sklearn.datasets import load_iris
from sklearn import tree
import pydotplus
#加載kdd數(shù)據(jù)集
def load_kdd99(filename):
X=[]
with open(filename) as f:
for line in f:
line = line.strip('\n')
line = line.split(',')
X.append(line)
return X
#找到訓(xùn)練數(shù)據(jù)集
def get_guess_passwdandNormal(x):
v=[]
features=[]
targets=[]
#找到標(biāo)記為guess-passwd和normal且是POP3協(xié)議的數(shù)據(jù)
for x1 in x:
if ( x1[41] in ['guess_passwd.','normal.'] ) and ( x1[2] == 'pop_3' ):
if x1[41] == 'guess_passwd.':
targets.append(1)
else:
targets.append(0)
#挑選與POP3密碼破解相關(guān)的網(wǎng)絡(luò)特征和TCP協(xié)議內(nèi)容的特征作為樣本特征
x1 = [x1[0]] + x1[4:8]+x1[22:30]
v.append(x1)
for x1 in v :
v1=[]
for x2 in x1:
v1.append(float(x2))
features.append(v1)
return features,targets
if __name__ == '__main__':
v=load_kdd99("../../data/kddcup99/corrected")
x,y=get_guess_passwdandNormal(v)
clf = tree.DecisionTreeClassifier()
print(cross_val_score(clf, x, y, n_jobs=-1, cv=10))
clf = clf.fit(x, y)
dot_data = tree.export_graphviz(clf, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("POP3Detector.pdf")
隨后生成的用于辨別是否POP3暴力破解的的決策樹如下:

隨機(jī)森林算法
隨機(jī)森林指的是利用多棵樹對樣本進(jìn)行訓(xùn)練并預(yù)測的一種分類器。是一個包含多個決策樹的分類器,并且其輸出類別是由個別樹輸出的類別的眾數(shù)決定的。隨機(jī)森林的每一顆決策樹之間是沒有關(guān)聯(lián)的。在得到森林之后,當(dāng)有一個新的輸入樣本進(jìn)入的時候,就讓森林中的每一顆決策樹分別進(jìn)行判斷,看看這個樣本屬于哪一類,然后看看哪一類被選擇最多,則預(yù)測這個樣本為那一類。一般來說,隨機(jī)森林的判決性能優(yōu)于決策樹。
隨機(jī)森林的helloworld
接下來我們利用隨機(jī)生成的一些數(shù)據(jù)直觀的看看決策樹和隨機(jī)森林的準(zhǔn)確率對比:
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_blobs
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.tree import DecisionTreeClassifier
X,y = make_blobs(n_samples = 10000,n_features=10,centers = 100,random_state = 0)
clf = DecisionTreeClassifier(max_depth = None,min_samples_split=2,random_state = 0)
scores = cross_val_score(clf,X,y)
print("決策樹準(zhǔn)確率;",scores.mean())
clf = RandomForestClassifier(n_estimators=10,max_depth = None,min_samples_split=2,random_state = 0)
scores = cross_val_score(clf,X,y)
print("隨機(jī)森林準(zhǔn)確率:",scores.mean())
最后可以看到?jīng)Q策樹的準(zhǔn)確率是要稍遜于隨機(jī)森林的。

使用隨機(jī)森林算法檢測FTP暴力破解
接下來我們使用ADFA-LD數(shù)據(jù)集中關(guān)于FTP的數(shù)據(jù)使用隨機(jī)森林算法建立一個隨機(jī)森林分類器,ADFA-LD數(shù)據(jù)集中記錄了函數(shù)調(diào)用序列,每個文件包含的函數(shù)調(diào)用的序列個數(shù)都不一樣。相關(guān)數(shù)據(jù)集的詳細(xì)內(nèi)容請自行g(shù)oogle。
詳細(xì)源碼如下:
# -*- coding:utf-8 -*-
#使用隨機(jī)森林算法檢測FTP暴力破解
import re
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import cross_val_score
import os
from sklearn import tree
import pydotplus
import numpy as np
from sklearn.ensemble import RandomForestClassifier
def load_one_flle(filename):
x=[]
with open(filename) as f:
line=f.readline()
line=line.strip('\n')
return line
def load_adfa_training_files(rootdir):
x=[]
y=[]
list = os.listdir(rootdir)
for i in range(0, len(list)):
path = os.path.join(rootdir, list[i])
if os.path.isfile(path):
x.append(load_one_flle(path))
y.append(0)
return x,y
def dirlist(path, allfile):
filelist = os.listdir(path)
for filename in filelist:
filepath = path+filename
if os.path.isdir(filepath):
#處理路徑異常
dirlist(filepath+'/', allfile)
else:
allfile.append(filepath)
return allfile
def load_adfa_hydra_ftp_files(rootdir):
x=[]
y=[]
allfile=dirlist(rootdir,[])
for file in allfile:
#正則表達(dá)式匹配hydra異常ftp文件
if re.match(r"../../data/ADFA-LD/Attack_Data_Master/Hydra_FTP_\d+/UAD-Hydra-FTP*",file):
x.append(load_one_flle(file))
y.append(1)
return x,y
if __name__ == '__main__':
x1,y1=load_adfa_training_files("../../data/ADFA-LD/Training_Data_Master/")
x2,y2=load_adfa_hydra_ftp_files("../../data/ADFA-LD/Attack_Data_Master/")
x=x1+x2
y=y1+y2
vectorizer = CountVectorizer(min_df=1)
x=vectorizer.fit_transform(x)
x=x.toarray()
#clf = tree.DecisionTreeClassifier()
clf = RandomForestClassifier(n_estimators=10, max_depth=None,min_samples_split=2, random_state=0)
clf = clf.fit(x,y)
score = cross_val_score(clf, x, y, n_jobs=-1, cv=10)
print(score)
print('平均正確率為:',np.mean(score))
最后可以獲得一個準(zhǔn)確率約在98.4%的隨機(jī)森林分類器。
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python 如何對Series中的每一個數(shù)據(jù)做運算
這篇文章主要介紹了python 實現(xiàn)對Series中的每一個數(shù)據(jù)做運算操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
利用Python自制網(wǎng)頁并實現(xiàn)一鍵自動生成探索性數(shù)據(jù)分析報告
這篇文章主要介紹了利用Python自制了網(wǎng)頁并實現(xiàn)一鍵自動生成探索性數(shù)據(jù)分析報告,文章內(nèi)容具有一定的參考價值,需要的小伙伴可以參考一下2022-05-05
python中實現(xiàn)字符串翻轉(zhuǎn)的方法
這篇文章主要介紹了python中實現(xiàn)字符串翻轉(zhuǎn)的方法,代碼很簡單,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-07-07
python3圖片轉(zhuǎn)換二進(jìn)制存入mysql
MYSQL是支持把圖片存入數(shù)據(jù)庫的,也相應(yīng)的有一個專門的字段BLOB (Binary Large Object),即較大的二進(jìn)制對象字段,看下面代碼2013-12-12
Python 快速驗證代理IP是否有效的方法實現(xiàn)
有時候,我們需要用到代理IP,比如在爬蟲的時候,不知道怎么驗證這些IP是不是有效的,本文就介紹一下,感興趣的可以了解一下2021-07-07
python之DataFrame實現(xiàn)excel合并單元格
這篇文章主要為大家詳細(xì)介紹了python之DataFrame實現(xiàn)excel合并單元格,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04

