能否提供一个详细的基于决策树算法的MNIST手写数字识别的Python代码示例,包括数据预处理、模型构建和训练过程?
时间: 2024-11-04 20:14:21 浏览: 21
当然可以。以下是使用scikit-learn库实现的一个简单决策树模型用于MNIST手写数字识别的Python代码示例:
```python
# 导入所需库
import numpy as np
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# 加载MNIST数据集
mnist = fetch_openml('mnist_784', version=1)
X, y = mnist['data'], mnist['target']
# 数据预处理
# 将像素值缩放到0到1之间
X = X.astype('float32') / 255.
# 将标签转换为整数数组
y = y.astype(np.uint8)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 标准化数据
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 创建决策树分类器
clf = DecisionTreeClassifier(random_state=42)
# 模型训练
clf.fit(X_train, y_train)
# 预测
y_pred = clf.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy * 100:.2f}%")
# 相关问题--
阅读全文