python写一个贝叶斯模型
时间: 2024-05-14 10:17:17 浏览: 131
好的,下面是一个简单的贝叶斯模型的 Python 代码示例:
```python
import numpy as np
class NaiveBayes:
def __init__(self):
self.classes = None
self.class_priors = None
self.conditional_probs = None
def fit(self, X, y):
self.classes = np.unique(y)
self.class_priors = np.zeros(len(self.classes))
self.conditional_probs = {}
# 计算先验概率
for c in self.classes:
self.class_priors[c] = np.mean(y == c)
# 计算条件概率
for c in self.classes:
X_c = X[y == c]
self.conditional_probs[c] = {}
for i in range(X.shape[1]):
self.conditional_probs[c][i] = {}
for val in np.unique(X[:, i]):
self.conditional_probs[c][i][val] = np.mean(X_c[:, i] == val)
def predict(self, X):
y_pred = np.zeros(X.shape[0])
for i, x in enumerate(X):
posteriors = []
for c in self.classes:
prior = np.log(self.class_priors[c])
posterior = prior
for j, val in enumerate(x):
likelihood = np.log(self.conditional_probs[c][j][val])
posterior += likelihood
posteriors.append(posterior)
y_pred[i] = self.classes[np.argmax(posteriors)]
return y_pred
```
这是一个简单的朴素贝叶斯分类器实现。其中,fit() 方法用于训练模型,predict() 方法用于预测新数据。在 fit() 方法中,我们计算了每个类别的先验概率和每个特征在每个类别下的条件概率。在 predict() 方法中,我们使用计算出来的先验概率和条件概率来计算每个类别的后验概率,并选择具有最高后验概率的类别作为预测结果。
阅读全文