使用决策树进行分类

来源:互联网 发布:正版cad软件多少钱 编辑:程序博客网 时间:2024/06/07 05:46
#创建数据集def createDataSet():    dataSet = [[1, 1, 'yes'],               [1, 1, 'yes'],               [1, 0, 'no'],               [0, 1, 'no'],               [0, 1, 'no']]    labels = ['no surfacing', 'flippers']    return dataSet, labels#测试的树数据def retrieveTree(i):    listOfTrees = [{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1:'yes'}}}},                    {'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1:'yes'}}, 1: 'no'}}}}]    return listOfTrees[i]#使用决策树进行分类def classify(inputTree, featLabels, testVec):    #inputTree为输入的树,featLabels为特征值标签,testVec为测试的特征值结果    first = list(inputTree.keys())    firstStr = first[0] #树的根节点    secondDict = inputTree[firstStr] #子树    featIndex = featLabels.index(firstStr) #返回特征值的索引    for key in secondDict.keys():        if testVec[featIndex] == key: #testVec[featIndex]为测试数据当前特征值的结果            if type(secondDict[key]).__name__=="dict": #判断是否为字典,有没有子树                classLabel = classify(secondDict[key], featLabels, testVec)            else:   classLabel = secondDict[key] #这个测试值得标签则树子节点的值    return classLabel#测试[1,0]的标签为myDat, labels = createDataSet()myTree = retrieveTree(0)classLabel = classify(myTree, labels, [1, 0])print(classLabel)>>no
原创粉丝点击