Python 实现朴素贝叶斯分类器 - 代码详解
这是一个朴素贝叶斯分类器的 Python 实现代码,它包含以下几个方法和属性:
-
__init__(self): 初始化方法,用于创建一个 NaiveBayesClassifier 对象。它初始化了先验概率 (prior)、条件概率 (conditional_prob) 和标签 (labels)。 -
fit(self, X, y): 训练方法,用于训练分类器。它接受训练数据 X 和标签 y 作为输入,并计算先验概率和条件概率。先验概率是每个类别出现的概率,条件概率是每个特征在给定类别下的概率。 -
predict(self, X): 预测方法,用于对输入数据 X 进行分类预测。它接受一个数据集作为输入,并返回预测的标签列表。预测过程中,根据先验概率和条件概率计算后验概率,并选择具有最大后验概率的类别作为预测结果。
class NaiveBayesClassifier:
def __init__(self):
self.prior = {}
self.conditional_prob = {}
self.labels = None
def fit(self, X, y):
self.labels, counts = np.unique(y, return_counts=True)
total_samples = X.shape[0]
for label, count in zip(self.labels, counts):
self.prior[label] = (count + 1) / (total_samples + len(self.labels))
for feature_index in range(X.shape[1]):
feature_values = np.unique(X[:, feature_index])
self.conditional_prob[feature_index] = {}
for feature_value in feature_values:
self.conditional_prob[feature_index][feature_value] = {}
for label in self.labels:
numerator = np.sum((X[:, feature_index] == feature_value) & (y == label)) + 1
denominator = np.sum(y == label) + len(feature_values)
self.conditional_prob[feature_index][feature_value][label] = numerator / denominator
def predict(self, X):
predictions = []
for sample in X:
max_posterior = float('-inf')
predicted_label = None
for label in self.labels:
posterior = np.log(self.prior[label])
for feature_index, feature_value in enumerate(sample):
conditional_prob = self.conditional_prob[feature_index][feature_value][label]
posterior += np.log(conditional_prob)
if posterior > max_posterior:
max_posterior = posterior
predicted_label = label
predictions.append(predicted_label)
return predictions
其中,先验概率的计算公式为:(count + 1) / (total_samples + len(self.labels)),其中 count 为某个类别的样本数量,total_samples 为总样本数量,len(self.labels) 为类别的数量。这里使用了拉普拉斯平滑,避免出现概率为 0 的情况。
条件概率的计算公式为:(numerator + 1) / (denominator + len(feature_values)),其中 numerator 为某个特征值在某个类别下的出现次数,denominator 为某个类别的样本数量,len(feature_values) 为特征的取值数量。同样使用了拉普拉斯平滑。
在预测过程中,计算每个类别的后验概率,并选择具有最大后验概率的类别作为预测结果。为了避免概率相乘时出现下溢问题,使用了对数运算,将乘法转换为加法。
原文地址: https://www.cveoy.top/t/topic/pkbx 著作权归作者所有。请勿转载和采集!