使用决策树算法进行鸢尾花数据分类(python)
时间: 2024-09-26 12:06:28 浏览: 44
python利用c4.5决策树对鸢尾花卉数据集进行分类(iris)
决策树是一种基于树形结构来进行分类和预测的机器学习算法。在Python中,我们可以使用Scikit-learn库来构建决策树模型并应用于鸢尾花(Iris)数据集,这是一个经典的分类问题。以下是基本步骤:
1. **导入必要的库**:
```python
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
```
2. **加载鸢尾花数据**:
```python
iris = datasets.load_iris()
```
3. **数据预处理**:
创建DataFrame,并划分特征(X)和目标变量(y):
```python
data = pd.DataFrame(data=iris.data, columns=iris.feature_names)
target = iris.target
```
将数据划分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42)
```
4. **创建并训练决策树模型**:
```python
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
```
5. **做出预测**:
```python
y_pred = model.predict(X_test)
```
6. **评估模型性能**:
```python
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
```
阅读全文