决策树是机器学习中常用的监督学习算法,适用于分类和回归任务。以下是使用 scikit-learn 实现决策树的基本步骤:

  1. 安装与导入
    确保已安装 scikit-learn,若未安装可运行:

    pip install scikit-learn
    

    导入必要模块:

    from sklearn.datasets import load_iris
    from sklearn.tree import DecisionTreeClassifier, plot_tree
    from sklearn.model_selection import train_test_split
    import matplotlib.pyplot as plt
    
  2. 数据准备
    使用内置数据集(如鸢尾花数据集)或加载自定义数据:

    X, y = load_iris(return_X_y=True)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    
    Scikit_Learn
  3. 训练模型
    创建决策树分类器并拟合数据:

    clf = DecisionTreeClassifier()
    clf.fit(X_train, y_train)
    

    模型训练完成后,可通过 clf.score(X_test, y_test) 评估性能。

  4. 可视化决策树
    使用 plot_tree 绘制树结构:

    plt.figure(figsize=(12,8))
    plot_tree(clf, filled=True)
    plt.show()
    
    Decision_Tree
  5. 预测与应用
    对新数据进行预测:

    prediction = clf.predict([[5.1, 3.4, 1.5, 0.2]])
    

    预测结果将返回分类标签(如鸢尾花种类)。

如需深入了解决策树的参数调优或集成学习方法,可参考本站扩展教程:
/[scikit-learn/decision-tree-advanced]