# encoding=utf8
import numpy as np

def computeCost(X, y, theta):
    """
    计算线性回归的损失函数
    
    参数:
    X: 特征矩阵 (m, n+1), m 为样本数, n 为特征数
    y: 标签向量 (m, 1)
    theta: 模型参数 (n+1, 1)
    
    返回:
    cost: 计算出的损失值
    """
    # 根据公式编写损失函数计算函数
    # ********* begin *********#
    
    # m 是样本的数量
    m = len(y)
    
    # 计算预测值 h(x) = X * theta
    predictions = X.dot(theta)
    
    # 计算预测值与真实值之间的误差平方和
    squared_errors = np.power((predictions - y), 2)
    
    # 根据公式 J(θ) = (1/2m) * Σ(h(x) - y)^2 计算最终的 cost
    cost = np.sum(squared_errors) / (2 * m)
    
    # ********* end *********#
    return cost