web安全之机器学习入门——3.2 决策树与随机森林
目录
简介
决策树简单用法
决策树检测P0P3爆破
决策树检测FTP爆破
随机森林检测FTP爆破
简介
决策树和随机森林算法是最常见的分类算法;
决策树,判断的逻辑很多时候和人的思维非常接近。
随机森林算法,利用多棵决策树对样本进行训练并预测的一种分类器,并且其输出的类别是由个别决策树输出的类别的众数决定。
决策树简单用法
使用sklearn自带的iris数据集
# -*- coding: utf- -*-
from sklearn.datasets import load_iris
from sklearn import tree
import pydotplus
"""
如果报错GraphViz's executables not found,手动添加环境变量
"""
import os
os.environ["PATH"] += os.pathsep + 'D:/Program Files (x86)/Graphviz2.38/bin/' #注意修改你的路径
iris = load_iris() 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/6/iris.pdf")

决策树算法检测P0P3爆破
# -*- coding:utf- -*- import re
from sklearn import cross_validation
from sklearn import tree
import pydotplus
import os
os.environ["PATH"] += os.pathsep + 'D:/Program Files (x86)/Graphviz2.38/bin/' #注意修改你的路径 """
收集并清洗数据
"""
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且是P0P3协议的数据
"""
for x1 in x:
if ( x1[] in ['guess_passwd.','normal.'] ) and ( x1[] == 'pop_3' ):
if x1[] == 'guess_passwd.':
y.append()
else:
y.append()
"""
特征化
挑选与p0p3密码破解相关的网络特征以及TCP协议内容的特征作为样本特征
"""
x1 = [x1[]] + x1[:]+x1[:]
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_validation.cross_val_score(clf, x, y, n_jobs=-, cv=)) 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/6/iris-dt.pdf")
准确率达到99%
[ 0.98637602 . . . . . .
. . . ]
可视化结果

决策树算法检测FTP爆破
# -*- coding:utf- -*- import re
import os
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import cross_validation
import os
from sklearn import tree
import pydotplus """ """
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(, len(list)):
path = os.path.join(rootdir, list[i])
if os.path.isfile(path):
x.append(load_one_flle(path))
y.append()
return x,y """
定义遍历目录下文件的函数,作为load_adfa_hydra_ftp_files的子函数
"""
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 """
从攻击数据集中筛选和FTP爆破相关的数据
"""
def load_adfa_hydra_ftp_files(rootdir):
x=[]
y=[]
allfile=dirlist(rootdir,[])
for file in allfile:
"""
rootdir下有多个文件,多个文件里又有多个文件
"""
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()
return x,y if __name__ == '__main__':
"""
特征化
由于ADFA-LD数据集都记录了函数调用的序列,每个文件包含的函数调用序列的个数都不一致
"""
x1,y1=load_adfa_training_files("../data/ADFA-LD/Training_Data_Master/")
#x1{2184×833} y1{833}
x2,y2=load_adfa_hydra_ftp_files("../data/ADFA-LD/Attack_Data_Master/")
#x2{524×162} y2{162} x=x1+x2
y=y1+y2
#x{2184×995} y{955}
vectorizer = CountVectorizer(min_df=)
#min_df如果某个词的document frequence小于min_df,则这个词不会被当作关键词
x=vectorizer.fit_transform(x)
x=x.toarray()
#x{142×955}
#实例化决策树算法
clf = tree.DecisionTreeClassifier()
#效果验证
print(cross_validation.cross_val_score(clf, x, y, n_jobs=-, cv=)) 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/6/ftp.pdf")
[ . 0.98019802 0.95 0.97979798 0.96969697 0.88888889
0.98989899 0.95959596 0.92929293 0.95959596]

随机森林算法检测FTP爆破
# -*- coding:utf- -*-
#pydotplus只支持决策树
import re
import os
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import cross_validation
import os
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier
import numpy as np 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(, len(list)):
path = os.path.join(rootdir, list[i])
if os.path.isfile(path):
x.append(load_one_flle(path))
y.append()
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,[])
for file in allfile:
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()
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
#print(x)
vectorizer = CountVectorizer(min_df=)
x=vectorizer.fit_transform(x)
x=x.toarray()
#print(y)
#选用决策树分类器
clf1 = tree.DecisionTreeClassifier()
score=cross_validation.cross_val_score(clf1, x, y, n_jobs=-, cv=)
print('决策树',np.mean(score))
#选用随机森林分类器
clf2 = RandomForestClassifier(n_estimators=, max_depth=None,min_samples_split=, random_state=)
score=cross_validation.cross_val_score(clf2, x, y, n_jobs=-, cv=)
print('随机森林',np.mean(score))
决策树 0.955736173617
随机森林 0.984888688869
web安全之机器学习入门——3.2 决策树与随机森林的更多相关文章
- web安全之机器学习入门——3.1 KNN/k近邻
		
