用python实现决策树算法_python实现ID3决策树算法
时间: 2023-07-20 11:19:35 浏览: 40
好的,下面是用 Python 实现 ID3 决策树算法的代码示例:
```python
import math
from collections import Counter
def find_entropy(data):
"""
计算数据集的信息熵
"""
# 统计数据集中每个类别的样本数
class_counts = Counter(data["label"])
# 计算每个类别样本数占总数的比例
class_probs = [class_count / len(data["label"]) for class_count in class_counts.values()]
# 计算信息熵
entropy = sum([-class_prob * math.log(class_prob, 2) for class_prob in class_probs])
return entropy
def find_best_split(data, features):
"""
找到最佳分裂特征和特征值
"""
# 计算数据集的信息熵
entropy = find_entropy(data)
# 初始化最佳分裂特征和特征值
best_feature, best_value = None, None
# 初始化最小信息增益
min_info_gain = float("inf")
# 遍历每个特征
for feature in features:
# 找到该特征的所有取值
values = set(data[feature])
# 遍历每个取值
for value in values:
# 将数据集分成两部分
left_data = data[data[feature] == value]
right_data = data[data[feature] != value]
# 如果分裂后的数据集不为空
if len(left_data) > 0 and len(right_data) > 0:
# 计算分裂后的信息熵
left_entropy = find_entropy(left_data)
right_entropy = find_entropy(right_data)
split_entropy = (len(left_data) / len(data)) * left_entropy + (len(right_data) / len(data)) * right_entropy
# 计算信息增益
info_gain = entropy - split_entropy
# 如果信息增益更大,则更新最佳分裂特征和特征值
if info_gain < min_info_gain:
best_feature, best_value = feature, value
min_info_gain = info_gain
# 返回最佳分裂特征和特征值
return best_feature, best_value
def build_tree(data, features):
"""
构建决策树
"""
# 如果数据集为空,则返回 None
if len(data) == 0:
return None
# 如果数据集中所有样本都属于同一类别,则返回该类别
if len(set(data["label"])) == 1:
return data["label"].iloc[0]
# 如果没有可用特征,则返回数据集中样本数最多的类别
if len(features) == 0:
return Counter(data["label"]).most_common(1)[0][0]
# 找到最佳分裂特征和特征值
best_feature, best_value = find_best_split(data, features)
# 如果信息增益小于等于 0,则返回数据集中样本数最多的类别
if best_feature is None or best_value is None:
return Counter(data["label"]).most_common(1)[0][0]
# 创建节点
node = {"feature": best_feature, "value": best_value, "left": None, "right": None}
# 将数据集分成两部分
left_data = data[data[best_feature] == best_value]
right_data = data[data[best_feature] != best_value]
# 递归构建左子树和右子树
node["left"] = build_tree(left_data, [feature for feature in features if feature != best_feature])
node["right"] = build_tree(right_data, [feature for feature in features if feature != best_feature])
# 返回节点
return node
```
该代码实现了 ID3 决策树算法,其中 `find_entropy` 函数用于计算数据集的信息熵,`find_best_split` 函数用于找到最佳分裂特征和特征值,`build_tree` 函数用于构建决策树。
相关推荐
















