贝叶斯分类器有哪些,列出代码
时间: 2024-03-18 10:16:49 浏览: 59
常见的贝叶斯分类器有朴素贝叶斯分类器和多项式朴素贝叶斯分类器。
朴素贝叶斯分类器代码:
```python
from collections import Counter
import math
class NaiveBayesClassifier:
def __init__(self):
self.classes = None
self.class_word_counts = {}
self.class_total_counts = {}
self.vocabulary = set()
def train(self, X_train, y_train):
self.classes = set(y_train)
for c in self.classes:
self.class_word_counts[c] = Counter()
self.class_total_counts[c] = 0
for x, y in zip(X_train, y_train):
self.class_word_counts[y].update(x)
self.class_total_counts[y] += sum(x)
self.vocabulary.update(x)
def predict(self, x):
class_scores = {}
for c in self.classes:
score = math.log(self.class_total_counts[c])
for word in x:
count = self.class_word_counts[c][word] + 1
total = self.class_total_counts[c] + len(self.vocabulary)
score += math.log(count / total)
class_scores[c] = score
return max(class_scores, key=class_scores.get)
```
多项式朴素贝叶斯分类器代码:
```python
from collections import Counter
import math
class MultinomialNaiveBayesClassifier:
def __init__(self):
self.classes = None
self.class_word_counts = {}
self.class_total_counts = {}
self.vocabulary = set()
def train(self, X_train, y_train):
self.classes = set(y_train)
for c in self.classes:
self.class_word_counts[c] = Counter()
self.class_total_counts[c] = 0
for x, y in zip(X_train, y_train):
self.class_word_counts[y].update(x)
self.class_total_counts[y] += sum(x)
self.vocabulary.update(x)
def predict(self, x):
class_scores = {}
for c in self.classes:
score = math.log(self.class_total_counts[c])
for word in x:
count = self.class_word_counts[c][word] + 1
total = self.class_total_counts[c] + len(self.vocabulary)
score += math.log(count / total)
class_scores[c] = score
return max(class_scores, key=class_scores.get)
```
阅读全文