
數(shù)據(jù)挖掘之決策樹歸納算法的Python實(shí)現(xiàn)
引自百度:決策樹算法是一種逼近離散函數(shù)值的方法。它是一種典型的分類方法,首先對(duì)數(shù)據(jù)進(jìn)行處理,利用歸納算法生成可讀的規(guī)則和決策樹,然后使用決策對(duì)新數(shù)據(jù)進(jìn)行分析。本質(zhì)上決策樹是通過一系列規(guī)則對(duì)數(shù)據(jù)進(jìn)行分類的過程
決策樹的算法原理:
(1)通過把實(shí)例從根節(jié)點(diǎn)開始進(jìn)行排列到某個(gè)葉子節(jié)點(diǎn)來進(jìn)行分類的。
(2)葉子節(jié)點(diǎn)即為實(shí)例所屬的分類的,樹上的每個(gè)節(jié)點(diǎn)說明了實(shí)例的屬性。
(3)樹的生成,開始的所有數(shù)據(jù)都在根節(jié)點(diǎn)上,然后根據(jù)你所設(shè)定的標(biāo)準(zhǔn)進(jìn)行分類,用不同的測(cè)試屬性遞歸進(jìn)行數(shù)據(jù)分析。
決策樹的實(shí)現(xiàn)主要思路如下:
(1)先計(jì)算整體類別的熵
(2)計(jì)算每個(gè)特征將訓(xùn)練數(shù)據(jù)集分割成的每個(gè)子集的熵,并將這個(gè)熵乘以每個(gè)子集相對(duì)于這個(gè)訓(xùn)練集的頻率,最后將這些乘積累加,就會(huì)得到一個(gè)個(gè)特征對(duì)應(yīng)的信息增益。
(3)選擇信息增益最大的作為最優(yōu)特征分割訓(xùn)練數(shù)據(jù)集
(4)遞歸上述過程
(5)遞歸結(jié)束條件:訓(xùn)練集的所有實(shí)例屬于同一類;或者所有特征已經(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
#實(shí)現(xiàn)熵的計(jì)算
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
#一個(gè)確定“最好地”劃分?jǐn)?shù)據(jù)元組為個(gè)體類的分裂準(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í)例數(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)練集所有實(shí)例屬于同一類
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ù) 第三版》)。
運(yùn)行結(jié)果:
數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實(shí)戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認(rèn)知誤區(qū) 在 MySQL 數(shù)據(jù)庫(kù)管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫(kù)表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動(dòng)態(tài)隨機(jī)一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價(jià)值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲(chǔ)的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫(kù)表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實(shí)戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫(kù))處理 Excel 數(shù)據(jù)時(shí),“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗(yàn)與 t 檢驗(yàn):差異、適用場(chǎng)景與實(shí)踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計(jì)學(xué)領(lǐng)域,假設(shè)檢驗(yàn)是驗(yàn)證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲(chǔ)的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計(jì)劃中 rows 數(shù)量的準(zhǔn)確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計(jì)劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對(duì)象的 text 與 content:區(qū)別、場(chǎng)景與實(shí)踐指南 在 Python 進(jìn)行 HTTP 網(wǎng)絡(luò)請(qǐng)求開發(fā)時(shí)(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價(jià)值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫(kù)表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請(qǐng)求工具對(duì)比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請(qǐng)求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長(zhǎng)浮點(diǎn)數(shù)據(jù)的科學(xué)計(jì)數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長(zhǎng)浮點(diǎn)數(shù)據(jù)時(shí)的科學(xué)計(jì)數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價(jià)值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運(yùn)營(yíng)問題、提升執(zhí)行效率的核心手段,其價(jià)值 ...
2025-09-12用 SQL 驗(yàn)證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實(shí)戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計(jì)” 與 “用戶體驗(yàn) ...
2025-09-11塔吉特百貨孕婦營(yíng)銷案例:數(shù)據(jù)驅(qū)動(dòng)下的精準(zhǔn)零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當(dāng)下,精準(zhǔn)營(yíng)銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務(wù)數(shù)據(jù)分析:概念辨析與協(xié)同價(jià)值 在數(shù)據(jù)驅(qū)動(dòng)決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務(wù)數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實(shí)踐到業(yè)務(wù)價(jià)值挖掘 在數(shù)據(jù)分析場(chǎng)景中,聚類分析作為 “無監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計(jì)模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價(jià)值導(dǎo)向 統(tǒng)計(jì)模型作為數(shù)據(jù)分析的核心工具,并非簡(jiǎn)單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10