决策树的python代码_决策树的Python代码实现与分析

1、 计算给定数据集的香农熵

def calcShannonEnt(dataSet):

#calculate the shangnon value

numEntries = len(dataSet)    #求dataset的元素个数,dataSet的类型是列表

labelCounts = {}             # 创建空列表,存储每一类数量

for featVec in dataSet:      #对dataSet的每一类训练数据

currentLabel = featVec[-1]   # 将dataSet的每一个元素的最后一个元素选择出来,dataSet的元素也是列表

if currentLabel not in labelCounts.keys(): #返回一个字典所有的键。

labelCounts[currentLabel] = 0 #若字典中不存在该类别标签,则使用字典的自动添加进行添加值为0的项

labelCounts[currentLabel] += 1 #递增类别标签的值,labelCounts[currentLabel]主要是统计同一个label出现的次数

shannonEnt = 0.0

for key in labelCounts:    # 对每一分类,计算熵

prob = float(labelCounts[key])/numEntries  #计算某个标签的概率 P(x)

shannonEnt -= prob*math.log(prob,2)   #计算信息熵 P(x) * log(P(x))

return shannonEnt

2. 创建数据的函数

def createDataSet():

dataSet =

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一份使用Python实现决策树算法的代码: ```python import numpy as np def entropy(y): """计算熵""" _, counts = np.unique(y, return_counts=True) p = counts / len(y) return -np.sum(p * np.log2(p)) class DecisionTree: def __init__(self, max_depth=None): self.max_depth = max_depth def fit(self, X, y): self.n_features_ = X.shape[1] self.tree_ = self._grow_tree(X, y) def predict(self, X): return [self._predict(inputs) for inputs in X] def _best_split(self, X, y): """找到最好的特征和分割点""" m = y.size if m <= 1: return None, None num_parent = [np.sum(y == c) for c in range(self.n_classes_)] best_gini = 1.0 - sum((n / m) ** 2 for n in num_parent) best_idx, best_thr = None, None for idx in range(self.n_features_): thresholds, classes = zip(*sorted(zip(X[:, idx], y))) num_left = [0] * self.n_classes_ num_right = num_parent.copy() for i in range(1, m): c = classes[i - 1] num_left[c] += 1 num_right[c] -= 1 gini_left = 1.0 - sum((num_left[x] / i) ** 2 for x in range(self.n_classes_)) gini_right = 1.0 - sum((num_right[x] / (m - i)) ** 2 for x in range(self.n_classes_)) gini = (i * gini_left + (m - i) * gini_right) / m if thresholds[i] == thresholds[i - 1]: continue if gini < best_gini: best_gini = gini best_idx = idx best_thr = (thresholds[i] + thresholds[i - 1]) / 2 return best_idx, best_thr def _grow_tree(self, X, y, depth=0): """递归地构建决策树""" num_samples_per_class = [np.sum(y == i) for i in range(self.n_classes_)] predicted_class = np.argmax(num_samples_per_class) node = Node( predicted_class=predicted_class, num_samples=len(y), num_samples_per_class=num_samples_per_class, ) # 停止递归条件 if ( depth < self.max_depth and np.unique(y).size > 1 and X.shape[0] > self.min_samples_split ): idx, thr = self._best_split(X, y) if idx is not None: indices_left = X[:, idx] < thr X_left, y_left = X[indices_left], y[indices_left] X_right, y_right = X[~indices_left], y[~indices_left] node.feature_index = idx node.threshold = thr node.left = self._grow_tree(X_left, y_left, depth + 1) node.right = self._grow_tree(X_right, y_right, depth + 1) return node def _predict(self, inputs): """预测一个样本""" node = self.tree_ while node.left: if inputs[node.feature_index] < node.threshold: node = node.left else: node = node.right return node.predicted_class class Node: def __init__(self, *, predicted_class, num_samples, num_samples_per_class): self.predicted_class = predicted_class self.num_samples = num_samples self.num_samples_per_class = num_samples_per_class self.feature_index = 0 self.threshold = 0 self.left = None self.right = None ``` 这份代码实现了基于 Gini 系数的分类决策树算法。其中 `max_depth` 参数表示树的最大深度,`min_samples_split` 参数表示一个节点至少需要包含多少个样本才能进行分裂。使用时,可以按照下面的方式实例化并调用: ```python clf = DecisionTree(max_depth=3) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) ``` 其中 `X_train` 和 `y_train` 分别表示训练集的特征和标签,`X_test` 表示测试集的特征。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值