朴素贝叶斯分类器python实验包公
时间: 2024-10-24 21:04:14 浏览: 56
朴素贝叶斯分类器是一种基于概率统计的简单而有效的机器学习算法,它假设特征之间相互独立,适合处理文本分类等问题。在Python中,我们可以使用scikit-learn库来方便地实现朴素贝叶斯分类器。以下是简单的步骤:
1. 首先,你需要安装`scikit-learn`库,如果尚未安装,可以使用pip命令:
```
pip install scikit-learn
```
2. 导入所需的模块:
```python
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
```
3. 加载数据集,例如Iris数据集:
```python
iris = load_iris()
X = iris.data
y = iris.target
```
4. 划分训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
5. 创建并训练朴素贝叶斯模型:
```python
gnb = GaussianNB()
gnb.fit(X_train, y_train)
```
6. 预测测试集结果,并计算准确率:
```python
y_pred = gnb.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
```
阅读全文