id3决策树python调包实现
时间: 2023-12-19 10:30:35 浏览: 84
可以使用Python中的scikit-learn库来实现ID3决策树。具体步骤如下:
1.导入需要的库和数据集
```python
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
```
2.将数据集分为训集和测试集
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
```
3.创建决策树模型并进行训练
```python
# 创建决策树模型
clf = DecisionTreeClassifier(criterion='entropy')
# 训练模型
clf.fit(X_train, y_train)
```
4.使用测试集进行预测并计算准确率
```python
# 预测测试集
y_pred = clf.predict(X_test)
# 计算准确率
accuracy = clf.score(X_test, y_test)
print('Accuracy:', accuracy)
```
完整代码如下:
```python
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
# 加载数据集
iris = datasets.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=1)
# 创建决策树模型
clf = DecisionTreeClassifier(criterion='entropy')
# 训练模型
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
# 计算准确率
accuracy = clf.score(X_test, y_test)
print('Accuracy:', accuracy)
```
阅读全文