import numpy as np


def linear_regression_grad_descent(X, y, alpha, iter):
    X = np.array(X)
    y = np.array(y).reshape(-1, 1)

    # 样本数和特征数
    m, n = X.shape
    theta = np.zeros((n, 1))

    # --- 必须将以下逻辑放入循环内 ---
    for _ in range(iter):
        # 1. 计算预测值
        prediction = X @ theta
        # 2. 计算误差
        errors = prediction - y
        # 3. 计算梯度 (1/m) * X.T * errors
        grad = (1.0 / m) * (X.T @ errors)
        # 4. 更新系数
        theta = theta - alpha * grad
    # ------------------------------

    # 将系数展平并四舍五入
    final_coeffs = [round(float(c), 4) for c in theta.flatten()]

    return np.array(final_coeffs)


# 测试输入
X = [[1, 1], [1, 2], [1, 3], [1, 4]]
y = [2, 3, 4, 5]
alpha = 0.01
iterations = 1000
print(linear_regression_grad_descent(X, y, alpha, iterations))

测试输入