
數(shù)據(jù)挖掘之決策樹歸納算法的Python實現(xiàn)
引自百度:決策樹算法是一種逼近離散函數(shù)值的方法。它是一種典型的分類方法,首先對數(shù)據(jù)進行處理,利用歸納算法生成可讀的規(guī)則和決策樹,然后使用決策對新數(shù)據(jù)進行分析。本質(zhì)上決策樹是通過一系列規(guī)則對數(shù)據(jù)進行分類的過程
決策樹的算法原理:
(1)通過把實例從根節(jié)點開始進行排列到某個葉子節(jié)點來進行分類的。
(2)葉子節(jié)點即為實例所屬的分類的,樹上的每個節(jié)點說明了實例的屬性。
(3)樹的生成,開始的所有數(shù)據(jù)都在根節(jié)點上,然后根據(jù)你所設(shè)定的標(biāo)準(zhǔn)進行分類,用不同的測試屬性遞歸進行數(shù)據(jù)分析。
決策樹的實現(xiàn)主要思路如下:
(1)先計算整體類別的熵
(2)計算每個特征將訓(xùn)練數(shù)據(jù)集分割成的每個子集的熵,并將這個熵乘以每個子集相對于這個訓(xùn)練集的頻率,最后將這些乘積累加,就會得到一個個特征對應(yīng)的信息增益。
(3)選擇信息增益最大的作為最優(yōu)特征分割訓(xùn)練數(shù)據(jù)集
(4)遞歸上述過程
(5)遞歸結(jié)束條件:訓(xùn)練集的所有實例屬于同一類;或者所有特征已經(jīng)使用完畢。
代碼如下:
[python] view plain copy
#!/usr/bin/python
#coding=utf-8
import operator
import math
#定義訓(xùn)練數(shù)據(jù)集
def createDataSet():
#用書上圖8.2的數(shù)據(jù)
dataSet = [
['youth', 'no', 'no', 'no'],
['youth', 'yes', 'no', 'yes'],
['youth', 'yes', 'yes', 'yes'],
['middle_aged', 'no', 'no', 'no'],
['middle_aged', 'no', 'yes', 'no'],
['senior', 'no', 'excellent', 'yes'],
['senior', 'no', 'fair', 'no']
]
labels = ['age', 'student', 'credit_rating']
return dataSet, labels
#實現(xiàn)熵的計算
def calShannonEnt(dataSet):
numEntries = len(dataSet)
labelCounts = {}
for featVect in dataSet:
currentLabel = featVect[-1]
if currentLabel not in labelCounts:
labelCounts[currentLabel] = 0
labelCounts[currentLabel] += 1
shannonEnt = 0.0
for key in labelCounts:
prob = float(labelCounts[key]) / numEntries
shannonEnt -= prob * math.log(prob, 2)
return shannonEnt
#分割訓(xùn)練數(shù)據(jù)集
def splitDataSet(dataSet, axis, value):
retDataSet = []
for featVec in dataSet:
if featVec[axis] == value:
reducedFeatVec = featVec[:axis]
reducedFeatVec.extend(featVec[axis+1:])
retDataSet.append(reducedFeatVec)
return retDataSet
#一個確定“最好地”劃分?jǐn)?shù)據(jù)元組為個體類的分裂準(zhǔn)則的過程
def Attribute_selection_method(dataSet):
numFeatures = len(dataSet[0]) - 1
baseEntropy = calShannonEnt(dataSet)
bestInfoGain = 0.0
bestFeature = -1
for i in range(numFeatures):
featList = [example[i] for example in dataSet]
uniqueValue = set(featList)
newEntropy = 0.0
for value in uniqueValue:
subDataSet = splitDataSet(dataSet, i, value)
prob = len(subDataSet) / len(dataSet)
newEntropy += prob * calShannonEnt(subDataSet)
infoGain = baseEntropy - newEntropy
if infoGain > bestInfoGain:
bestInfoGain = infoGain
bestFeature = i
return bestFeature
#采用majorityvote策略,選擇當(dāng)前訓(xùn)練集中實例數(shù)最大的類
def majorityCnt(classList):
classCount = {}
for vote in classList:
if vote not in classCount.keys():
classCount[vote] = 0
classCount[vote] += 1
sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
#創(chuàng)建決策樹
def Generate_decision_tree(dataSet, labels):
classList = [example[-1] for example in dataSet]
# 訓(xùn)練集所有實例屬于同一類
if classList.count(classList[0]) == len(classList):
return classList[0]
# 訓(xùn)練集的所有特征使用完畢,當(dāng)前無特征可用
if len(dataSet[0]) == 1:
return majorityCnt(classList)
bestFeat = Attribute_selection_method(dataSet)
bestFeatLabel = labels[bestFeat]
myTree = {bestFeatLabel: {}}
del(labels[bestFeat])
featValues = [example[bestFeat] for example in dataSet]
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:]
myTree[bestFeatLabel][value] = Generate_decision_tree(splitDataSet(dataSet, bestFeat, value), subLabels)
return myTree
def main():
print ' ____ _ _ _____ '
print ' | _ \ ___ ___(_)___(_) ___ _ _|_ _| __ ___ ___ '
print ''''' | | | |/ _ \/ __| / __| |/ _ \| '_ \| || '__/ _ \/ _ \\'''
print ' | |_| | __/ (__| \__ \ | (_) | | | | || | | __/ __/'
print ' |____/ \___|\___|_|___/_|\___/|_| |_|_||_| \___|\___|決策樹'
print
myDat, labels = createDataSet()
myTree = Generate_decision_tree(myDat, labels)
print '[*]生成的決策樹:\n',myTree
if __name__ == '__main__':
main()
這里的數(shù)據(jù)也是使用書上的(《數(shù)據(jù)挖掘概念與技術(shù) 第三版》)。
運行結(jié)果:
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動決策的時代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計的實用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時代,BI ...
2025-07-10SQL 在預(yù)測分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢預(yù)判? ? 在數(shù)據(jù)驅(qū)動決策的時代,預(yù)測分析作為挖掘數(shù)據(jù)潛在價值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點,而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報考到取證的全攻略? 在數(shù)字經(jīng)濟蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗:捕捉數(shù)據(jù)背后的時間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢性檢驗如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗:數(shù)據(jù)趨勢與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢變化以及識別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對策略? 長短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨特的門控機制,在 ...
2025-07-07統(tǒng)計學(xué)方法在市場調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場調(diào)研是企業(yè)洞察市場動態(tài)、了解消費者需求的重要途徑,而統(tǒng)計學(xué)方法則是市場調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03