import json import numpy as np # 每行是一项观测;设计矩阵第 2 列固定为 1,让模型学习截距。 x = np.arange(1.0, 6.0) y = np.array([2, 4, 5, 4, 5]) design = np.column_stack((x, np.ones_like(x))) # 求使 ||Xθ-y||² 最小的 θ,返回元组的第一项存放斜率和截距。 slope, intercept = np.linalg.lstsq(design, y, rcond=None)[0] sse = float(np.sum((design @ [slope, intercept] - y) ** 2)) prediction = float(6 * slope + intercept) assert np.allclose([slope, intercept, sse, prediction], [.6, 2.2, 2.4, 5.8]) result = {"coefficients": [float(slope), float(intercept)], "sse": sse, "prediction": prediction} print("LAB_RESULT " + json.dumps(result, ensure_ascii=False))