Web安全之機器學習 | 決策樹與隨機森林算法

決策樹算法

1、決策樹算法概述

決策樹表現了對象屬性與對象值之間的一種映射關係。決策樹中每個節點表示某個對象,而每個分叉路徑則代表某個可能的屬性值,每個葉節點則對應從根節點到該葉節點所經歷的路徑所表示的對象值。決策樹可以用於數據分類也可以用於預測。

例如:

from sklearn import  tree

X = [[0, 0], [1, 1]]
Y = [0, 1]
clf = tree.DecisionTreeClassifier()
# 訓練樣本
clf = clf.fit(X, Y)

# 結果預測
print(clf.predict([[2., 2.]]))

打印結果:

[1]

2、示例:決策樹應用

通過導入Scikit-Learn自帶的iris數據集合,使用決策樹算法訓練,並生成可視化決策樹圖:

from sklearn.datasets import load_iris
from sklearn import tree
import pydotplus

# 加載iris數據集
iris = load_iris()
#使用決策樹算法進行訓練,並將訓練得到的決策樹保存成pdf文件
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
dot_data = tree.export_graphviz(clf, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf("photo/iris.pdf")

打開iris.pdf:

如果遇到報錯:pydotplus.graphviz.InvocationException: GraphViz's executables not found

解決方式:(1)先使用pip安裝graphviz:

pip install graphviz

(2)下載GraphViz軟件安裝,下載地址:https://graphviz.gitlab.io/_pages/Download/Download_windows.html

(3)然後將GraphViz的安裝目錄的bin目錄添加到環境變量Path中。

(4)重啓編譯器

 

3、示例:使用決策樹算法檢測POP3暴力破解

from sklearn.model_selection import cross_val_score
from sklearn import tree
import pydotplus

# 加載KDD 99數據集中的數據
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=[]
    w=[]
    y=[]

    # 篩選標記爲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.':
                y.append(1)
            else:
                y.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))
        w.append(v1)
    return w,y

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("photo/iris-dt.pdf")

測試結果準確率約爲99%:

可視化決策樹iris-dt.pdf:

4、示例:使用決策樹算法檢測FTP暴力破解

使用ADFA-LD數據集中FTP暴力破解的相關數據,ADFA-LD系統調用可抽象成向量。

import re
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


def load_one_flle(filename):
    x=[]
    with open(filename) as f:
        line=f.readline()
        line=line.strip('\n')
    return line

# 加載ADFA-LD中的正常樣本數據
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 = os.path.join(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,[])

    # 從攻擊數據集中篩選和FTP暴力破解相關的數據
    for file in allfile:
        if re.match(r"ADFA-LD/Attack_Data_Master/Hydra_FTP_\d",file):
            x.append(load_one_flle(file))
            y.append(1)
    return x,y



if __name__ == '__main__':

    # 特徵化
    x1,y1=load_adfa_training_files("ADFA-LD/Training_Data_Master/")
    x2,y2=load_adfa_hydra_ftp_files("ADFA-LD/Attack_Data_Master/")

    x=x1+x2
    y=y1+y2
    #print x
    vectorizer = CountVectorizer(min_df=1)
    x=vectorizer.fit_transform(x)
    x=x.toarray()
    #print y

    # 訓練樣本
    clf = tree.DecisionTreeClassifier()

    # 十折交叉驗證
    scores = cross_val_score(clf, x, y, n_jobs=-1, cv=10)
    print(scores)
    # 準確率
    print(np.mean(scores))
    
    # 可視化訓練得到的決策樹
    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("photo/ftp.pdf")

測試結果準確率約爲96%:

可視化決策樹:

隨機森林算法概述:

1、隨機森林算法概述:

隨機森林指的是利用多棵樹對樣本進行訓練並預測的一種分類器。隨機森林是用隨機的方式建立一個森林,森林由很多的決策樹組成,隨機森林的每棵樹決策樹之間是沒有關聯的。在得到森林之後,當有一個新的輸入樣本進入的時候,就讓森林中的每棵決策樹分別進行判斷,看看這個樣本屬於哪一類,然後看哪一類被選最多,則預測這個樣本爲那一類。

2、示例:隨機森林應用(一)

  使用同樣的數據集合測試來對比決策樹和隨機森林:


from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_blobs
from sklearn.ensemble import RandomForestClassifier
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())

打印結果:

0.9794087938205586
0.9996078431372549

可大概看出,一般情況下,隨機森林的判決性能優於決策樹。

3、示例:使用隨機森林算法檢測FTP暴力破解

繼續使用ADFA-LD數據集中FTP暴力破解的相關數據。

關鍵代碼:


if __name__ == '__main__':

    x1,y1=load_adfa_training_files("ADFA-LD/Training_Data_Master/")
    x2,y2=load_adfa_hydra_ftp_files("ADFA-LD/Attack_Data_Master/")

    x=x1+x2
    y=y1+y2
    #print x
    vectorizer = CountVectorizer(min_df=1)
    x=vectorizer.fit_transform(x)
    x=x.toarray()

    # 實例化決策樹
    clf1 = tree.DecisionTreeClassifier()
    score=cross_val_score(clf1, x, y, n_jobs=-1, cv=10)
    print(np.mean(score))

    # 實例化隨機森林
    clf2 = RandomForestClassifier(n_estimators=10, max_depth=None,min_samples_split=2, random_state=0)
    score=cross_val_score(clf2, x, y, n_jobs=-1, cv=10)
    print(np.mean(score))

測試結果顯示,決策樹準確率約爲96%,隨機森林準確率約爲98%:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章