跳到正文

剪贴板

剪贴板 7s5eaecw

原文
剪贴板信息

剪贴板信息

收录
更新

好的,我将为您提供一个基于二分决策树的猫狗分类Python代码,其中所有特征和目标变量都是二分的。这种情况在实际应用中很常见,比如通过一系列”是/否”问题来进行分类。

Python
# 导入必要的库
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns

# 设置图形样式
sns.set_style("whitegrid")
plt.rcParams['font.size'] = 12

# =============================================================================
# 1. 创建二分特征的数据集
# =============================================================================
'''
创建具有二分特征的猫狗数据集
所有特征都是二元的(0或1),目标变量也是二元的(猫=0, 狗=1)

二分特征说明:
- ear_shape: 耳朵形状 (0=圆润, 1=尖三角形)
- nose_length: 鼻子长度 (0=短, 1=长)
- whisker_prominence: 胡须明显度 (0=不明显, 1=明显)
- tail_position: 尾巴姿态 (0=下垂, 1=竖起)
- body_shape: 身体形状 (0=纤细, 1=粗壮)
- sound_type: 叫声类型 (0=喵喵叫, 1=汪汪叫)
'''

np.random.seed(42)
n_samples = 1000

# 创建空的数据字典
data = {
    'ear_shape': [],
    'nose_length': [],
    'whisker_prominence': [],
    'tail_position': [],
    'body_shape': [],
    'sound_type': [],
    'animal_type': []
}