目录 sklearn.neighbors.NearestNeighbors 参数/方法 基础用法 用于监督学习 检测异常操作(一) 检测异常操作(二) 检测rootkit 检测webshell skl ...
 - R语言︱决策树族——随机森林算法
		
每每以为攀得众山小,可.每每又切实来到起点,大牛们,缓缓脚步来俺笔记葩分享一下吧,please~ --------------------------- 笔者寄语:有一篇<有监督学习选择深度学习 ...
 - [ML学习笔记] 决策树与随机森林(Decision Tree&Random Forest)
		
[ML学习笔记] 决策树与随机森林(Decision Tree&Random Forest) 决策树 决策树算法以树状结构表示数据分类的结果.每个决策点实现一个具有离散输出的测试函数,记为分支 ...
 - 逻辑斯蒂回归VS决策树VS随机森林
		
LR 与SVM 不同 1.logistic regression适合需要得到一个分类概率的场景,SVM则没有分类概率 2.LR其实同样可以使用kernel,但是LR没有support vector在计 ...
 - web安全之机器学习入门——2.机器学习概述
		
目录 0 前置知识 什么是机器学习 机器学习的算法 机器学习首先要解决的两个问题 一些基本概念 数据集介绍 1 正文 数据提取 数字型 文本型 数据读取 0 前置知识 什么是机器学习 通过简单示例来理 ...
 - 什么是机器学习的分类算法?【K-近邻算法(KNN)、交叉验证、朴素贝叶斯算法、决策树、随机森林】
		
1.K-近邻算法(KNN) 1.1 定义 (KNN,K-NearestNeighbor) 如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类 ...
 - Python数据科学手册-机器学习: 决策树与随机森林
		
无参数 算法 随机森林 随机森林是一种集成方法,集成多个比较简单的评估器形成累计效果. 导入标准程序库 随机森林的诱因: 决策树 随机森林是建立在决策树 基础上 的集成学习器 建一颗决策树 二叉决策树 ...
 - chapter02 三种决策树模型:单一决策树、随机森林、GBDT(梯度提升决策树) 预测泰坦尼克号乘客生还情况
		
单一标准的决策树:会根每维特征对预测结果的影响程度进行排序,进而决定不同特征从上至下构建分类节点的顺序.Random Forest Classifier:使用相同的训练样本同时搭建多个独立的分类模型, ...
 - 美团店铺评价语言处理以及分类(tfidf,SVM,决策树,随机森林,Knn,ensemble)
		
第一篇 数据清洗与分析部分 第二篇 可视化部分, 第三篇 朴素贝叶斯文本分类 支持向量机分类 支持向量机 网格搜索 临近法 决策树 随机森林 bagging方法 import pandas as pd ...
 
随机推荐
- SSM的搭建
			
1.首先是工具的准备. eclipse jdk1.7 maven 3.5.4 tomcat 8.5 2.工具环境的搭建 首先,new建立选择maven project工程,勾选simple proje ...
 - ServerSocket详解及线程阻塞_03
			
ServerSocket详解构造方法ServerSocket()ServerSocket(int port)ServerSocket(int port ,int backlog)serverSocke ...
 - 《用Python做HTTP接口测试》练习资料共享
			
原作者代码在https://github.com/akuing/python-http-interface-test
 - 日常杂记——C#验证码
			
随机生成验证码,不能以图片的形式存在,所以需要将验证码图片以MemoryStream形式存储在内存的流当中,但是在使用时发现使用PictureBox控件无法显示内存流,所以需要先将流转化为图片,才可以 ...
 - time_wait的快速回收和重用
			
TCP四次挥手: Time_wait产生原因及作用: 1. time_wait状态如何产生? 由上面的变迁图,首先调用close()发起主动关闭的一方,在发送最后一个ACK之后会进入time_wait ...
 - vue-cli使用vux时报错处理,“You may need an appropriate loader to handle this file type”
			
先说解决方案: 在项目中找到build,找到webpack.base.conf.js 将vux给出的解决方案代码拷贝出来 const vuxLoader = require('vux-loader') ...
 - 浅谈Tomcat和Servlet
			
本文浅谈下对Tomcat和Servlet总体的理解,初学时有用过一段时间,但当时疲于应对如何xml配置和使用,对他们的理解就像是一个黑匣子.现在回顾一下帮助自己加深网络的理解.开始还是先推荐我看的文章 ...
 - keil的自动补全功能
			
设置完之后,在.c文件上试一下,发现还是不能自动补全. 后来去各种贴吧里找到了答案,是我的.c文件还没有保存到工程文件中去,所以不能实现这个功能.
 - Python中的进程
			
进程 from multiprocessing import Process import time def start(name): time.sleep(1) print('hello', nam ...
 - 分布式系统里session同步
			
https://blog.csdn.net/xyw591238/article/details/51644315