python 朴素贝叶斯实现,不是用库
时间: 2024-01-31 09:02:55 浏览: 25
下面是一个简单的 python 实现朴素贝叶斯分类器的示例代码:
```python
import math
class NaiveBayesClassifier:
def __init__(self):
self.classes = {}
self.freq = {}
self.total_docs = 0
def train(self, documents, labels):
# 计算每个类别的文档数
for label in labels:
if label not in self.classes:
self.classes[label] = 1
else:
self.classes[label] += 1
# 计算每个单词在每个类别中出现的次数
for i, doc in enumerate(documents):
label = labels[i]
if label not in self.freq:
self.freq[label] = {}
for word in doc:
if word not in self.freq[label]:
self.freq[label][word] = 1
else:
self.freq[label][word] += 1
# 计算总文档数
self.total_docs = len(documents)
def classify(self, document):
# 计算每个类别的先验概率
prior_prob = {}
for label in self.classes:
prior_prob[label] = math.log(self.classes[label] / self.total_docs)
# 计算每个类别的条件概率
cond_prob = {}
for label in self.freq:
cond_prob[label] = {}
for word in self.freq[label]:
cond_prob[label][word] = math.log((self.freq[label][word] + 1) / (sum(self.freq[label].values()) + len(self.freq[label])))
# 计算文档属于每个类别的概率
scores = {}
for label in prior_prob:
score = prior_prob[label]
for word in document:
if word in cond_prob[label]:
score += cond_prob[label][word]
scores[label] = score
# 返回概率最大的类别
return max(scores, key=scores.get)
```
在上面的代码中,`train()` 方法用于训练分类器,`documents` 参数是一个列表,包含所有训练文档,每个文档是一个列表,包含所有单词;`labels` 参数是一个列表,包含所有训练文档的分类标签。`classify()` 方法用于分类新文档,`document` 参数是一个列表,包含新文档中的所有单词。在分类过程中,先计算每个类别的先验概率和每个单词在每个类别中出现的条件概率,然后根据贝叶斯公式计算文档属于每个类别的概率,最后返回概率最大的类别作为文档的分类结果。