基于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])}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
接下来就是画图的实现
#### -*- 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)
基于id3算法根据房价数据进行画图预测python的更多相关文章
- 机器学习决策树ID3算法,手把手教你用Python实现
本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是机器学习专题的第21篇文章,我们一起来看一个新的模型--决策树. 决策树的定义 决策树是我本人非常喜欢的机器学习模型,非常直观容易理解 ...
- 决策树-预测隐形眼镜类型 (ID3算法,C4.5算法,CART算法,GINI指数,剪枝,随机森林)
1. 1.问题的引入 2.一个实例 3.基本概念 4.ID3 5.C4.5 6.CART 7.随机森林 2. 我们应该设计什么的算法,使得计算机对贷款申请人员的申请信息自动进行分类,以决定能否贷款? ...
- 决策树笔记:使用ID3算法
决策树笔记:使用ID3算法 决策树笔记:使用ID3算法 机器学习 先说一个偶然的想法:同样的一堆节点构成的二叉树,平衡树和非平衡树的区别,可以认为是"是否按照重要度逐渐降低"的顺序 ...
- 决策树--ID3 算法(一)
Contents 1. 决策树的基本认识 2. ID3算法介绍 3. 信息熵与信息增益 4. ID3算法的C++实现 1. 决策树的基本认识 决策树是一种 ...
- 【Machine Learning】决策树之ID3算法 (2)
决策树之ID3算法 Content 1.ID3概念 2.信息熵 3.信息增益 Information Gain 4. ID3 bias 5. Python算法实现(待定) 一.ID3概念 ID3算法最 ...
- 机器学习笔记----- ID3算法的python实战
本文申明:本文原创,如有转载请申明.数据代码来自实验数据都是来自[美]Peter Harrington 写的<Machine Learning in Action>这本书,侵删. Hell ...
- ID3算法 决策树的生成(1)
# coding:utf-8 import matplotlib.pyplot as plt import numpy as np import pylab def createDataSet(): ...
- 陕西中际现代:基于自适应算法的PLC滴灌控制系统
基于自适应算法的PLC滴灌控制系统 陕西中际现代包装科技有限公司滴灌部 1.介绍 水资源正在成为一种珍贵的资源.城镇的市民使用成千上万立方的水来浇灌花园和绿地.他们依赖于使用固定灌溉计划的控制器.而这 ...
- Python实现ID3算法
自己用Python写的数据挖掘中的ID3算法,现在觉得Python是实现算法的最好工具: 先贴出ID3算法的介绍地址http://wenku.baidu.com/view/cddddaed0975f4 ...
随机推荐
- luogu P2607 [ZJOI2008]骑士 tarjan dp
LINK:骑士 本来是不打算写的 发现这道题在tarjan的时候有一个坑点 所以写出来记录一下. 可以发现图可能是不连通的 且一个连通块中是一个奇环树. 做法:类似tarjan找割点 然后把环给拉出来 ...
- win10 安装tensorflow2.0 GPU版本遇到的坑
背景:我的机器上tensorflow 1.14 & 2.0,这俩版本都有,之前都是用1.14版本,今天试一下2.0尝尝鲜, 结果就掉坑去了 把CUDA10.1 和 cudnn 安装 ...
- Caffe CuDNN版本与环境不同导致make错误
1.将./include/caffe/util/cudnn.hpp 换成最新版的caffe里的cudnn的实现,即相应的cudnn.hpp. 2.将./include/caffe/layers里的,所 ...
- Rx.js实现原理浅析
前言 上次给大家分享了cycle.js的内容,这个框架核心模块的代码其实只有一百多行,要理解这个看似复杂的框架,其实最核心的是理解它依赖的异步数据流处理框架--rx.js.今天,给大家分享一下rx.j ...
- github开源文章生成pdf
最近需要研究ELK,然后在网上发现了有本书写的不错,然后搜到是在 github 上开源过的.这本书的时间有点久了,就想通过源码自己来生成一个 pdf 我使用的是 ubuntu 系统 step1:安装 ...
- UI自动化填写问卷(selenium)+定时任务(懒人必备)
1.自动填报 UI自动化 selenium 开发程序动机:天天有人催着填写问卷,弄的头大.主要还是懒的每天一个个去填写内容. 开发总时长:2个小时:学习+开发+修改 遇到的小问题: 在自动化填写地图的 ...
- Android Studio--家庭记账本(二)
家庭记账本APP目前实现了记账功能,也就是说增加功能,今天打算添加删除功能,参考着增加的代码研究,从网上查阅资料,打算实现左滑删除功能,目前学到了xml里面的HorizontalScrollView布 ...
- 2020重新出发,JAVA学前了解,Windosws常用快捷键
前言:windows 常用快捷键 标准计算机键盘共104键,除了26个字母键.符号键.数字键外,剩下的都是一些功能键: 键盘功能键 常用功能键:Esc.Tab.Caps Lock.Shift.Ctrl ...
- tableau用户分类
1.观察消费金额的分布 直接[消费金额]直方图趋势不明显的时候,可以考虑将金额对数化处理 这样看起来就近似个正态分布了 2.怎么看超市卖的最好的产品 更深层次的分析怎么做呢? 这个聚合字段在数据源不会 ...
- C#LeetCode刷题之#34-在排序数组中查找元素的第一个和最后一个位置(Find First and Last Position of Element in Sorted Array)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4970 访问. 给定一个按照升序排列的整数数组 nums,和一个目 ...