利用python实现朴素贝叶斯分类器
时间: 2024-10-29 18:15:52 浏览: 46
python实现朴素贝叶斯分类器
朴素贝叶斯分类器是一种基于概率统计的简单而强大的机器学习算法。在Python中,可以使用scikit-learn库来轻松实现它。下面是基本步骤:
1. 导入所需的库:
```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
```
2. 加载数据集并预处理:
```python
data = load_iris()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
3. 创建并训练朴素贝叶斯模型:
```python
gnb = GaussianNB() # 使用高斯朴素贝叶斯,默认适合数值型特征
gnb.fit(X_train, y_train)
```
4. 预测测试集结果:
```python
predictions = gnb.predict(X_test)
```
5. 评估模型性能:
```python
accuracy = accuracy_score(y_test, predictions)
print("Accuracy:", accuracy)
```
阅读全文