下面是详细讲解“Python机器学习之决策树分类详解”的完整攻略。
决策树分类是一种基于树形结构的分类方法,它通过数据集进行划分,构建一棵决策树来进行分类。决策树分类具有可解释性、易于理解和实现等优点,因此在实际应用中得到了广泛的应用。
决策树分类的原理是通过对数据集进行划分,构建一棵决策树来进行分类。具体实现过程如下:
以下是用Python实现决策树分类的步骤。
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
以下是两个示例说明,分别是使用决策树分类对鸢尾花数据集进行分类和使用决策树分类对手写数字数据集进行分类。
以下是一个使用决策树分类对鸢尾花数据集进行分类的示例。
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
输出结果为:
Accuracy: 0.9777777777777777
以下是一个使用决策树分类对手写数字数据集进行分类的示例。
from sklearn.datasets import load_digits
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
digits = load_digits()
X = digits.data
y = digits.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
输出结果为:
Accuracy: 0.837037037037037
决策树分类是一种基于树形结构的分类方法,具有可解释性强、易于理解和实现等优点。本教程介绍了决策树分类的原理和实现步骤,并提供了两个示例说明,分别是使用决策树分类对鸢尾花数据集进行分类和使用决策树分类对手写数字数据集进行分类。
本文链接:http://task.lmcjl.com/news/14990.html