python实现贝叶斯决策模型代码
时间: 2023-08-06 12:04:42 浏览: 101
以下是一个简单的 Python 代码实现贝叶斯决策模型的示例:
```python
import numpy as np
class NaiveBayes:
def __init__(self):
self.classes = None
self.prior_probs = None
self.conditional_probs = None
def fit(self, X, y):
self.classes = np.unique(y)
n_classes = len(self.classes)
n_features = X.shape[1]
# 计算先验概率
self.prior_probs = np.zeros(n_classes)
for i, c in enumerate(self.classes):
self.prior_probs[i] = np.sum(y == c) / len(y)
# 计算条件概率
self.conditional_probs = np.zeros((n_classes, n_features))
for i, c in enumerate(self.classes):
X_c = X[y == c]
for j in range(n_features):
self.conditional_probs[i, j] = (X_c[:,j].mean(), X_c[:,j].std())
def predict(self, X):
y_pred = np.zeros(len(X))
for i, x in enumerate(X):
posteriors = np.zeros(len(self.classes))
for j, c in enumerate(self.classes):
prior_prob = np.log(self.prior_probs[j])
conditional_prob = 0
for k in range(len(x)):
conditional_prob += np.log(self.gaussian_pdf(x[k], self.conditional_probs[j,k,0], self.conditional_probs[j,k,1]))
posteriors[j] = prior_prob + conditional_prob
y_pred[i] = self.classes[np.argmax(posteriors)]
return y_pred
def gaussian_pdf(self, x, mean, std):
exponent = np.exp(-((x-mean)**2 / (2 * std**2)))
return (1 / (np.sqrt(2 * np.pi) * std)) * exponent
```
这个类中包含了 `fit` 和 `predict` 两个方法。`fit` 方法用于训练模型,`predict` 方法用于预测新的数据。在训练过程中,先计算每个类别的先验概率,再计算每个特征在每个类别中的条件概率。在预测时,对于每个数据点,计算每个类别的后验概率,并选择最高的后验概率作为预测结果。其中,用到了高斯分布的概率密度函数来计算连续特征的条件概率。
阅读全文