1. 程式人生 > >資料探勘領域十大經典演算法之—C4.5演算法(超詳細附程式碼)

資料探勘領域十大經典演算法之—C4.5演算法(超詳細附程式碼)

資料探勘十大經典演算法如下:
這裡寫連結內容

簡介

C4.5是決策樹演算法的一種。決策樹演算法作為一種分類演算法,目標就是將具有p維特徵的n個樣本分到c個類別中去。常見的決策樹演算法有ID3,C4.5,CART。

基本思想

下面以一個例子來詳細說明C4.5的基本思想
例子
上述資料集有四個屬性,屬性集合A={ 天氣,溫度,溼度,風速}, 類別標籤有兩個,類別集合L={進行,取消}。

1. 計算類別資訊熵
類別資訊熵表示的是所有樣本中各種類別出現的不確定性之和。根據熵的概念,熵越大,不確定性就越大,把事情搞清楚所需要的資訊量就越多。
這裡寫連結內容

2. 計算每個屬性的資訊熵
每個屬性的資訊熵相當於一種條件熵。他表示的是在某種屬性的條件下,各種類別出現的不確定性之和。屬性的資訊熵越大,表示這個屬性中擁有的樣本類別越不“純”。
這裡寫連結內容

3. 計算資訊增益
資訊增益的 = 熵 - 條件熵,在這裡就是 類別資訊熵 - 屬性資訊熵,它表示的是資訊不確定性減少的程度。如果一個屬性的資訊增益越大,就表示用這個屬性進行樣本劃分可以更好的減少劃分後樣本的不確定性,當然,選擇該屬性就可以更快更好地完成我們的分類目標。

資訊增益就是ID3演算法的特徵選擇指標。
這裡寫連結內容
但是我們假設這樣的情況,每個屬性中每種類別都只有一個樣本,那這樣屬性資訊熵就等於零,根據資訊增益就無法選擇出有效分類特徵。所以,C4.5選擇使用資訊增益率對ID3進行改進。

4.計算屬性分裂資訊度量
用分裂資訊度量來考慮某種屬性進行分裂時分支的數量資訊和尺寸資訊,我們把這些資訊稱為屬性的內在資訊(instrisic information)。資訊增益率用資訊增益 / 內在資訊,會導致屬性的重要性隨著內在資訊的增大而減小(也就是說,如果這個屬性本身不確定性就很大,那我就越不傾向於選取它),這樣算是對單純用資訊增益有所補償。
這裡寫連結內容

5. 計算資訊增益率
(下面寫錯了。。應該是IGR = Gain / H )
這裡寫連結內容

天氣的資訊增益率最高,選擇天氣為分裂屬性。發現分裂了之後,天氣是“陰”的條件下,類別是”純“的,所以把它定義為葉子節點,選擇不“純”的結點繼續分裂。
這裡寫連結內容

在子結點當中重複過程1~5。
至此,這個資料集上C4.5的計算過程就算完成了,一棵樹也構建出來了。

總結演算法流程為:

while (當前節點”不純“)  
	(1)計算當前節點的類別資訊熵Info(D) (以類別取值計算)  
	(2)計算當前節點各個屬性的資訊熵Info(Ai) (以屬性取值下的類別取值計算)  
	(3)計算各個屬性的資訊增益Gain(Ai)=
Info(D)-Info(Ai) (4)計算各個屬性的分類資訊度量H(Ai) (以屬性取值計算) (5)計算各個屬性的資訊增益率IGR(Ai)=Gain(Ai)/H(Ai) end while 當前節點設定為葉子節點

優缺點

優點

產生的分類規則易於理解,準確率較高。

缺點

在構造樹的過程中,需要對資料集進行多次的順序掃描和排序,因而導致演算法的低效。

程式碼

程式碼已在github上實現,這裡也貼出來

# encoding=utf-8

import cv2
import time
import numpy as np
import pandas as pd


from sklearn.cross_validation import train_test_split
from sklearn.metrics import accuracy_score

# 二值化
def binaryzation(img):
    cv_img = img.astype(np.uint8)
    cv2.threshold(cv_img,50,1,cv2.THRESH_BINARY_INV,cv_img)
    return cv_img

def binaryzation_features(trainset):
    features = []

    for img in trainset:
        img = np.reshape(img,(28,28))
        cv_img = img.astype(np.uint8)

        img_b = binaryzation(cv_img)
        # hog_feature = np.transpose(hog_feature)
        features.append(img_b)

    features = np.array(features)
    features = np.reshape(features,(-1,feature_len))

    return features


class Tree(object):
    def __init__(self,node_type,Class = None, feature = None):
        self.node_type = node_type  # 節點型別(internal或leaf)
        self.dict = {} # dict的鍵表示特徵Ag的可能值ai,值表示根據ai得到的子樹 
        self.Class = Class  # 葉節點表示的類,若是內部節點則為none
        self.feature = feature # 表示當前的樹即將由第feature個特徵劃分(即第feature特徵是使得當前樹中資訊增益最大的特徵)

    def add_tree(self,key,tree):
        self.dict[key] = tree

    def predict(self,features): 
        if self.node_type == 'leaf' or (features[self.feature] not in self.dict):
            return self.Class

        tree = self.dict.get(features[self.feature])
        return tree.predict(features)

