用鸢尾花数据集复现一下朴素贝叶斯算法
时间: 2023-10-24 20:00:54 浏览: 97
要复现朴素贝叶斯算法使用鸢尾花数据集,您可以按照以下步骤进行操作:
1. 导入所需的库:
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
```
2. 加载鸢尾花数据集:
```python
iris = load_iris()
X = iris.data
y = iris.target
```
3. 将数据集拆分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. 初始化朴素贝叶斯分类器并进行训练:
```python
gnb = GaussianNB()
gnb.fit(X_train, y_train)
```
5. 使用训练好的模型进行预测:
```python
y_pred = gnb.predict(X_test)
```
6. 计算准确率:
```python
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
完整的代码如下所示:
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
gnb = GaussianNB()
gnb.fit(X_train, y_train)
y_pred = gnb.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
以上代码将使用朴素贝叶斯算法对鸢尾花数据集进行分类,并输出准确率。
阅读全文