先进模式识别技术作业
求判别函数,对样本X=(0,0)进行分类,作图可视化边界。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.naive_bayes import GaussianNB
from sklearn.datasets import make_blobs
# 创建模拟数据
X, y = make_blobs(n_samples=100, centers=2, random_state=42)
# 训练贝叶斯分类器
classifier = GaussianNB()
classifier.fit(X, y)
# 定义网格以绘制决策边界
h = .02 # 步长
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = classifier.predict(np.c_[xx.ravel(), yy.ravel()])
# 将结果放入颜色图
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=0.4)
plt.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k')
# 对样本X=(0, 0)进行分类
sample_to_predict = np.array([[0, 0]])
predicted_class = classifier.predict(sample_to_predict)
plt.scatter(sample_to_predict[:, 0], sample_to_predict[:, 1], marker='o', c='red', s=200, label=f"Predicted: {predicted_class[0]}")
plt.legend()
plt.title("Decision Boundary and Sample Classification")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.show()