欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2018年01月30日 11:05:46   作者:TravisZeng  
這篇文章主要介紹了Python決策樹和隨機森林算法,集合實例形式詳細分析了決策樹和隨機森林算法的概念、原理及Python相關(guān)實現(xiàn)技巧與注意事項,需要的朋友可以參考下

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

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

https://github.com/traviszeng/MLWithWebSecurity

決策樹算法

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

決策樹的helloworld

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

#決策樹的helloworld 使用決策樹對iris數(shù)據(jù)集進行分類
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ù)來使用決策樹算法來學習如何識別數(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
#找到訓練數(shù)據(jù)集
def get_guess_passwdandNormal(x):
  v=[]
  features=[]
  targets=[]
  #找到標記為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暴力破解的的決策樹如下:

隨機森林算法

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

隨機森林的helloworld

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

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("決策樹準確率;",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())

最后可以看到?jīng)Q策樹的準確率是要稍遜于隨機森林的。

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

接下來我們使用ADFA-LD數(shù)據(jù)集中關(guān)于FTP的數(shù)據(jù)使用隨機森林算法建立一個隨機森林分類器,ADFA-LD數(shù)據(jù)集中記錄了函數(shù)調(diào)用序列,每個文件包含的函數(shù)調(diào)用的序列個數(shù)都不一樣。相關(guān)數(shù)據(jù)集的詳細內(nèi)容請自行g(shù)oogle。

詳細源碼如下:

# -*- coding:utf-8 -*-
#使用隨機森林算法檢測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:
    #正則表達式匹配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))

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

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程

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

相關(guān)文章

最新評論