"""用小样本拟合用电量,并在额外两天检查预测误差。""" import json # NumPy 构建设计矩阵并求系数;Matplotlib 绘制拟合和残差。 import matplotlib.pyplot as plt import numpy as np def main(): # 模拟数据。x 为设备运行小时,y 为用电量(kWh)。 x = np.array([1.0, 2, 3, 4, 5]) y = np.array([3.0, 5, 6, 8, 11]) # 两条留出观测只用于算预测误差,其中运行时长超出了训练范围。 x_test = np.array([6.0, 7]) y_test = np.array([12.0, 15]) # 将截距作为设计矩阵的第一列,每行表示一条观测。 design = np.column_stack((np.ones(x.size), x)) # 中心化后的内积刻画 x 与 y 的共同变化,除以 x 的离差平方和得到斜率。 dx = x - x.mean() slope = np.dot(dx, y - y.mean()) / np.dot(dx, dx) intercept = y.mean() - slope * x.mean() # lstsq 直接最小化 ||design @ beta - y||²。只取系数,顺序为截距、斜率。 beta, *_ = np.linalg.lstsq(design, y, rcond=None) np.testing.assert_allclose(beta, [intercept, slope], atol=1e-12) # design 的形状为 (5, 2),乘以长为 2 的系数向量,得到五个拟合值。 fitted = design @ beta residual = y - fitted prediction = beta[0] + beta[1] * x_test # 每条留出记录的误差先取绝对值再平均,单位仍为 kWh。 mae = np.abs(y_test - prediction).mean() # 带截距时,残差与设计矩阵两列正交。 np.testing.assert_allclose(design.T @ residual, 0, atol=1e-12) np.testing.assert_allclose([intercept, slope, mae], [0.9, 1.9, 0.55]) # 左图分辨训练点与留出点,右图以零线为参照,便于观察残差有无系统偏差。 fig, axes = plt.subplots(1, 2, figsize=(8, 3.2), layout="constrained") axes[0].scatter(x, y, label="Train") axes[0].plot(np.r_[x, x_test], np.r_[fitted, prediction], label="OLS line") axes[0].scatter(x_test, y_test, marker="x", label="Holdout") axes[0].set(xlabel="Run time (h)", ylabel="Electricity (kWh)") axes[0].legend() axes[1].axhline(0, color="gray") axes[1].scatter(x, residual) axes[1].set(xlabel="Run time (h)", ylabel="Train residual (kWh)") print("LAB_RESULT " + json.dumps({ "intercept": intercept, "slope": slope, "train_sse": float(np.dot(residual, residual)), "holdout_mae": mae, })) plt.show() if __name__ == "__main__": main()