python实现wine数据集实现一个朴素贝叶斯分类器
时间: 2024-03-27 16:39:11 浏览: 120
好的,我可以为您提供一个简单的代码实现。
首先,我们需要导入所需的库和数据集:
```python
import pandas as pd
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
```
```python
wine = load_wine()
X = wine.data
y = wine.target
```
接着,我们将数据集分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
然后,我们将朴素贝叶斯分类器实例化,并将训练数据拟合到分类器中:
```python
gnb = GaussianNB()
gnb.fit(X_train, y_train)
```
最后,我们可以使用测试集来评估分类器的性能:
```python
accuracy = gnb.score(X_test, y_test)
print("Accuracy:", accuracy)
```
完整的代码如下:
```python
import pandas as pd
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
wine = load_wine()
X = wine.data
y = wine.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
gnb = GaussianNB()
gnb.fit(X_train, y_train)
accuracy = gnb.score(X_test, y_test)
print("Accuracy:", accuracy)
```
希望这个简单的代码可以帮助您实现朴素贝叶斯分类器。
阅读全文