python分类器朴素贝叶斯构建
时间: 2024-10-09 15:05:17 浏览: 66
朴素贝叶斯分类器是一种基于概率的机器学习模型,尤其适用于文本分类和垃圾邮件过滤等任务。在Python中,我们可以使用sklearn库来轻松构建这种分类器。以下是构建步骤:
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. **加载数据集** (这里以Iris数据集为例):
```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
nb_classifier = GaussianNB() # 使用高斯朴素贝叶斯(对于数值型数据)
nb_classifier.fit(X_train, y_train)
```
5. **预测和评估**:
```python
y_pred = nb_classifier.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
```
阅读全文