朴素贝叶斯分类器python
时间: 2023-09-13 19:07:42 浏览: 37
朴素贝叶斯分类器是一种基于贝叶斯定理的分类算法,它假设所有特征之间是独立的,并且通过将每个特征的条件概率乘起来,来计算属于某个类别的概率。
Python中有很多库支持朴素贝叶斯分类器的实现,比如scikit-learn库。下面是一个使用scikit-learn库实现朴素贝叶斯分类器的示例代码:
```python
from sklearn.naive_bayes import GaussianNB
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# 加载数据集
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.3, random_state=42)
# 创建朴素贝叶斯分类器
clf = GaussianNB()
# 训练模型
clf.fit(X_train, y_train)
# 预测结果
y_pred = clf.predict(X_test)
# 输出准确率
print("Accuracy:", clf.score(X_test, y_test))
```
在上面的代码中,我们首先加载了鸢尾花数据集,然后划分数据集为训练集和测试集。接着,我们创建了一个高斯朴素贝叶斯分类器,并用训练集进行训练。最后,我们用测试集进行预测,并输出了模型的准确率。
需要注意的是,朴素贝叶斯分类器假设所有特征都是独立的,因此在实际应用中,我们需要对数据集进行预处理和特征选择,以便使得特征之间尽可能的独立。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)