使用决策树算法预测隐形眼镜类型

2024-02-25 11:36

本文主要是介绍使用决策树算法预测隐形眼镜类型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

谷歌笔记本(可选)

编写算法:决策树

 准备数据:拆分数据集

测试算法:构造注解树

使用算法:预测隐形眼镜类型


谷歌笔记本(可选)

from google.colab import drive
drive.mount("/content/drive")

output

Mounted at /content/drive

编写算法:决策树

from math import log
import operatordef calcShannonEnt(dataSet):numEntries = len(dataSet)labelCounts = {}for featVec in dataSet:currentLabel = featVec[-1]if currentLabel not in labelCounts.keys():labelCounts[currentLabel] = 0labelCounts[currentLabel] += 1shannonEnt = 0for key in labelCounts:prob = float(labelCounts[key]) / numEntriesshannonEnt -= prob * log(prob, 2)return shannonEnt

这段代码是用于计算给定数据集的香农熵(Shannon Entropy)的Python实现。香农熵在信息论中是一个度量不确定性或信息混乱程度的重要概念,在机器学习领域,特别是在决策树算法中,用于评估特征对于划分数据集纯度的贡献。

1. `calcShannonEnt`函数接收一个名为dataSet的数据集作为输入,该数据集通常是由特征向量构成的列表,每个特征向量最后一个元素为其对应的类别标签。

2. 首先统计数据集中样本的数量:`numEntries = len(dataSet)`。

3. 初始化一个字典`labelCounts`,用于存储各类别标签出现的次数。通过遍历整个数据集,对每一个特征向量(featVec),提取其类别标签(currentLabel),并将其计数加到字典对应键值上。

4. 计算香农熵:初始化`shannonEnt`为0,然后遍历`labelCounts`字典,对于每个类别标签key,计算其概率(通过其出现次数除以总样本数得到),然后用公式 `- prob * log(prob, 2)` 计算其熵值,并累加到`shannonEnt`上。这里的log是以2为底的对数,因为熵的单位通常是比特(bits)。

5. 最后返回计算得出的香农熵值`shannonEnt`。

总结:这个函数的主要目的是衡量给定数据集中各类别的不确定性或分布均匀性,熵值越大表示不确定性越高,越需要进行划分以提高模型的纯度。

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
def chooseBestFeatureToSplit(dataSet):numFeatures = len(dataSet[0]) - 1   # 2baseEntropy = calcShannonEnt(dataSet)  # 0.9709505944546686bestInfoGain = 0bestFeature = -1for i in range(numFeatures):featList = [example[i] for example in dataSet]uniqueVals = set(featList)newEntropy = 0for value in uniqueVals:subDataSet = splitDataSet(dataSet, i, value)prob = len(subDataSet) / float(len(dataSet))newEntropy += prob * calcShannonEnt(subDataSet)infoGain = baseEntropy - newEntropyif(infoGain > bestInfoGain):bestInfoGain = infoGainbestFeature = ireturn bestFeature

这段代码是用于选择数据集中最佳特征进行划分的函数,通常在决策树构建过程中使用。其主要目的是通过计算信息增益(Information Gain)来确定最优分割特征。

1. numFeatures 计算特征的数量,等于数据集中每个样本向量元素的个数减1(因为最后一个元素通常是类别标签)。

2. 初始化基本熵(baseEntropy),通过调用之前定义的 calcShannonEnt(dataSet) 函数计算整个数据集的香农熵。

3. 初始化最佳信息增益(bestInfoGain)为0,以及最佳特征索引(bestFeature)为-1,分别用于存储找到的最大信息增益和对应的特征编号。

4. 遍历所有特征(i从0到numFeatures-1): 

        a. 通过列表推导式提取出当前特征i的所有取值,存入featList。

        b. 将featList中的唯一值转化为一个集合(uniqueVals),这将作为当前特征可能的划分依据。

        c. 对于uniqueVals中的每一个value,利用splitDataSet函数根据特征i和该value划分数据集得到subDataSet。

        d. 计算划分后子数据集的概率(prob),即子数据集大小除以原数据集大小。

        e. 计算划分后的子数据集的香农熵,并乘以对应概率得到加权平均熵(newEntropy)。

        f. 使用公式计算信息增益:infoGain = baseEntropy - newEntropy

        g. 如果当前信息增益大于已记录的最佳信息增益,则更新bestInfoGain和bestFeature。

5. 循环结束后返回最佳特征索引(bestFeature)。这个特征就是当前能带来最大信息增益的特征,用于下一步决策树节点的划分。

