国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python決策樹和隨機森林算法實例詳解

2020-01-04 16:01:17
字體:
來源:轉載
供稿:網友

本文實例講述了Python決策樹和隨機森林算法。分享給大家供大家參考,具體如下:

決策樹和隨機森林都是常用的分類算法,它們的判斷邏輯和人的思維方式非常類似,人們常常在遇到多個條件組合問題的時候,也通??梢援嫵鲆活w決策樹來幫助決策判斷。本文簡要介紹了決策樹和隨機森林的算法以及實現,并使用隨機森林算法和決策樹算法來檢測FTP暴力破解和POP3暴力破解,詳細代碼可以參考:

https://github.com/traviszeng/MLWithWebSecurity

決策樹算法

決策樹表現了對象屬性和屬性值之間的一種映射關系。決策樹中的每個節點表示某個對象,而每個分叉路徑則表示某個可能的屬性值,而每個葉節點則對應從根節點到該葉節點所經歷的路徑所表現的對象值。在數據挖掘中,我們常常使用決策樹來進行數據分類和預測。

決策樹的helloworld

在這一小節,我們簡單使用決策樹來對iris數據集進行數據分類和預測。這里我們要使用sklearn下的tree的graphviz來幫助我們導出決策樹,并以pdf的形式存儲。具體代碼如下:

#決策樹的helloworld 使用決策樹對iris數據集進行分類from sklearn.datasets import load_irisfrom sklearn import treeimport pydotplus#導入iris數據集iris = load_iris()#初始化DecisionTreeClassifierclf = tree.DecisionTreeClassifier()#適配數據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數據集得到的可視化決策樹如下圖所示:

Python,決策樹,隨機森林,算法

通過這個小例子,我們可以初步感受到決策樹的工作過程和特點。相較于其他的分類算法,決策樹產生的結果更加直觀也更加符合人類的思維方式。

使用決策樹檢測POP3暴力破解

在這里我們是用KDD99數據集中POP3相關的數據來使用決策樹算法來學習如何識別數據集中和POP3暴力破解相關的信息。關于KDD99數據集的相關內容可以自行google一下。下面是使用決策樹算法的源碼:

#使用決策樹算法檢測POP3暴力破解import reimport matplotlib.pyplot as pltfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.model_selection import cross_val_scoreimport osfrom sklearn.datasets import load_irisfrom sklearn import treeimport pydotplus#加載kdd數據集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#找到訓練數據集def get_guess_passwdandNormal(x):  v=[]  features=[]  targets=[]  #找到標記為guess-passwd和normal且是POP3協議的數據  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密碼破解相關的網絡特征和TCP協議內容的特征作為樣本特征      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,targetsif __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暴力破解的的決策樹如下:

Python,決策樹,隨機森林,算法

隨機森林算法

隨機森林指的是利用多棵樹對樣本進行訓練并預測的一種分類器。是一個包含多個決策樹的分類器,并且其輸出類別是由個別樹輸出的類別的眾數決定的。隨機森林的每一顆決策樹之間是沒有關聯的。在得到森林之后,當有一個新的輸入樣本進入的時候,就讓森林中的每一顆決策樹分別進行判斷,看看這個樣本屬于哪一類,然后看看哪一類被選擇最多,則預測這個樣本為那一類。一般來說,隨機森林的判決性能優于決策樹。

隨機森林的helloworld

接下來我們利用隨機生成的一些數據直觀的看看決策樹和隨機森林的準確率對比:

from sklearn.model_selection import cross_val_scorefrom sklearn.datasets import make_blobsfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.ensemble import ExtraTreesClassifierfrom sklearn.tree import DecisionTreeClassifierX,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("決策樹準確率;",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("隨機森林準確率:",scores.mean())

最后可以看到決策樹的準確率是要稍遜于隨機森林的。

Python,決策樹,隨機森林,算法

使用隨機森林算法檢測FTP暴力破解

接下來我們使用ADFA-LD數據集中關于FTP的數據使用隨機森林算法建立一個隨機森林分類器,ADFA-LD數據集中記錄了函數調用序列,每個文件包含的函數調用的序列個數都不一樣。相關數據集的詳細內容請自行google。

詳細源碼如下:

# -*- coding:utf-8 -*-#使用隨機森林算法檢測FTP暴力破解import reimport matplotlib.pyplot as pltfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.model_selection import cross_val_scoreimport osfrom sklearn import treeimport pydotplusimport numpy as npfrom sklearn.ensemble import RandomForestClassifierdef load_one_flle(filename):  x=[]  with open(filename) as f:    line=f.readline()    line=line.strip('/n')  return linedef 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,ydef 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 allfiledef load_adfa_hydra_ftp_files(rootdir):  x=[]  y=[]  allfile=dirlist(rootdir,[])  for file in allfile:    #正則表達式匹配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,yif __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))

最后可以獲得一個準確率約在98.4%的隨機森林分類器。

希望本文所述對大家Python程序設計有所幫助。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 涿州市| 黑山县| 曲阜市| 宿迁市| 安徽省| 涿鹿县| 华容县| 那曲县| 荣昌县| 怀集县| 阳朔县| 海口市| 乌鲁木齐县| 阳曲县| 南丰县| 阿勒泰市| 大关县| 江城| 漠河县| 兰考县| 乌鲁木齐县| 河西区| 永年县| 昌图县| 林甸县| 益阳市| 颍上县| 长春市| 林州市| 砚山县| 包头市| 新余市| 高要市| 龙井市| 佛山市| 岢岚县| 万全县| 保山市| 青阳县| 德钦县| 阳春市|