朴素贝叶斯算法python
时间: 2023-10-24 21:26:16 浏览: 38
朴素贝叶斯算法是一种基于概率统计的分类方法,它的思想是根据已知的训练数据集,通过特征之间的条件独立性假设,利用贝叶斯公式计算出每个类别的概率,然后将待分类样本的特征值代入计算,最终确定其所属类别。
在Python中,可以使用scikit-learn库中的朴素贝叶斯算法实现分类。具体步骤如下:
1.导入需要的库和数据
```
from sklearn.naive_bayes import GaussianNB # 高斯朴素贝叶斯算法
from sklearn import datasets # 数据集
```
2.加载数据集
```
iris = datasets.load_iris()
X = iris.data
y = iris.target
```
3.拆分数据集
```
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
```
4.训练模型
```
gnb = GaussianNB()
gnb.fit(X_train, y_train)
```
5.预测结果
```
y_pred = gnb.predict(X_test)
```
6.评估模型
```
from sklearn.metrics import accuracy_score
accuracy_score(y_test, y_pred)
```
完整代码如下:
```
from sklearn.naive_bayes import GaussianNB # 高斯朴素贝叶斯算法
from sklearn import datasets # 数据集
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据集
iris = datasets.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=0)
# 训练模型
gnb = GaussianNB()
gnb.fit(X_train, y_train)
# 预测结果
y_pred = gnb.predict(X_test)
# 评估模型
accuracy_score(y_test, y_pred)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)