import numpy as np

X = np.array([
    [40, 1],
    [55, 2],
    [70, 2],
    [85, 3],
    [100, 3],
    [120, 4]
], dtype=float)

y = np.array([120, 180, 220, 290, 340, 410], dtype=float)

#进行均值化
X_mean = np.mean(X, axis=0)
X_std = np.std(X, axis=0)
X_scale = (X - X_mean) / X_std
print("X_scale:", X_scale)

#计算新的平均值
new_mean = np.mean(X_scale, axis=0)
new_std = np.std(X_scale, axis=0)

w = np.array([0.0, 0])
b = 0
loss_history = []
samples = len(y)

for epoch in range(1000):
    #1.计算预测值
    pred_y = np.dot(X_scale, w) + b

    #2.计算误差
    errors = pred_y - y

    #3.计算MAE
    loss = np.mean(errors ** 2)

    #4.记录当前loss
    loss_history.append(loss)

    #5.更新参数
    dw = (2 / samples) * (X_scale.T @ errors)
    db = (2 / samples) * np.sum(errors)

    learning_rate = 0.1
    w = w - dw*learning_rate
    b = b - db*learning_rate

    # 6. 每隔 100 次显示一次训练情况
    if epoch % 100 == 0:
        print(
            f"epoch={epoch:4d}, "
            f"loss={loss:.6f}"
        )

