分别利用支持向量机和朴素贝叶斯实现Mnist数据集的分类,写出python代码
时间: 2024-02-27 14:53:09 浏览: 79
好的,以下是使用支持向量机和朴素贝叶斯实现 Mnist 数据集分类的 Python 代码:
使用支持向量机:
```python
from sklearn import svm
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
# 加载 Mnist 数据集
mnist = fetch_openml('mnist_784')
X = mnist.data / 255.0
y = mnist.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 搭建 SVM 模型
clf = svm.SVC(C=5, kernel='rbf', gamma=0.05, decision_function_shape='ovr')
clf.fit(X_train, y_train)
# 在测试集上进行预测
acc = clf.score(X_test, y_test)
print('Accuracy:', acc)
```
使用朴素贝叶斯:
```python
from sklearn import naive_bayes
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
# 加载 Mnist 数据集
mnist = fetch_openml('mnist_784')
X = mnist.data / 255.0
y = mnist.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 搭建朴素贝叶斯模型
clf = naive_bayes.MultinomialNB()
clf.fit(X_train, y_train)
# 在测试集上进行预测
acc = clf.score(X_test, y_test)
print('Accuracy:', acc)
```
以上代码仅供参考,实际应用中还需根据具体情况进行调参和优化。
阅读全文