用决策树实现mnist数据集python
时间: 2023-07-02 20:23:33 浏览: 101
使用adaboost,贝叶斯朴素法,决策树,knn,逻辑斯蒂,最大熵,svm,感知机算法实现了MNIST数据集学习并分类
好的,我可以给您提供一些实现决策树对 MNIST 数据集的 Python 代码。
首先,导入必要的库:
``` python
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```
然后,加载 MNIST 数据集:
``` python
digits = load_digits()
X = digits.data
y = digits.target
```
接着,将数据集划分为训练集和测试集:
``` python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
然后,定义并训练决策树模型:
``` python
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
```
最后,使用训练好的模型对测试集进行预测,并计算准确率:
``` python
y_pred = clf.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print("Accuracy:", acc)
```
完整代码如下:
``` python
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
digits = load_digits()
X = digits.data
y = digits.target
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)
acc = accuracy_score(y_test, y_pred)
print("Accuracy:", acc)
```
希望这个代码能够对您有所帮助!
阅读全文