基于id3算法根据房价数据进行画图预测python

根据已给的波士顿房价数据,对波斯顿房价进行预测。即,实现给出若干条件(如房间数、社区的低收入阶层的比率和镇上学生与教师数量比例的部分数据),要能说出给出的条件是否能够有效进行预测,如可以做有效预测,则给出预测的结果。
这里
上面的是数据
下面是ID3的算法

#coding:utf-8

__author__ = 'liukai'

from math import log

class DecisonTree:
    trainData = []
    trainLabel = []
    featureValus = {} #每个特征所有可能的取值

    def __init__(self, trainData, trainLabel, threshold):
        self.loadData(trainData, trainLabel)
        self.threshold = threshold
        self.tree = self.createTree(range(0,len(trainLabel)), range(0,len(trainData[0])))


    #加载数据
    def loadData(self, trainData, trainLabel):
        if len(trainData) != len(trainLabel):
            raise ValueError('input error')
        self.trainData = trainData
        self.trainLabel = trainLabel

        #计算 featureValus
        for data in trainData:
            for index, value in enumerate(data):
                if not index in self.featureValus.keys():
                    self.featureValus[index] = [value]
                if not value in self.featureValus[index]:
                    self.featureValus[index].append(value)

    #计算信息熵
    def caculateEntropy(self, dataset):
        labelCount = self.labelCount(dataset)
        size = len(dataset)
        result = 0
        for i in labelCount.values():
            pi = i / float(size)
            result -= pi * (log(pi) /log(2))
        return result

    #计算信息增益
    def caculateGain(self, dataset, feature):
        values = self.featureValus[feature] #特征feature 所有可能的取值
        result = 0
        for v in values:
            subDataset = self.splitDataset(dataset=dataset, feature=feature, value=v)
            result += len(subDataset) / float(len(dataset)) * self.caculateEntropy(subDataset)
        return self.caculateEntropy(dataset=dataset) - result

    #计算数据集中,每个标签出现的次数
    def labelCount(self, dataset):
        labelCount = {}
        for i in dataset:
            if trainLabel[i] in labelCount.keys():
                labelCount[trainLabel[i]] += 1
            else:
                labelCount[trainLabel[i]] = 1

        return labelCount

    '''
    dataset:数据集
    features:特征集
    '''
    def createTree(self, dataset, features):

        labelCount = self.labelCount(dataset)
        #如果特征集为空,则该树为单节点树
        #计算数据集中出现次数最多的标签
        if not features:
            return max(list(labelCount.items()),key = lambda x:x[1])[0]

        #如果数据集中,只包同一种标签,则该树为单节点树
        if len(labelCount) == 1:
            # return labelCount.keys()[0]
            return labelCount.keys()

        #计算特征集中每个特征的信息增益
        l = map(lambda x : [x, self.caculateGain(dataset=dataset, feature=x)], features)

        #选取信息增益最大的特征
        feature, gain = max(l, key = lambda x: x[1])

        #如果最大信息增益小于阈值,则该树为单节点树
        #
        if self.threshold > gain:
            return max(list(labelCount.items()),key = lambda x:x[1])[0]

        tree = {}
        #选取特征子集
        subFeatures = filter(lambda x : x != feature, features)
        tree['feature'] = feature
        #构建子树
        for value in self.featureValus[feature]:
            subDataset = self.splitDataset(dataset=dataset, feature=feature, value=value)

            #保证子数据集非空
            if not subDataset:
                continue
            tree[value] = self.createTree(dataset=subDataset, features=subFeatures)
        return tree

    def splitDataset(self, dataset, feature, value):
        reslut = []
        for index in dataset:
            if self.trainData[index][feature] == value:
                reslut.append(index)
        return reslut

    def classify(self, data):
        def f(tree, data):
            if type(tree) != dict:
                return tree
            else:
                return f(tree[data[tree['feature']]], data)
        return f(self.tree, data)


if __name__ == '__main__':

    trainData = [
        [0, 0, 0, 0],
        [0, 0, 0, 1],
        [0, 1, 0, 1],
        [0, 1, 1, 0],
        [0, 0, 0, 0],
        [1, 0, 0, 0],
        [1, 0, 0, 1],
        [1, 1, 1, 1],
        [1, 0, 1, 2],
        [1, 0, 1, 2],
        [2, 0, 1, 2],
        [2, 0, 1, 1],
        [2, 1, 0, 1],
        [2, 1, 0, 2],
        [2, 0, 0, 0],
    ]

    trainLabel = [0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0]

    tree = DecisonTree(trainData=trainData, trainLabel=trainLabel, threshold=0)
    print (tree.tree)

# {'feature': 2,
#  0: {'feature': 1, 0: dict_keys([0]),1: dict_keys([1])},
#  1: dict_keys([1])}

接下来就是画图的实现

#### -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import time
import math
from math import sin
import numpy as np

# plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
# plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

# plt.xlabel(“x轴标签”)
# plt.ylabel("y轴标签")
# plt.title("图像标题")
# plt.xlim(0,5)     在画好的图形中选取x范围内的图形片段。
# plt.ylim(0,5)     y片段
# plt.plot(x,y,linewidth=4)    设置线的宽度
# plt.plot(x,y,"g字符")     g代表绿色 后面的字符表示线的种类。如虚线,点线等

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

#D.柱状图bar
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2.3, 3.4, 1.2, 6.6, 7.0]

plt.figure()
plt.bar(x, y)
plt.title("bar")
plt.show()
exit()
##饼图###
labels = ['China', 'Swiss', 'USA', 'UK', 'Laos', 'Spain']
X = [222, 42, 455, 664, 454, 334]
fig = plt.figure()
plt.pie(X, labels=labels, autopct='%1.2f%%')  # 画饼图(数据,数据对应的标签,百分数保留两位小数点)
plt.title("Pie chart")

plt.show()
plt.savefig("PieChart.jpg")
exit()

x=np.arange(0,2*np.pi,0.01)
y=np.sin(x)
plt.xlabel('角度')
plt.ylabel("SIN")
# plt.ylim(-1,1)   #片段选择
plt.plot(x,y)
plt.show()


exit()

x = [1, 2, 3, 4, 5]
y = [2.3, 3.4, 1.2, 6.6, 7.0]
fig = plt.figure(figsize=(12, 6))
plt.subplot(121)
plt.plot(x, y, color='r', linestyle='-')
plt.subplot(122)
plt.title("正弦图片")
plt.plot(x, y, color='r', linestyle='--')
plt.show()
exit()
x = [1, 2, 3, 4, 5]
y = [2.3, 3.4, 1.2, 6.6, 7.0]
plt.scatter(x, y, color='r', marker='+')
plt.show()
exit()
plt.figure(figsize=(6,6))
plt.subplot(231)
plt.subplot(232)
plt.subplot(233)
plt.subplot(234)
plt.subplot(235)
plt.subplot(236)
plt.show()

exit()
x_data = [1, 2, 3, 4, 5]
y_data = [2.3, 3.4, 1.2, 6.6, 7.0]
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data, y_data)
# plt.ion()#本次运行请注释,全局运行不要注释
plt.show()
time.sleep(20)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

灵舒敲代码

我的公v是cxyy1106,欢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值