"""从训练集估计尺度,比较最近 1 个和最近 3 个样本的投票。""" import json import matplotlib.pyplot as plt import numpy as np def neighbors(train, query, mean, scale, k): # query 每行是一个待预测点。广播后,三个轴依次是查询、训练、特征。 # 同一组训练均值与标准差作用于查询和训练,距离才可比。 z_train = (train - mean) / scale z_query = (query - mean) / scale # 沿特征轴累加得平方距离。排序与开根后的欧氏距离顺序一致。 distance2 = np.sum((z_query[:, None, :] - z_train[None, :, :]) ** 2, axis=2) # 稳定排序使等距样本按训练行号先后进入候选。 return np.argsort(distance2, axis=1, kind="stable")[:, :k] def run(): # 两个合成传感器的单位不同。第五条位于类别交界且带有负类标签。 train = np.array([[1, 7], [2, 20], [3, 25], [4, 50], [5, 62], [7, 75], [8, 90], [9, 79]], dtype=float) y_train = np.array([0, 0, 0, 1, 0, 1, 1, 1]) test = np.array([[1.5, 15], [5.1, 60], [6.4, 68], [8.5, 84]]) y_test = np.array([0, 1, 1, 1]) # 只在训练行估计中心和总体标准差。零波动列除数用 1。 mean = train.mean(axis=0) scale = train.std(axis=0, ddof=0) scale[scale == 0] = 1 k_values = [1, 3] test_neighbors = neighbors(train, test, mean, scale, max(k_values)) # 标签只取 0 或 1,因此邻居标签相加就是正类票数。 test_votes = np.array([y_train[test_neighbors[:, :k]].sum(axis=1) for k in k_values]) # 投票表按“k 的取值 × 查询数”排列。超过半数才判 1,平票判 0。 test_predictions = test_votes > np.array(k_values)[:, None] / 2 # 用密集的网格显示分类区域。查询点的连线指向它的邻居。 a, b = np.meshgrid(np.linspace(0.5, 9.5, 130), np.linspace(0, 100, 125)) # 展平网格并合为两列,逐行预测后按原形恢复为图上的区域。 grid = np.column_stack((a.ravel(), b.ravel())) grid_neighbors = neighbors(train, grid, mean, scale, max(k_values)) fig, axes = plt.subplots(1, 2, figsize=(8.5, 3.8), layout="constrained") for ax, k in zip(axes, k_values): region = (y_train[grid_neighbors[:, :k]].sum(axis=1) > k / 2).reshape(a.shape) ax.contourf(a, b, region, levels=[-0.5, 0.5, 1.5], colors=["#dceafd", "#f9dfc8"]) for label, color in [(0, "C0"), (1, "C1")]: ax.scatter(*train[y_train == label].T, color=color, label=f"Train class {label}") for index in test_neighbors[1, :k]: ax.plot([test[1, 0], train[index, 0]], [test[1, 1], train[index, 1]], "k--", alpha=0.65) ax.scatter(*test.T, color="black", marker="x", label="Test queries") ax.set(xlabel="Sensor 1", ylabel="Sensor 2", title=f"k = {k}") axes[0].legend(fontsize=8) # 测试准确率只用四条留出记录;邻居行号加 1 与 MATLAB 结果对齐。 return { "training_mean": mean.tolist(), "training_scale": scale.tolist(), "k_values": k_values, "test_predictions": test_predictions.astype(int).tolist(), "test_positive_votes": test_votes.tolist(), "test_accuracy": np.mean(test_predictions == y_test, axis=1).tolist(), "query_neighbor_rows": (test_neighbors[1] + 1).tolist(), } if __name__ == "__main__": print("LAB_RESULT " + json.dumps(run(), allow_nan=False)) plt.show()