import pandas as pd
import numpy as np
from math import exp, sqrt, pi
# 生成仿真数据集(假设的数据,你需要根据实际情况调整)
data = {
'feature1': np.random.uniform(-3, 3, 100), # 随机生成100个特征1的值
'class': np.random.choice([0, 1], 100) # 随机生成100个类别标签
}
df = pd.DataFrame(data)
# 计算先验概率
class_0_prior = len(df[df['class'] == 0]) / len(df)
class_1_prior = len(df[df['class'] == 1]) / len(df)
print(f"Class 0 Prior: {class_0_prior}")
print(f"Class 1 Prior: {class_1_prior}")
# 定义Parzen窗估计函数
def parzen_window_estimation(test_point, data_points, h):
n = len(data_points)
return sum((1 / (h * sqrt(2 * pi))) * exp(-0.5 * ((test_point - x) / h) ** 2) for x in data_points) / n
# 从数据集中提取每个类别的特征数据
feature1_class_0 = df[df['class'] == 0]['feature1']
feature1_class_1 = df[df['class'] == 1]['feature1']
# 定义核宽度h
h = 0.4
# 为测试样本估计类概率密度(选择一个范围内的随机值作为测试点)
test_point = np.random.uniform(-3.09, 3.19)
p_x_given_class_0 = parzen_window_estimation(test_point, feature1_class_0, h)
p_x_given_class_1 = parzen_window_estimation(test_point, feature1_class_1, h)
# 计算后验概率(按比例)
posterior_class_0 = p_x_given_class_0 * class_0_prior
posterior_class_1 = p_x_given_class_1 * class_1_prior
# 贝叶斯分类决策
predicted_class = 0 if posterior_class_0 > posterior_class_1 else 1
print(f"Test Point: {test_point}")
print(f"P(x|class 0): {p_x_given_class_0}")
print(f"P(x|class 1): {p_x_given_class_1}")
print(f"Posterior Class 0: {posterior_class_0}")
print(f"Posterior Class 1: {posterior_class_1}")
print(f"Predicted Class: {predicted_class}")