使用决策树分类python
时间: 2024-06-20 14:00:41 浏览: 14
决策树是一种常用的机器学习算法,特别适合做分类和回归任务。在Python中,你可以使用`scikit-learn`库来构建决策树。以下是一个简单的步骤:
1. **安装scikit-learn**:
如果你还没有安装,可以使用pip安装:
```bash
pip install scikit-learn
```
2. **导入必要的模块**:
```python
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import pandas as pd
```
3. **加载数据**:
假设你想用鸢尾花数据集(Iris dataset):
```python
iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['target'] = iris.target
```
4. **数据预处理**:
将数据划分为特征(X)和目标变量(y),并可能进行归一化或编码分类变量:
```python
X = df.drop('target', axis=1)
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
5. **创建决策树模型**:
```python
classifier = tree.DecisionTreeClassifier()
```
6. **拟合模型**:
```python
classifier.fit(X_train, y_train)
```
7. **预测新数据**:
```python
predictions = classifier.predict(X_test)
```
8. **评估模型**:
使用`accuracy_score`, `confusion_matrix`, 或其他评估指标:
```python
from sklearn.metrics import accuracy_score
print("Accuracy: ", accuracy_score(y_test, predictions))
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)