def majorityCnt(classList):classCount={}for vote in classList:if vote not in classCount.keys():classCount[vote] = 0classCount[vote] += 1sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)return sortedClassCount[0][0]
def createTree(dataSet, labels):classList = [example[-1] for example in dataSet]if classList.count(classList[0]) == len(classList):return classList[0]if len(dataSet[0]) == 1:return majorityCnt(classList)bestFeat = chooseBestFeatureToSplit(dataSet)bestFeatLabel = labels[bestFeat]myTree = {bestFeatLabel:{}}subLabels = labels[:]del(subLabels[bestFeat])featValues = [example[bestFeat] for example in dataSet]uniqueVals = set(featValues)for value in uniqueVals:myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)return myTree

这段代码是用于创建决策树的函数,名为`createTree`。它递归地构建决策树直到满足停止条件。

1. 首先计算数据集classList中最后一个元素(类别标签)的唯一值数量,如果所有样本的类别标签都相同,则说明当前节点下的样本已经足够纯,无需继续划分,直接返回这个唯一的类别标签作为叶子节点的预测结果。

2. 检查是否所有特征已经被用尽(即每个样本只有一个特征),如果是,则返回该节点下出现次数最多的类别标签(通过调用`majorityCnt(classList)`实现)。

3. 使用`chooseBestFeatureToSplit`函数选择最优特征进行划分,并获取其对应的标签名称(bestFeatLabel)。

4. 初始化一个新的字典结构myTree,以表示当前节点以及其子节点。字典的键为最优特征的标签,值为另一个字典,后续将填充各个特征取值对应的子树。

5. 创建一个子标签列表subLabels,它是原标签列表labels的一个副本,然后删除最优特征对应的标签,这样在构建子节点时不会重复考虑此特征。

6. 提取数据集中最优特征的所有取值并转化为一个集合uniqueVals。

7. 遍历uniqueVals中的每一个特征取值value:
   a. 调用`splitDataSet(dataSet, bestFeat, value)`对数据集进行划分,得到该特征取值对应的新子数据集。
   b. 以最优特征的取值value作为键,递归调用`createTree`生成对应的子树,并将其添加到myTree[bestFeatLabel]中。

8. 当所有子树构造完成后,返回整个决策树结构myTree。整个过程按照信息增益最大原则自顶向下构建决策树,直至达到终止条件。

 

 准备数据:拆分数据集

fr = open('/content/drive/MyDrive/MachineLearning/机器学习/决策树/使用决策树预测隐形眼镜类型/lenses.txt')
lenses = [inst.strip().split('\t') for inst in fr.readlines()]
lensesLabels = ['age', 'prescript', 'astigmatic', 'tearRate']
lensesTree = createTree(lenses, lensesLabels)
lensesTree, lensesLabels

output

({'tearRate': {'normal': {'astigmatic': {'no': {'age': {'presbyopic': {'prescript': {'myope': 'no lenses','hyper': 'soft'}},'pre': 'soft','young': 'soft'}},'yes': {'prescript': {'myope': 'hard','hyper': {'age': {'presbyopic': 'no lenses','pre': 'no lenses','young': 'hard'}}}}}},'reduced': 'no lenses'}},['age', 'prescript', 'astigmatic', 'tearRate'])

测试算法:构造注解树

import matplotlib.pyplot as plt
decisionNode = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")
def plotNode(nodeTxt, centerPt, parentPt, nodeType):createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction',xytext=centerPt, textcoords='axes fraction',va='center', ha='center', bbox=nodeType, arrowprops=arrow_args)
def getNumLeafs(myTree):numLeafs = 0firstStr = list(myTree.keys())[0]secondDict = myTree[firstStr]for key in secondDict.keys():if type(secondDict[key]).__name__ == 'dict':numLeafs += getNumLeafs(secondDict[key])else:numLeafs += 1return numLeafs
def getTreeDepth(myTree):maxDepth = 0firstStr = list(myTree.keys())[0]secondDict = myTree[firstStr]for key in secondDict.keys():if type(secondDict[key]).__name__=='dict':thisDepth = 1 + getTreeDepth(secondDict[key])else:thisDepth = 1if thisDepth > maxDepth:maxDepth = thisDepthreturn maxDepth
def plotMidText(cntrPt, parentPt, txtString):xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0]yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1]createPlot.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30)
def plotTree(myTree, parentPt, nodeTxt):numLeafs = getNumLeafs(myTree)depth = getTreeDepth(myTree)firstStr = list(myTree.keys())[0]cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)plotMidText(cntrPt, parentPt, nodeTxt)plotNode(firstStr, cntrPt, parentPt, decisionNode)secondDict = myTree[firstStr]plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalDfor key in secondDict.keys():if type(secondDict[key]).__name__=='dict':plotTree(secondDict[key],cntrPt,str(key))else:plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalWplotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode)plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD
def createPlot(inTree):fig = plt.figure(1, facecolor='white')fig.clf()axprops = dict(xticks=[], yticks=[])createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)plotTree.totalW = float(getNumLeafs(inTree))plotTree.totalD = float(getTreeDepth(inTree))plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0;plotTree(inTree, (0.5,1.0), '')plt.show()
createPlot(lensesTree)

