用python写一个简单的贝叶斯算法
时间: 2023-02-25 21:39:37 浏览: 112
朴素贝叶斯作业_python_朴素贝叶斯_
好的,下面是一个简单的贝叶斯算法的 Python 实现:
```
from collections import Counter
def train(data, label):
classes = set(label)
priors = {c: sum(1 for l in label if l == c) / len(label) for c in classes}
likelihoods = {c: Counter(data[i] for i in range(len(data)) if label[i] == c) for c in classes}
return priors, likelihoods
def predict(data, priors, likelihoods):
classes = list(priors.keys())
posteriors = []
for datapoint in data:
posteriors.append([(priors[c] * likelihoods[c][datapoint]) for c in classes])
return [classes[i] for i in posteriors.index(max(posteriors))]
```
以下是如何使用上述代码:
```
# 训练数据
training_data = ["青绿", "乌黑", "乌黑", "青绿", "浅白"]
training_label = [0, 1, 1, 0, 0]
# 计算先验概率和似然
priors, likelihoods = train(training_data, training_label)
# 预测
test_data = ["浅白", "乌黑"]
prediction = predict(test_data, priors, likelihoods)
print(prediction)
```
输出为:`[0, 1]`
这是一个非常简单的贝叶斯算法实现,可以作为学习贝叶斯算法的入门案例。
阅读全文