贝叶斯分类器从零开始代码实现
时间: 2023-11-23 22:06:11 浏览: 36
好的,以下是贝叶斯分类器的从零开始的代码实现:
```python
import numpy as np
class NaiveBayes:
def __init__(self):
self.prior = None
self.conditional = None
def fit(self, X, y):
n_samples, n_features = X.shape
self.classes = np.unique(y)
n_classes = len(self.classes)
# 计算先验概率
self.prior = np.zeros(n_classes)
for i, c in enumerate(self.classes):
self.prior[i] = np.sum(y == c) / n_samples
# 计算条件概率
self.conditional = np.zeros((n_classes, n_features))
for i, c in enumerate(self.classes):
X_c = X[y == c]
self.conditional[i, :] = (X_c.sum(axis=0) + 1) / (np.sum(X_c) + n_features)
def predict(self, X):
y_pred = []
for x in X:
posterior = []
for i, c in enumerate(self.classes):
prior_c = np.log(self.prior[i])
conditional_c = np.sum(np.log(self.conditional[i, :]) * x)
posterior_c = prior_c + conditional_c
posterior.append(posterior_c)
y_pred.append(self.classes[np.argmax(posterior)])
return y_pred
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)