决策树python代码(决策树 python)

[img]

简介:

决策树(Decision Tree)是一种非常常见的机器学习算法,它可以用来进行分类和回归等任务。在这篇文章中,我们将使用Python编写一个简单的决策树算法来进行分类任务。

多级标题:

1. 数据准备

2. 构建决策树

3. 预测数据

4. 代码实现

5. 总结

数据准备:

在开始编写代码之前,我们需要准备一些数据来进行分类。在这个例子中,我们将使用一个简单的数据集,其中包含两个特征和两种不同的标签。我们将随机生成一些数据点,以帮助我们构建我们的决策树算法。

构建决策树:

在这个步骤中,我们将使用递归的方式来构建我们的决策树算法。我们首先需要选择一个特征来分裂我们的数据集,这个特征应该对数据集进行最有效的分割。然后我们将数据集按照这个特征分裂成两个子集,并在每个子集上递归地构建决策树。我们会不断地这样分裂数据集并构建子树,直到达到预先设定的停止条件为止。

预测数据:

当我们完成了我们的决策树构建之后,我们就可以使用它来进行分类任务了。对于一个新的数据点,我们可以按照决策树的分裂规则来进行分类。首先将数据点传递给根节点,然后按照每个节点的分裂规则遍历决策树,最终到达一个叶子节点,这个叶子节点就是我们预测的类别。

代码实现:

下面是我们使用Python编写的一个简单的决策树算法实现,它可以用来进行二分类任务。

```

import numpy as np

class Node:

def __init__(self, feature_index=None, threshold=None, left=None, right=None, value=None):

self.feature_index = feature_index # 特征索引

self.threshold = threshold # 分割点阈值

self.left = left # 左子树

self.right = right # 右子树

self.value = value # 叶子节点预测值

class DecisionTree:

def __init__(self, max_depth=None):

self.max_depth = max_depth

self.root = None

def fit(self, X, y):

self.n_classes = len(np.unique(y))

self.n_features = X.shape[1]

self.root = self._grow_tree(X, y)

def predict(self, X):

return [self._predict(inputs) for inputs in X]

def _grow_tree(self, X, y, depth=0):

n_samples, n_features = X.shape

n_labels = len(np.unique(y))

# 终止条件

if (self.max_depth is not None and depth >= self.max_depth) or n_labels == 1 or n_samples < 2:

return Node(value=self._most_common_label(y))

# 选择最佳分裂特征和分割点

feature_indices = np.random.choice(n_features, int(np.sqrt(n_features)), replace=False)

best_feature, best_threshold = self._best_criteria(X, y, feature_indices)

# 递归构建子树

left_mask = X[:, best_feature] <= best_threshold

right_mask = X[:, best_feature] > best_threshold

left = self._grow_tree(X[left_mask], y[left_mask], depth+1)

right = self._grow_tree(X[right_mask], y[right_mask], depth+1)

return Node(best_feature, best_threshold, left, right)

def _best_criteria(self, X, y, feature_indices):

best_gain = -1

split_idx, split_threshold = None, None

for i in feature_indices:

feature_values = X[:, i]

thresholds = np.unique(feature_values)

for threshold in thresholds:

gain = self._information_gain(y, feature_values, threshold)

if gain > best_gain:

best_gain = gain

split_idx = i

split_threshold = threshold

return split_idx, split_threshold

def _information_gain(self, y, X_feature, threshold):

parent_entropy = entropy(y)

left_mask = X_feature <= threshold

right_mask = X_feature > threshold

if not np.any(left_mask) or not np.any(right_mask):

return 0

n_l, n_r = len(y[left_mask]), len(y[right_mask])

e_l, e_r = entropy(y[left_mask]), entropy(y[right_mask])

child_entropy = (n_l/len(y))*e_l + (n_r/len(y))*e_r

ig = parent_entropy - child_entropy

return ig

def _most_common_label(self, y):

return np.bincount(y).argmax()

def _predict(self, inputs):

node = self.root

while node.left:

if inputs[node.feature_index] <= node.threshold:

node = node.left

else:

node = node.right

return node.value

def entropy(y):

hist = np.bincount(y)

ps = hist / np.sum(hist)

return -np.sum([p * np.log2(p) for p in ps if p > 0])

```

总结:

在这篇文章中,我们介绍了决策树算法的基本原理,并使用Python编写了一个简单的决策树分类算法。决策树是一种非常直观的算法,它的结果易于理解和解释。在实际应用中,我们需要利用不同的分割规则和调整算法参数等手段来提高算法预测精度。

标签列表