# 計算資料集x的經驗熵H(x)
def calc_ent(x):
    x_value_list = set([x[i] for i in range(x.shape[0])])
    ent = 0.0
    for x_value in x_value_list:
        p = float(x[x == x_value].shape[0]) / x.shape[0]
        logp = np.log2(p)
        ent -= p * logp

    return ent

# 計算條件熵H(y/x)
def calc_condition_ent(x, y):
    x_value_list = set([x[i] for i in range(x.shape[0])])
    ent = 0.0
    for x_value in x_value_list:
        sub_y = y[x == x_value]
        temp_ent = calc_ent(sub_y)
        ent += (float(sub_y.shape[0]) / y.shape[0]) * temp_ent

    return ent

# 計算資訊增益
def calc_ent_grap(x,y):
    base_ent = calc_ent(y)
    condition_ent = calc_condition_ent(x, y)
    ent_grap = base_ent - condition_ent

    return ent_grap

# C4.5演算法
def recurse_train(train_set,train_label,features):
    
    LEAF = 'leaf'
    INTERNAL = 'internal'

    # 步驟1——如果訓練集train_set中的所有例項都屬於同一類Ck
    label_set = set(train_label)
    if len(label_set) == 1:
        return Tree(LEAF,Class = label_set.pop())

    # 步驟2——如果特徵集features為空
    class_len = [(i,len(list(filter(lambda x:x==i,train_label)))) for i in range(class_num)] # 計算每一個類出現的個數
    (max_class,max_len) = max(class_len,key = lambda x:x[1])
    
    if len(features) == 0:
        return Tree(LEAF,Class = max_class)

    # 步驟3——計算資訊增益,並選擇資訊增益最大的特徵
    max_feature = 0
    max_gda = 0
    D = train_label
    for feature in features:
        # print(type(train_set))
        A = np.array(train_set[:,feature].flat) # 選擇訓練集中的第feature列(即第feature個特徵)
        gda = calc_ent_grap(A,D)
        if calc_ent(A) != 0:  ####### 計算資訊增益比,這是與ID3演算法唯一的不同
            gda /= calc_ent(A)
        if gda > max_gda:
            max_gda,max_feature = gda,feature

    # 步驟4——資訊增益小於閾值
    if max_gda < epsilon:
        return Tree(LEAF,Class = max_class)

    # 步驟5——構建非空子集
    sub_features = list(filter(lambda x:x!=max_feature,features))
    tree = Tree(INTERNAL,feature=max_feature)

    max_feature_col = np.array(train_set[:,max_feature].flat)
    feature_value_list = set([max_feature_col[i] for i in range(max_feature_col.shape[0])]) # 儲存資訊增益最大的特徵可能的取值 (shape[0]表示計算行數)
    for feature_value in feature_value_list:

        index = []
        for i in range(len(train_label)):
            if train_set[i][max_feature] == feature_value:
                index.append(i)

        sub_train_set = train_set[index]
        sub_train_label = train_label[index]

        sub_tree = recurse_train(sub_train_set,sub_train_label,sub_features)
        tree.add_tree(feature_value,sub_tree)

    return tree

def train(train_set,train_label,features):
    return recurse_train(train_set,train_label,features)

def predict(test_set,tree):
    result = []
    for features in test_set:
        tmp_predict = tree.predict(features)
        result.append(tmp_predict)
    return np.array(result)


class_num = 10  # MINST資料集有10種labels,分別是“0,1,2,3,4,5,6,7,8,9”
feature_len = 784  # MINST資料集每個image有28*28=784個特徵(pixels)
epsilon = 0.001  # 設定閾值

if __name__ == '__main__':

    print("Start read data...")

    time_1 = time.time()

    raw_data = pd.read_csv('../data/train.csv', header=0)  # 讀取csv資料
    data = raw_data.values
    
    imgs = data[::, 1::]
    features = binaryzation_features(imgs) # 圖片二值化(很重要,不然預測準確率很低)
    labels = data[::, 0]

    # 避免過擬合,採用交叉驗證,隨機選取33%資料作為測試集,剩餘為訓練集
    train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size=0.33, random_state=0)
    time_2 = time.time()
    print('read data cost %f seconds' % (time_2 - time_1))

    # 通過C4.5演算法生成決策樹
    print('Start training...')
    tree = train(train_features,train_labels,list(range(feature_len)))
    time_3 = time.time()
    print('training cost %f seconds' % (time_3 - time_2))

    print('Start predicting...')
    test_predict = predict(test_features,tree)
    time_4 = time.time()
    print('predicting cost %f seconds' % (time_4 - time_3))
    
    # print("預測的結果為:")
    # print(test_predict)
    for i in range(len(test_predict)):
        if test_predict[i] == None:
            test_predict[i] = epsilon
    score = accuracy_score(test_labels, test_predict)
    print("The accruacy score is %f" % score)

測試資料集為MNIST資料集,獲取地址為train.csv

執行結果

這裡寫連結內容