帮我写一个朴素贝叶斯算法用python
时间: 2023-06-06 12:06:21 浏览: 114
好的,我可以帮您写一个朴素贝叶斯算法,以下是代码示例:
```python
import pandas as pd
import numpy as np
class NaiveBayes:
def __init__(self):
self.class_priors = None
self.conditional_prob = None
def fit(self, X, y):
n_samples, n_features = X.shape
# 计算先验概率
self.class_priors = {}
for c in np.unique(y):
self.class_priors[c] = np.mean(y == c)
# 计算条件概率
self.conditional_prob = {}
for f in range(n_features):
self.conditional_prob[f] = {}
for c in np.unique(y):
X_c = X[y == c]
self.conditional_prob[f][c] = {
'mean': X_c[:, f].mean(),
'std': X_c[:, f].std(),
}
def predict(self, X):
n_samples, n_features = X.shape
classes = list(self.class_priors.keys())
n_classes = len(classes)
# 计算后验概率
posterior_prob = np.zeros((n_samples, n_classes))
for i in range(n_samples):
for j in range(n_classes):
class_prior = self.class_priors[classes[j]]
posterior_prob[i, j] = np.log(class_prior)
for f in range(n_features):
mean = self.conditional_prob[f][classes[j]]['mean']
std = self.conditional_prob[f][classes[j]]['std']
x = X[i, f]
likelihood = self._gaussian_pdf(x, mean, std)
posterior_prob[i, j] += np.log(likelihood)
# 返回预测结果
return [classes[np.argmax(posterior_prob[i, :])] for i in range(n_samples)]
@staticmethod
def _gaussian_pdf(x, mean, std):
eps = 1e-4
variance = np.maximum(std ** 2, eps)
return np.exp(-0.5 * ((x - mean) ** 2) / variance) / np.sqrt(2 * np.pi * variance)
```
此处为一个朴素贝叶斯分类器的示例代码,您可以根据自己的需求调整和扩展代码。
阅读全文