python 决策树算法实例
时间: 2023-07-20 17:35:52 浏览: 112
以下是使用Python中的scikit-learn库实现决策树算法的一个简单实例:
首先,导入需要的库:
```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
```
加载鸢尾花数据集:
```python
iris = load_iris()
X = iris.data
y = iris.target
```
划分训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
创建决策树分类器:
```python
clf = DecisionTreeClassifier(random_state=42)
```
训练分类器:
```python
clf.fit(X_train, y_train)
```
使用分类器进行预测:
```python
y_pred = clf.predict(X_test)
```
评估分类器的性能:
```python
acc = accuracy_score(y_test, y_pred)
print("Accuracy:", acc)
```
完整代码如下:
```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(random_state=42)
# 训练分类器
clf.fit(X_train, y_train)
# 使用分类器进行预测
y_pred = clf.predict(X_test)
# 评估分类器的性能
acc = accuracy_score(y_test, y_pred)
print("Accuracy:", acc)
```
输出结果:
```
Accuracy: 1.0
```
以上是使用Python中的scikit-learn库实现决策树算法的一个简单实例。
阅读全文