python实现贝叶斯判别
时间: 2023-10-14 20:06:36 浏览: 102
python基于概率论的分类算法 朴素贝叶斯原理简单,也很容易实现,多用于文本分类
贝叶斯判别是一种分类算法,它基于贝叶斯定理和特征的先验概率,通过对后验概率进行计算,从而确定样本的分类。
在Python中,可以使用sklearn库中的朴素贝叶斯算法实现贝叶斯判别。具体步骤如下:
1. 导入需要的库和数据集
```python
from sklearn.datasets import load_iris
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
```
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.3, random_state=0)
```
4. 创建分类器对象
```python
clf = GaussianNB()
```
5. 在训练集上训练分类器
```python
clf.fit(X_train, y_train)
```
6. 在测试集上进行预测
```python
y_pred = clf.predict(X_test)
```
7. 计算分类器的准确率
```python
from sklearn.metrics import accuracy_score
accuracy_score(y_test, y_pred)
```
完整代码如下:
```python
from sklearn.datasets import load_iris
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
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=0)
clf = GaussianNB()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy_score(y_test, y_pred)
```
阅读全文