決策樹演算法實現(scikit learn)

2022-05-15 12:20:40 字數 3417 閱讀 2438

sk-learn的決策樹文件

決策樹的演算法介紹

在 mac os x 中安裝與使用 graphviz 圖形視覺化工具

決策樹歸納演算法(id3)

優先選擇資訊獲取量最大的屬性作為屬性判斷結點

資訊獲取量(information gain):gain(a) = info(d) - infor_a(d)

age屬性資訊獲取量的計算過程如下所示:

演算法步驟:

(a) 給定結點的所有樣本屬於同一類。

(b) 沒有剩餘屬性可以用來進一步劃分樣本。在此情況下,使用多數表決。這涉及將給定的結點轉換成樹葉,並用樣本中的多數所在的類標記它。替換地,可以存放結點樣本的類分布。

(c) 分枝test_attribute = a,沒有樣本。在這種情況下,以 samples 中的多數類建立乙個樹葉。

決策樹的優缺點

優:直觀,便於理解,小規模資料集有效

缺:處理連續變數不好

類別較多時,錯誤增加的比較快

可規模性一般

資料轉換為 sklearn需要的格式

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# created by xuehz on 2017/3/3

from sklearn.feature_extraction import dictvectorizer # 將字典 轉化為 sklearn 用的資料形式 資料型 矩陣

import csv

from sklearn import preprocessing

from sklearn import tree

from sklearn.externals.six import stringio

allelectronicsdata = open('allelectronics.csv','rb')

reader = csv.reader(allelectronicsdata)

header = reader.next() #['rid', 'age', 'income', 'student', 'credit_rating', 'class_buys_computer']

## 資料預處理

featurelist = #[,

for i in range(1, len(row) - 1):

rowdict[header[i]] = row[i]

# vectorize features

vec = dictvectorizer()

dummyx = vec.fit_transform(featurelist).toarray()

print("dummyx:"+str(dummyx))

print(vec.get_feature_names())

"""[[ 0. 0. 1. 0. 1. 1. 0. 0. 1. 0.]

[ 0. 0. 1. 1. 0. 1. 0. 0. 1. 0.]

['age=middle_aged', 'age=senior', 'age=youth', 'credit_rating=excellent', 'credit_rating=fair', 'income=high', 'income=low', 'income=medium', 'student=no', 'student=yes']

"""# label的轉化,直接用preprocessing的labelbinarizer方法

lb = preprocessing.labelbinarizer()

dummyy = lb.fit_transform(labellist)

print("dummyy:"+str(dummyy))

print("labellist:"+str(labellist))

"""dummyy:[[0]

[0][1]

[1][1]

labellist:['no', 'no', 'yes', 'yes', 'yes', 'no', 'yes', 'no', 'yes', 'yes', 'yes', 'yes', 'yes', 'no']

"""#criterion是選擇決策樹節點的 標準 ,這裡是按照「熵」為標準,即id3演算法;預設標準是gini index,即cart演算法。

clf = tree.decisiontreeclassifier(criterion='entropy')

clf = clf.fit(dummyx,dummyy)

print("clf:"+str(clf))

"""clf:decisiontreeclassifier(class_weight=none, criterion='entropy', max_depth=none,

max_features=none, max_leaf_nodes=none, min_samples_leaf=1,

min_samples_split=2, min_weight_fraction_leaf=0.0,

presort=false, random_state=none, splitter='best')

"""#生成dot檔案

with open("allelectronicinformationgainori.dot",'w') as f:

f = tree.export_graphviz(clf, feature_names= vec.get_feature_names(),out_file= f)

#測試**,取第1個例項資料,將001->100,即age:youth->middle_aged

onerowx = dummyx[0,:]

print("onerowx:"+str(onerowx))

newrowx = onerowx

newrowx[0] = 1

newrowx[2] = 0

print("newrowx:"+str(newrowx))

#****

predictedy = clf.predict(newrowx)

print("predictedy:"+str(predictedy))

生成的 .dot 檔案
digraph tree
將dot檔案用graphviz轉換為pdf檔案

在命令列下,cd到你的dot檔案的路徑下,輸入

dot -tpdf filename.dot -o output.pdf

(filename以dot檔名為準)

機器學習演算法/決策樹

不足之處 請指出

個人部落格:

決策樹演算法 python實現

定義 資訊增益 再劃分資料之前之後資訊發生的變化。香濃熵 簡稱熵 集合資訊的度量方式,熵是資訊的期望值。其實決策樹主要就是選擇最優劃分屬性對給定集合進行劃分,隨著花粉的不斷進行,我們希望最終決策樹所包含的樣本盡量屬於同一類別,即結點的 純度 越來越高。資訊增益的計算 1.資訊熵的計算ent d 越小...

Python實現決策樹演算法

決策樹的一般流程 檢測資料集中的每個子項是否屬於同乙個分類 if so return 類標籤 else 尋找劃分資料集的最好特徵 劃分資料集 建立分支 節點 from math import log import operator 生成樣本資料集 defcreatedataset dataset 1...

決策樹演算法 Python實現

import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import fetch california housing housing fetch california housing print housi...