# 生成猫的数据 (标签为0)
for i in range(n_samples // 2):
    # 猫的特征概率分布
    data['ear_shape'].append(np.random.choice([0, 1], p=[0.1, 0.9]))  # 猫90%是尖耳朵
    data['nose_length'].append(np.random.choice([0, 1], p=[0.9, 0.1]))  # 猫90%是短鼻子
    data['whisker_prominence'].append(np.random.choice([0, 1], p=[0.1, 0.9]))  # 猫90%胡须明显
    data['tail_position'].append(np.random.choice([0, 1], p=[0.3, 0.7]))  # 猫70%尾巴竖起
    data['body_shape'].append(np.random.choice([0, 1], p=[0.8, 0.2]))  # 猫80%身体纤细
    data['sound_type'].append(0)  # 猫总是喵喵叫
    data['animal_type'].append(0)  # 猫的标签

# 生成狗的数据 (标签为1)
for i in range(n_samples // 2):
    # 狗的特征概率分布
    data['ear_shape'].append(np.random.choice([0, 1], p=[0.8, 0.2]))  # 狗80%是圆耳朵
    data['nose_length'].append(np.random.choice([0, 1], p=[0.2, 0.8]))  # 狗80%是长鼻子
    data['whisker_prominence'].append(np.random.choice([0, 1], p=[0.8, 0.2]))  # 狗80%胡须不明显
    data['tail_position'].append(np.random.choice([0, 1], p=[0.7, 0.3]))  # 狗70%尾巴下垂
    data['body_shape'].append(np.random.choice([0, 1], p=[0.2, 0.8]))  # 狗80%身体粗壮
    data['sound_type'].append(1)  # 狗总是汪汪叫
    data['animal_type'].append(1)  # 狗的标签

# 创建DataFrame
df = pd.DataFrame(data)

# 打乱数据顺序
df = df.sample(frac=1, random_state=42).reset_index(drop=True)

print("二分特征数据集前10行:")
print(df.head(10))
print(f"\n数据集形状: {df.shape}")
print(f"\n猫狗数量分布:\n{df['animal_type'].value_counts()}")

# =============================================================================
# 2. 数据探索和可视化
# =============================================================================

# 创建特征名称的映射字典,便于可视化
feature_names = {
    'ear_shape': {0: '圆耳朵', 1: '尖耳朵'},
    'nose_length': {0: '短鼻子', 1: '长鼻子'},
    'whisker_prominence': {0: '胡须不明显', 1: '胡须明显'},
    'tail_position': {0: '尾巴下垂', 1: '尾巴竖起'},
    'body_shape': {0: '身体纤细', 1: '身体粗壮'},
    'sound_type': {0: '喵喵叫', 1: '汪汪叫'},
    'animal_type': {0: '猫', 1: '狗'}
}

# 绘制每个特征与目标变量的关系
fig, axes = plt.subplots(2, 3, figsize=(18, 12))
fig.suptitle('二分特征与猫狗类别的关系', fontsize=16)

features = ['ear_shape', 'nose_length', 'whisker_prominence',
           'tail_position', 'body_shape', 'sound_type']

for i, feature in enumerate(features):
    row, col = i // 3, i % 3

    # 创建交叉表
    cross_tab = pd.crosstab(
        df[feature].map(feature_names[feature]),
        df['animal_type'].map(feature_names['animal_type']),
        normalize='index'
    )

    # 绘制堆叠条形图
    cross_tab.plot(kind='bar', ax=axes[row, col], color=['skyblue', 'lightcoral'])
    axes[row, col].set_title(f'{feature_names[feature][0]} vs {feature_names[feature][1]}')
    axes[row, col].set_ylabel('比例')
    axes[row, col].legend(title='动物类型')
    axes[row, col].tick_params(axis='x', rotation=45)

plt.tight_layout()
plt.show()

# =============================================================================
# 3. 准备训练数据和测试数据
# =============================================================================

# 定义特征(X)和目标变量(y)
X = df.drop('animal_type', axis=1)  # 所有二分特征
y = df['animal_type']               # 二分目标变量

print("特征矩阵形状:", X.shape)
print("目标变量形状:", y.shape)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

print(f"\n训练集大小: {X_train.shape[0]}")
print(f"测试集大小: {X_test.shape[0]}")

# =============================================================================
# 4. 创建和训练二分决策树模型
# =============================================================================
'''
对于二分特征和二分目标,我们可以使用标准的决策树分类器。
由于所有特征都是二分的,决策树的分裂将始终是二分的。
'''

# 创建决策树分类器 - 特别适合二分数据
dt_classifier = DecisionTreeClassifier(
    max_depth=3,           # 限制树的最大深度
    min_samples_split=20,  # 节点至少需要20个样本才能继续分裂
    min_samples_leaf=10,   # 叶节点至少包含10个样本
    random_state=42        # 随机种子
)

# 训练模型
print("\n开始训练二分决策树模型...")
dt_classifier.fit(X_train, y_train)
print("模型训练完成!")

# =============================================================================
# 5. 模型评估
# =============================================================================

# 在训练集和测试集上进行预测
y_train_pred = dt_classifier.predict(X_train)
y_test_pred = dt_classifier.predict(X_test)

# 计算准确率
train_accuracy = accuracy_score(y_train, y_train_pred)
test_accuracy = accuracy_score(y_test, y_test_pred)

print(f"\n模型性能评估:")
print(f"训练集准确率: {train_accuracy:.4f}")
print(f"测试集准确率: {test_accuracy:.4f}")

# 详细分类报告
print("\n详细分类报告:")
print(classification_report(y_test, y_test_pred, target_names=['猫', '狗']))

# 绘制混淆矩阵
cm = confusion_matrix(y_test, y_test_pred)
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
            xticklabels=['猫', '狗'], yticklabels=['猫', '狗'])
plt.title('混淆矩阵 - 二分决策树')
plt.ylabel('真实标签')
plt.xlabel('预测标签')
plt.show()

# =============================================================================
# 6. 可视化二分决策树
# =============================================================================

# 创建更友好的特征名称用于可视化
friendly_feature_names = {
    'ear_shape': '耳朵形状\n(0=圆,1=尖)',
    'nose_length': '鼻子长度\n(0=短,1=长)',
    'whisker_prominence': '胡须明显度\n(0=不明显,1=明显)',
    'tail_position': '尾巴姿态\n(0=下垂,1=竖起)',
    'body_shape': '身体形状\n(0=纤细,1=粗壮)',
    'sound_type': '叫声类型\n(0=喵,1=汪)'
}

# 绘制决策树
plt.figure(figsize=(20, 12))
plot_tree(dt_classifier,
          feature_names=[friendly_feature_names[col] for col in X.columns],
          class_names=['猫', '狗'],
          filled=True,
          rounded=True,
          fontsize=12,
          impurity=False,
          proportion=True)
plt.title('二分决策树 - 猫狗分类', fontsize=16, pad=20)
plt.tight_layout()
plt.show()

# =============================================================================
# 7. 特征重要性分析
# =============================================================================

# 获取特征重要性
feature_importance = dt_classifier.feature_importances_
features = X.columns

# 创建特征重要性DataFrame
importance_df = pd.DataFrame({
    'feature': [friendly_feature_names[f] for f in features],
    'importance': feature_importance
}).sort_values('importance', ascending=False)

print("\n特征重要性排序:")
print(importance_df)

# 绘制特征重要性图
plt.figure(figsize=(10, 6))
sns.barplot(data=importance_df, x='importance', y='feature', palette='viridis')
plt.title('二分特征重要性分析')
plt.xlabel('重要性得分')
plt.tight_layout()
plt.show()

# =============================================================================
# 8. 决策规则解释
# =============================================================================

print("\n=== 决策树规则解释 ===")

# 获取决策树的决策路径
def explain_decision_tree(tree, feature_names, class_names):
    n_nodes = tree.tree_.node_count
    children_left = tree.tree_.children_left
    children_right = tree.tree_.children_right
    feature = tree.tree_.feature
    threshold = tree.tree_.threshold

    print("决策树规则:")
    node_depth = np.zeros(shape=n_nodes, dtype=np.int64)
    is_leaves = np.zeros(shape=n_nodes, dtype=bool)
    stack = [(0, 0)]  # 从根节点开始 (节点id, 深度)

    while len(stack) > 0:
        node_id, depth = stack.pop()
        node_depth[node_id] = depth

        # 如果是内部节点
        if (children_left[node_id] != children_right[node_id]):
            stack.append((children_left[node_id], depth + 1))
            stack.append((children_right[node_id], depth + 1))
        else:
            is_leaves[node_id] = True

    for i in range(n_nodes):
        if is_leaves[i]:
            class_prob = tree.tree_.value[i][0]
            total_samples = class_prob.sum()
            cat_prob = class_prob[0] / total_samples * 100
            dog_prob = class_prob[1] / total_samples * 100
            print(f"叶节点 {i}: 预测为 {class_names[np.argmax(class_prob)]} "
                  f"(猫: {cat_prob:.1f}%, 狗: {dog_prob:.1f}%)")
        else:
            feature_name = feature_names[feature[i]]
            print(f"节点 {i}: 如果 {feature_name} <= {threshold[i]:.2f} 则转到节点 {children_left[i]} "
                  f"否则转到节点 {children_right[i]}")

explain_decision_tree(dt_classifier, list(X.columns), ['猫', '狗'])

# =============================================================================
# 9. 使用模型进行新预测
# =============================================================================

print("\n=== 新样本预测 ===")

# 创建几个新的二分特征样本
# 样本1: 典型的猫特征
new_sample1 = pd.DataFrame([{
    'ear_shape': 1,        # 尖耳朵
    'nose_length': 0,      # 短鼻子
    'whisker_prominence': 1, # 胡须明显
    'tail_position': 1,    # 尾巴竖起
    'body_shape': 0,       # 身体纤细
    'sound_type': 0        # 喵喵叫
}])

# 样本2: 典型的狗特征
new_sample2 = pd.DataFrame([{
    'ear_shape': 0,        # 圆耳朵
    'nose_length': 1,      # 长鼻子
    'whisker_prominence': 0, # 胡须不明显
    'tail_position': 0,    # 尾巴下垂
    'body_shape': 1,       # 身体粗壮
    'sound_type': 1        # 汪汪叫
}])

# 样本3: 混合特征 (可能难以分类)
new_sample3 = pd.DataFrame([{
    'ear_shape': 1,        # 尖耳朵 (猫特征)
    'nose_length': 1,      # 长鼻子 (狗特征)
    'whisker_prominence': 1, # 胡须明显 (猫特征)
    'tail_position': 0,    # 尾巴下垂 (狗特征)
    'body_shape': 0,       # 身体纤细 (猫特征)
    'sound_type': 0        # 喵喵叫 (猫特征)
}])

new_samples = pd.concat([new_sample1, new_sample2, new_sample3], ignore_index=True)

# 进行预测
predictions = dt_classifier.predict(new_samples)
prediction_proba = dt_classifier.predict_proba(new_samples)

print("新样本预测结果:")
for i, (pred, proba) in enumerate(zip(predictions, prediction_proba)):
    animal = "猫" if pred == 0 else "狗"
    cat_prob = proba[0] * 100
    dog_prob = proba[1] * 100

    print(f"\n样本{i+1}特征:")
    for feature, value in new_samples.iloc[i].items():
        print(f"  {friendly_feature_names[feature]}: {value}")

    print(f"预测结果: {animal} | 猫的概率: {cat_prob:.2f}% | 狗的概率: {dog_prob:.2f}%")

# =============================================================================
# 10. 模型优势和局限性分析
# =============================================================================

print("\n=== 二分决策树模型分析 ===")
print("优势:")
print("1. 模型简单易懂,决策规则明确")
print("2. 所有特征都是二分的,便于理解和应用")
print("3. 计算效率高,适合实时预测")
print("4. 对缺失值相对鲁棒")
print("5. 能够处理特征间的交互作用")

print("\n局限性:")
print("1. 可能对训练数据过拟合,需要适当剪枝")
print("2. 对数据的小变化可能敏感(不稳定)")
print("3. 只能创建与坐标轴平行的决策边界")
print("4. 如果某个二分特征很重要但被早期错误排除,可能影响性能")

print("\n改进建议:")
print("1. 使用随机森林集成多个决策树以提高稳定性")
print("2. 通过交叉验证选择最优的树深度参数")
print("3. 考虑特征工程,创建更有区分度的二分特征")

二分决策树的核心特点:

1. 数据特征

  • 所有输入特征都是二值的(0或1)
  • 目标变量也是二值的(猫或狗)
  • 这种结构使得决策树非常直观

2. 决策过程

  • 每个内部节点测试一个二分特征
  • 每个分支对应特征的一个可能值(0或1)
  • 从根节点到叶节点的路径就是一系列”是/否”问题的答案

3. 模型优势

  • 可解释性强:决策规则清晰明了
  • 计算高效:二分决策简单快速
  • 无需标准化:所有特征已经是可比尺度

4. 实际应用场景

  • 医疗诊断(症状有/无)
  • 质量控制(合格/不合格)
  • 客户分类(购买/未购买)
  • 风险评估(高风险/低风险)

5. 决策树输出解释

在二分决策树中,每个叶节点会显示:

  • 该节点中猫和狗的样本数量或比例
  • 基于多数投票的预测类别
  • 分类的置信度

这种二分特征的决策树在实际业务场景中非常实用,因为它对应着人们自然的决策思维方式——通过一系列”是/否”问题来得出结论。