用python代码实现朴贝叶斯方法算法
时间: 2023-08-15 20:30:46 浏览: 92
python实现朴素贝叶斯算法
5星 · 资源好评率100%
以下是一个简单的朴素贝叶斯分类器的Python代码实现:
```python
import numpy as np
class NaiveBayes:
def __init__(self):
self.classes = None
self.class_prob = None
self.feature_prob = None
def fit(self, X, y):
self.classes = np.unique(y)
num_classes = len(self.classes)
num_features = X.shape[1]
self.class_prob = np.zeros(num_classes)
self.feature_prob = np.zeros((num_classes, num_features))
for i, c in enumerate(self.classes):
X_c = X[c == y]
self.class_prob[i] = X_c.shape[0] / X.shape[0]
self.feature_prob[i, :] = X_c.sum(axis=0) / X_c.sum()
def predict(self, X):
y_pred = []
for x in X:
probabilities = []
for i, c in enumerate(self.classes):
probability = np.log(self.class_prob[i])
for j in range(len(x)):
probability += np.log(self.feature_prob[i, j]) if x[j] == 1 else np.log(1 - self.feature_prob[i, j])
probabilities.append(probability)
idx = np.argmax(probabilities)
y_pred.append(self.classes[idx])
return y_pred
```
这个朴素贝叶斯分类器使用的是二进制特征,并假设特征之间条件独立。`fit`函数用于拟合模型,计算每个类别的先验概率和每个特征的条件概率。`predict`函数用于预测新数据点的类别。
阅读全文