重写轮子之 ID3
这是半成品, 已完成了 fit()
部分, 形成了包含一棵完整树的 node
对象.
后续工作是需解析该 node
对象, 完成 predict()
工作.
# !/usr/bin/python
# -*- coding:utf-8 -*-
"""
Re-implement ID3 algorithm as a practice
Only information gain criterion supplied in our DT algorithm.
使用该 ID3 re-implement 的前提:
1. train data 的标签必须转成0,1,2,...的形式
2. 只能处理连续特征
"""
# Author: 相忠良(Zhong-Liang Xiang) <ugoood@163.com>
# Finished at July ***, 2017
import numpy as np
from sklearn import datasets, cross_validation
## load data
def load_data():
iris = datasets.load_iris()
return cross_validation.train_test_split(iris.data, iris.target, test_size=0.25, random_state=0)
class DecisionNode():
def __init__(self, feature_i=None, threshold=None, value=None, left_branch=None, right_branch=None):
self.feature_i = feature_i # Best feature's index
self.threshold = threshold # Best split threshold in the feature
self.value = value # Value if the node is a leaf in the tree
self.left_branch = left_branch # 'Left' subtree
self.right_branch = right_branch # 'Right' subtree
# print feature_i, 'feature_i'
print self.value, 'value'
class MyDecisionTreeClassifier():
trees = []
num_eles_in_class_label = 3 # 分类标签类的个数
tree = {}
predict_label = []
X_train = []
y_train = []
max_depth = 3
max_leaf_nodes = 30
min_samples_leaf = 1
count = 0
def __init__(self, ):
self.root = None
# TODO
def fit(self, X, y):
self.root = DecisionNode(self.createTree(X, y))
def predict(self, X):
pass
def score(self, X, y):
pass
## entropy
# e.g entropy(y_test)
def __entropy(self, label_list):
bincount = np.bincount(label_list, minlength=self.num_eles_in_class_label)
sum = np.sum(bincount)
# print 'sum in entropy ', sum
temp = 1.0 * bincount / sum
tot = 0
# to avoid log2(0)
for e in temp:
if (e != 0):
tot += e * (-np.log2(e))
return tot
def gain(self, pre_split_label_list, after_split_label_list_2d):
total = 0
n = after_split_label_list_2d[0].__len__() + after_split_label_list_2d[1].__len__()
for item in after_split_label_list_2d:
total += self.__entropy(item) * (1.0 * item.__len__() / n)
return self.__entropy(pre_split_label_list) - total
## 针对np.bincount()的结果,如[37 34 41],判断是否为纯节点,既[0 22 0]的形式
def isPure(self, bincount_list):
sb = sorted(bincount_list)
if ((sb[-1] != 0) & (sb[-2] == 0)):
return True
else:
return False
## 计算出现次数最多的类别标签
def maxCate(self, bincount_list):
bincount_list = np.array(bincount_list)
return bincount_list.argmax()
## 递归停止条件:
# 如果样例小于等于10,停止
# 如果样例大于10 且 点纯,停止
# 否则 继续分裂
def createTree(self, X, y):
bincount_list = np.bincount(y, minlength=self.num_eles_in_class_label)
if ((self.isPure(bincount_list)) & (np.sum(bincount_list) > 10)):
print bincount_list, '11111'
return DecisionNode(value=self.maxCate(bincount_list))
elif (np.sum(bincount_list) <= 10):
print bincount_list, '22222'
return DecisionNode(value=self.maxCate(bincount_list))
else:
print bincount_list, '33333'
f, v, g = self.seek_best_split_feature(X, y)
mask_big = X[:, f] > v
mask_sma = X[:, f] <= v
bigger_X = []
bigger_y = []
smaller_X = []
smaller_y = []
bigger_X.append(X[mask_big])
bigger_y.append(y[mask_big])
smaller_X.append(X[mask_sma])
smaller_y.append(y[mask_sma])
left_branch = self.createTree(bigger_X[0], bigger_y[0])
right_branch = self.createTree(smaller_X[0], smaller_y[0])
return DecisionNode(feature_i=f, threshold=v, left_branch=left_branch, right_branch=right_branch)
## k>=2 特征区间切分点个数
# samples 样本
# labels 样本对应的标签
# return: best_feature, best_split_point, gain_on_that_point
def seek_best_split_feature(self, samples, labels, k=10): # 2 2.84 0.915290847812
samples = np.array(samples)
labels = np.array(labels)
best_split_point_pool = {} # 最佳分裂特征,点,及对应的gain
col_indx = 0
# 遍历所有特征,寻找某特征最佳分裂点
while col_indx < samples.shape[1]:
max = np.max(samples[:, col_indx])
min = np.min(samples[:, col_indx])
split_point = np.linspace(min, max, k, False)[1:]
# 寻找某特征最佳分裂点
temp = []
dic = {}
for p in split_point:
index_less = np.where(samples[:, col_indx] < p)[0] # [1 2]
index_bigger = np.where(samples[:, col_indx] >= p)[0]
label_less = labels[index_less]
label_bigger = labels[index_bigger]
temp.append(list(label_less))
temp.append(list(label_bigger))
g = self.gain(labels, temp)
dic[p] = g
temp = []
best_key = sorted(dic, key=lambda x: dic[x])[-1] # 返回value最大的那个key
dic_temp = {}
dic_temp[best_key] = dic[best_key]
best_split_point_pool[col_indx] = dic_temp
col_indx += 1
# 特征列表
feature_name_box = list(best_split_point_pool.keys())
b = list(best_split_point_pool.values()) # 临时表
# 最大gain列表
gain_box = []
# 最佳切分点列表
point_box = []
for item in b:
gain_box.append(item.values()[0])
point_box.append(item.keys()[0])
best_feature = feature_name_box[np.argmax(gain_box)]
best_split_point = point_box[np.argmax(gain_box)]
gain_on_that_point = np.max(gain_box)
return best_feature, best_split_point, gain_on_that_point
## 测试用例
X_train, X_test, y_train, y_test = load_data()
cls = MyDecisionTreeClassifier()
a = [[9, 2, 3, 4],
[5, 6, 7, 8],
[1, 10, 11, 12],
[13, 14, 15, 16]]
b = [0, 1, 2, 3]
a = np.array(a)
b = np.array(b)
# xx = [2,1,1]
# print cls.maxCate(xx),'11111111111111111111111'
cls.fit(X_train, y_train)
tree = cls.root
print type(cls.root)
'''
下面是编程过程中留下的经验
'''
# 重要1: np.linspace(0,1,5) 0-1之间,等分5份,包括首尾
# np.linspace(0,1,5)
# [ 0. 0.25 0.5 0.75 1. ]
# 重要2: np.where(a[:,0]>2) 返回矩阵a中第0列值大于2的那些行的索引号
# 返回值的样子 (array([1, 2]),)
# 重要3: 返回value最大的那个key
# print(sorted(dic, key=lambda x: dic[x])[-1])
# 重要4: np.bincount()指定最小长度
# xxx = [1,1,1,1,1]
# print np.bincount(xxx,minlength=3)
# 结果: [0 5 0]
重写轮子之 ID3的更多相关文章
- 重写轮子之 GaussionNB
我仿照sk-learn 中 GaussionNB 的结构, 重写了该算法的轮子,命名为 MyGaussionNB, 如下: # !/usr/bin/python # -*- coding:utf-8 ...
- 重写轮子之 kNN
# !/usr/bin/python # -*- coding:utf-8 -*- """ Re-implement kNN algorithm as a practic ...
- 关于重写ID3 Algorithm Based On MapReduceV1/C++/Streaming的一些心得体会
心血来潮,同时想用C++连连手.面对如火如荼的MP,一阵念头闪过,如果把一些ML领域的玩意整合到MP里面是不是很有意思 确实很有意思,可惜mahout来高深,我也看不懂.干脆自动动手丰衣足食,加上自己 ...
- 【转】C# 重写WndProc 拦截 发送 系统消息 + windows消息常量值(1)
C# 重写WndProc 拦截 发送 系统消息 + windows消息常量值(1) #region 截获消息 /// 截获消息 处理XP不能关机问题 protected ...
- Asp.net Mvc 请求是如何到达 MvcHandler的——UrlRoutingModule、MvcRouteHandler分析,并造个轮子
这个是转载自:http://www.cnblogs.com/keyindex/archive/2012/08/11/2634005.html(那个比较容易忘记,希望博主不要生气的) 前言 本文假定读者 ...
- 拆解轮子之XRecyclerView
简介 这个轮子是对RecyclerView的封装,主要完成了下拉刷新.上拉加载更多.RecyclerView头部.在我的Material Design学习项目中使用到了项目地址,感觉还不错.趁着毕业答 ...
- 跨平台技术实践案例: 用 reactxp 重写墨刀的移动端
Authors: Gao Cong, Perry Poon Illustrators: Shena Bian April 20, 2019 重新编写,又一次,我们又一次重新编写了移动端应用和移动端 ...
- 星级评分原理 N次重写的分析
使用的是雪碧图,用的软件是CSS Sprite Tools 第一次实现与分析: <!DOCTYPE html> <html> <head> <meta cha ...
- [18/11/29] 继承(extends)和方法的重写(override,不是重载)
一.何为继承?(对原有类的扩充) 继承让我们更加容易实现类的扩展. 比如,我们定义了人类,再定义Boy类就只需要扩展人类即可.实现了代码的重用,不用再重新发明轮子(don’t reinvent w ...
随机推荐
- 新概念英语(1-105)Full Of Mistakes
Lesson 105 Full of mistakes 错误百出 Listen to the tape then answer this question. What was Sandra's pre ...
- 使用 slf4j抽象日志层 和 其他日志实现对接
前言 如果你正在提供一个开源的Java-jar,那么让你的项目仅依赖slf4j-api然后让你的用户在他们开发和运营环境中选择任意的日志实现绝对是个好想法,.作为终端用户,他们可以快速地从上面提到的日 ...
- spring cloud zipkin sleuth与spring boot aop结合后,启动慢
问题描述: 引入了spring cloud的监控starter,间接引入jooq. 又引入了 spring-boot-starter-web,所以间接引入aop. 参考下面资料后:https://gi ...
- Vue框架
Vue框架 环境: windows python3.6.2 Vue的cdn: <script src="https://cdn.jsdelivr.net/npm/vue"&g ...
- spark2.1:在RDD[unit].foreach(s=>{})内部调用sparkSession对象抛出NullPointException
问题代码: val sample_data_combine_result=List( (0,(List(FitModel(4022,1447.92,-8.38983306721434,2.0),Fit ...
- asp.net core 二 Nginx Supervisor 负载,监听
ASP.NET Core负载均衡集群搭建(CentOS7+Nginx+Supervisor+Kestrel) asp.net core在linux运行下,一但命令行退出 ...
- angulajs_删除功能
- h5视频和音频 -2018/04/16
HTML5 规定了一种通过 video 元素来包含视频的标准方法. 当前video元素支持的三种视频格式: (1)Ogg 带有Theora视频编码和Vorbis音频编码的ogg文件 (2)MPEG4带 ...
- 《阿里巴巴 Java 开发手册》读书笔记
偶然看到阿里巴巴居然出书了???趁着满减活动(节约节约....)我赶紧买来准备看看,刚拿到的时候掂量了好多下,总觉得商家给我少发了一本书,结果打开才知道..原来这本书这么小.... 编码规范的重要性 ...
- 【Swift】图文混排,ios开发中在textfield或textView中插入图片
在ios开发中,我们一般都是在textfield或者textView中输入文字.当我们需要插入图片的时候其实也是很简单的 我们需要利用的textfield,textView的属性化文本,将图片以附件的 ...