output

使用算法:预测隐形眼镜类型

def classify(inputTree, featLabels, testVec):firstStr = list(inputTree.keys())[0]secondDict = inputTree[firstStr]featIndex = featLabels.index(firstStr)for key in secondDict.keys():if testVec[featIndex] == key:if type(secondDict[key]).__name__ == 'dict':classLabel = classify(secondDict[key], featLabels, testVec)else:classLabel = secondDict[key]return classLabel
classify(lensesTree, lensesLabels, ['pre', 'myope', 'yes', 'normal'])

output

'hard'

这篇关于使用决策树算法预测隐形眼镜类型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/745352

相关文章

python中的flask_sqlalchemy的使用及示例详解

《python中的flask_sqlalchemy的使用及示例详解》文章主要介绍了在使用SQLAlchemy创建模型实例时,通过元类动态创建实例的方式,并说明了如何在实例化时执行__init__方法,... 目录@orm.reconstructorSQLAlchemy的回滚关联其他模型数据库基本操作将数据添

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav

Java使用Spire.Doc for Java实现Word自动化插入图片

《Java使用Spire.DocforJava实现Word自动化插入图片》在日常工作中,Word文档是不可或缺的工具,而图片作为信息传达的重要载体,其在文档中的插入与布局显得尤为关键,下面我们就来... 目录1. Spire.Doc for Java库介绍与安装2. 使用特定的环绕方式插入图片3. 在指定位

Springboot3 ResponseEntity 完全使用案例

《Springboot3ResponseEntity完全使用案例》ResponseEntity是SpringBoot中控制HTTP响应的核心工具——它能让你精准定义响应状态码、响应头、响应体,相比... 目录Spring Boot 3 ResponseEntity 完全使用教程前置准备1. 项目基础依赖(M

Java使用Spire.Barcode for Java实现条形码生成与识别

《Java使用Spire.BarcodeforJava实现条形码生成与识别》在现代商业和技术领域,条形码无处不在,本教程将引导您深入了解如何在您的Java项目中利用Spire.Barcodefor... 目录1. Spire.Barcode for Java 简介与环境配置2. 使用 Spire.Barco

Android使用java实现网络连通性检查详解

《Android使用java实现网络连通性检查详解》这篇文章主要为大家详细介绍了Android使用java实现网络连通性检查的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录NetCheck.Java(可直接拷贝)使用示例(Activity/Fragment 内)权限要求

MyBatis中的两种参数传递类型详解(示例代码)

《MyBatis中的两种参数传递类型详解(示例代码)》文章介绍了MyBatis中传递多个参数的两种方式,使用Map和使用@Param注解或封装POJO,Map方式适用于动态、不固定的参数,但可读性和安... 目录✅ android方式一:使用Map<String, Object>✅ 方式二:使用@Param

C# 预处理指令(# 指令)的具体使用

《C#预处理指令(#指令)的具体使用》本文主要介绍了C#预处理指令(#指令)的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录1、预处理指令的本质2、条件编译指令2.1 #define 和 #undef2.2 #if, #el

C#中Trace.Assert的使用小结

《C#中Trace.Assert的使用小结》Trace.Assert是.NET中的运行时断言检查工具,用于验证代码中的关键条件,下面就来详细的介绍一下Trace.Assert的使用,具有一定的参考价值... 目录1、 什么是 Trace.Assert?1.1 最简单的比喻1.2 基本语法2、⚡ 工作原理3

C# IPAddress 和 IPEndPoint 类的使用小结

《C#IPAddress和IPEndPoint类的使用小结》本文主要介绍了C#IPAddress和IPEndPoint类的使用小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定... 目录一、核心作用网络编程基础类二、IPAddress 类详解三种初始化方式1. byte 数组初始化2. l