# encoding=utf8
import numpy as np

# 假设 computeCost 函数已经定义
def computeCost(X, y, theta):
    m = len(y)
    predictions = X.dot(theta)
    cost = (1/(2*m)) * np.sum(np.square(predictions - y))
    return cost

def gradientDescent(X, y, theta, alpha, iters):
    """
    使用梯度下降算法更新参数 theta
    
    参数:
    X: 特征矩阵
    y: 标签向量
    theta: 初始参数
    alpha: 学习率
    iters: 迭代次数
    
    返回:
    theta: 优化后的参数
    cost_history: 每次迭代的损失值历史记录
    """
    m = len(y)
    cost_history = np.zeros(iters) # 用于存储每次迭代的 cost
    
    for i in range(iters):
        # 计算预测值与真实值的误差
        error = X.dot(theta) - y
        
        # 根据梯度下降公式更新 theta
        # 公式: θ := θ - α * (1/m) * X^T * error
        gradient = X.T.dot(error)
        theta = theta - (alpha / m) * gradient
        
        # 记录当前迭代的 cost
        cost_history[i] = computeCost(X, y, theta)
        
    return theta, cost_history