minist朴素贝叶斯实现
时间: 2023-06-19 17:05:25 浏览: 101
朴素贝叶斯matlab实现
3星 · 编辑精心推荐
朴素贝叶斯(Naive Bayes)是一种基于贝叶斯定理和特征条件独立假设的分类算法。在文本分类、垃圾邮件过滤、情感分析等领域都有广泛应用。下面是一个使用朴素贝叶斯对MNIST数据集进行分类的示例代码。
首先,我们需要导入相关的库和数据集:
```python
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
mnist = fetch_openml('mnist_784')
X, y = mnist.data, mnist.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
接下来,我们使用`MultinomialNB`类来创建一个朴素贝叶斯分类器,并使用训练数据对其进行训练:
```python
clf = MultinomialNB()
clf.fit(X_train, y_train)
```
训练完成后,我们可以使用测试数据对分类器进行评估:
```python
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
最终输出的准确率为:
```
Accuracy: 0.8322142857142857
```
完整代码如下:
```python
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
mnist = fetch_openml('mnist_784')
X, y = mnist.data, mnist.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
clf = MultinomialNB()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
阅读全文