决策树训练橘子分级python
时间: 2023-07-08 11:54:25 浏览: 97
python实现决策树分类
5星 · 资源好评率100%
要使用决策树对橘子进行分级,可以使用Python中的scikit-learn库。以下是实现的步骤:
1. 导入需要的库。
```
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```
2. 读取橘子的数据集。
```
data = pd.read_csv('juzi.csv')
```
数据集中应包含橘子的特征,以及对应的分级标签。
3. 将数据集分成训练集和测试集。
```
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. 定义决策树模型并进行训练。
```
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
```
5. 对测试集进行预测并计算准确率。
```
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("准确率:", accuracy)
```
完整代码如下:
```
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
data = pd.read_csv('juzi.csv')
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, 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)
```
其中,juzi.csv文件为包含橘子特征和分级标签的数据集文件。运行代码后,会输出决策树的准确率。
阅读全文