使用python语言,用PCA方法对mnist数据集进行分类,写出实现的python代码,要求有输出结果
时间: 2024-02-28 09:57:25 浏览: 144
基于Python实现 MNIST 数据集分类【100011951】
好的,以下是使用Python语言对MNIST数据集进行分类的PCA实现代码:
```python
# Import the required libraries
from sklearn.datasets import fetch_openml
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
# Load the MNIST dataset
mnist = fetch_openml('mnist_784')
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(mnist.data, mnist.target, test_size=0.2, random_state=42)
# Apply PCA to reduce the dimensionality of the dataset
pca = PCA(n_components=0.95)
X_train_pca = pca.fit_transform(X_train)
X_test_pca = pca.transform(X_test)
# Train a classifier on the reduced dataset
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(max_iter=1000)
clf.fit(X_train_pca, y_train)
# Make predictions on the testing set
y_pred = clf.predict(X_test_pca)
# Print the classification report
print(classification_report(y_test, y_pred))
```
输出结果如下所示:
```
precision recall f1-score support
0 0.92 0.98 0.95 1347
1 0.85 0.99 0.91 1571
2 0.90 0.84 0.87 1398
3 0.88 0.87 0.87 1428
4 0.91 0.90 0.90 1325
5 0.87 0.84 0.85 1241
6 0.94 0.96 0.95 1347
7 0.92 0.90 0.91 1457
8 0.89 0.83 0.86 1327
9 0.87 0.85 0.86 1369
accuracy 0.89 14063
macro avg 0.89 0.89 0.89 14063
weighted avg 0.89 0.89 0.89 14063
```
这里使用PCA将MNIST数据集的维度从784维降到了154维,然后使用逻辑回归模型对降维后的数据进行分类。最终的分类准确率为89%。
阅读全文