利用决策树算法对Iris数据集构建决策树
时间: 2023-07-20 07:03:25 浏览: 119
首先,我们需要导入Iris数据集和相关的库:
```python
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
```
然后,我们可以加载Iris数据集并将其拆分为训练集和测试集:
```python
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.3, random_state=42)
```
接下来,我们可以使用决策树算法来构建一个分类器:
```python
clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train, y_train)
```
最后,我们可以使用测试集来评估分类器的性能:
```python
score = clf.score(X_test, y_test)
print("Accuracy:", score)
```
完整代码如下:
```python
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
# 加载Iris数据集并拆分为训练集和测试集
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.3, random_state=42)
# 使用决策树算法构建分类器
clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train, y_train)
# 评估分类器的性能
score = clf.score(X_test, y_test)
print("Accuracy:", score)
```
阅读全文