"""
Lab01: 线性模型的欠拟合与过拟合

你可以把整份代码理解成 7 个小步骤:

1. 自己设计真实函数
2. 自己生成模拟数据
3. 划分训练集和测试集
4. 自己实现模型、损失函数、评价函数
5. 分别构造欠拟合 / 正常拟合 / 过拟合三种情况
6. 输出评价指标
7. 画图展示结果
"""

from __future__ import annotations

import math
from pathlib import Path

import matplotlib.pyplot as plt
import torch

# 图片会保存在 src 目录下，和当前脚本放在一起。
OUTPUT_PATH = Path(__file__).resolve().parent / "fit_comparison.png"


# Step 1: 生成模拟数据
# 我们先设计一个包含 5 个有效特征的真实函数，再额外加入 20 个噪声维度。
def make_dataset(num_samples: int = 300, seed: int = 42) -> tuple[torch.Tensor, torch.Tensor]:
    """
    生成一份模拟数据。

    返回值:
    - all_x: 所有输入特征，形状是 (样本数, 25)
    - y: 标签，形状是 (样本数, 1)

    这里的 25 维中:
    - 前 5 维是真正和 y 有关的有效特征
    - 后 20 维是纯噪声特征，用来干扰模型
    """
    # 固定随机种子，保证每次运行结果基本一致，方便复现实验。
    torch.manual_seed(seed)

    # torch.rand(num_samples, 5) 会生成 [0, 1) 范围内的随机数。
    # * 4 - 2 之后，就把范围变成了 [-2, 2)。
    useful_x = torch.rand(num_samples, 5) * 4 - 2

    # 下面这种写法是 PyTorch 中很常见的“按列取特征”的方式。
    # useful_x[:, 0:1] 表示:
    # - ":" 取所有行
    # - "0:1" 取第 0 列，但保留二维形状
    #
    # 为什么不用 useful_x[:, 0] ?
    # 因为 useful_x[:, 0] 的形状是 (num_samples,)
    # 而 useful_x[:, 0:1] 的形状是 (num_samples, 1)
    # 后者更适合后面做矩阵运算。
    x1 = useful_x[:, 0:1]
    x2 = useful_x[:, 1:2]
    x3 = useful_x[:, 2:3]
    x4 = useful_x[:, 3:4]
    x5 = useful_x[:, 4:5]

    # 这是我们“自主设计”的真实函数。
    # 它使用了 5 个特征，并且带有平方项、乘积项、sin 非线性项。
    # 这样做的目的是:
    # - 满足“自主设计包含 5 个及以上特征的函数”
    # - 让问题不是简单的纯线性关系，这样才容易观察欠拟合和过拟合
    y = (
        2.0 * x1
        - 1.5 * x2**2
        + 1.2 * x3 * x4
        + 0.8 * torch.sin(math.pi * x5)
        + 0.6 * x1 * x5
        + 0.3
    )

    # 给标签 y 加一点随机噪声，让数据更接近真实世界中的“带误差测量”。
    # 如果完全没有噪声，过拟合现象会不够明显。
    y = y + 0.2 * torch.randn(num_samples, 1)

    # 再额外生成 20 维噪声特征。
    # 它们和 y 没有真实关系，只是为了“扩展维度”和“干扰模型”。
    noise_x = torch.randn(num_samples, 20)

    # torch.cat(..., dim=1) 表示按列拼接。
    # 拼接后总维度 = 5 个有效特征 + 20 个噪声特征 = 25 维。
    all_x = torch.cat([useful_x, noise_x], dim=1)
    return all_x, y


# Step 2: 划分训练集和测试集
def train_test_split(
    x: torch.Tensor, y: torch.Tensor, train_size: int, seed: int
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    """
    手动把数据分成训练集和测试集。

    为什么要分训练集和测试集?
    - 训练集用来“学参数”
    - 测试集用来“检查模型是不是只会背答案”

    如果模型在训练集很好、测试集很差，通常就是过拟合。
    """
    generator = torch.Generator().manual_seed(seed)

    # randperm(n) 会生成 0 ~ n-1 的一个随机打乱顺序。
    index = torch.randperm(x.shape[0], generator=generator)

    train_index = index[:train_size]
    test_index = index[train_size:]
    return x[train_index], y[train_index], x[test_index], y[test_index]


# Step 3: 构造不同的特征映射
# “特征映射”可以理解为:
# 我们把原始输入 x 再加工一下，变成更适合模型学习的新输入。


def underfit_features(x: torch.Tensor) -> torch.Tensor:
    """
    欠拟合版本:
    直接把原始 25 维特征送进线性模型。

    由于真实函数里有平方项、sin 项、乘积项，
    但这里的模型只看到“原始线性输入”，表达能力不够，所以容易欠拟合。
    """
    return x


def good_features(x: torch.Tensor) -> torch.Tensor:
    """
    正常拟合版本:
    按照真实函数的结构，手工构造出更合理的特征。

    这一步的思想是:
    模型本身还是线性模型，但如果特征设计得好，
    线性模型依然可以拟合非线性关系。
    """
    x1 = x[:, 0:1]
    x2 = x[:, 1:2]
    x3 = x[:, 2:3]
    x4 = x[:, 3:4]
    x5 = x[:, 4:5]

    # 这里构造出来的 5 个新特征，和上面真实函数中的结构基本对应。
    # 所以这组特征通常会得到最好的测试结果。
    return torch.cat(
        [x1, x2**2, x3 * x4, torch.sin(math.pi * x5), x1 * x5],
        dim=1,
    )


def overfit_features(x: torch.Tensor) -> torch.Tensor:
    """
    过拟合版本:
    人为构造很多复杂特征，让模型容量变大。

    再配合“很少的训练样本”，模型就可能把训练集记得过于死板，
    于是训练集效果极好，但测试集效果反而下降。
    """
    # 先放入原始特征和平方特征。
    parts = [x, x**2]

    # 再构造很多两两交叉项，比如 x1*x2, x1*x3, x2*x3 ...
    # 这些交叉项会显著增加特征数量，让模型更容易过拟合。
    cross_terms = []
    for i in range(15):
        for j in range(i + 1, 15):
            # x[:, i:i+1] 依旧保持二维列向量形状。
            cross_terms.append(x[:, i : i + 1] * x[:, j : j + 1])

    return torch.cat(parts + cross_terms, dim=1)


# Step 4: 数据标准化
def standardize(
    train_x: torch.Tensor, test_x: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    把每一列特征缩放到更适合训练的范围。

    标准化公式:
        x_new = (x - mean) / std

    注意:
    这里的 mean 和 std 必须只用训练集计算，
    然后再拿去处理测试集。
    这是机器学习里一个很重要的规范。
    """
    # dim=0 表示“按列统计”。
    # keepdim=True 表示保留二维形状，方便后面直接广播计算。
    mean = train_x.mean(dim=0, keepdim=True)
    std = train_x.std(dim=0, keepdim=True, unbiased=False)

    # 某些特征如果方差太小，std 可能接近 0。
    # 这时直接相除会不稳定，所以把它改成 1.0。
    std[std < 1e-6] = 1.0
    return (train_x - mean) / std, (test_x - mean) / std


# Step 5: 实现损失函数和评价函数
def mse_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
    """
    MSE = Mean Squared Error，均方误差。
    它是回归问题里最常见的损失函数之一。
    """
    return ((pred - target) ** 2).mean()


def rmse(pred: torch.Tensor, target: torch.Tensor) -> float:
    """
    RMSE = sqrt(MSE)。
    它和原始 y 的单位相同，所以比 MSE 更直观。
    数值越小说明预测越准。
    """
    return float(torch.sqrt(mse_loss(pred, target)))


def r2_score(pred: torch.Tensor, target: torch.Tensor) -> float:
    """
    R2 决定系数，取值通常越接近 1 越好。

    它衡量的是:
    模型解释了多少比例的数据波动。
    """
    ss_res = ((pred - target) ** 2).sum()
    ss_tot = ((target - target.mean()) ** 2).sum()
    return float(1 - ss_res / ss_tot)


# Step 6: 实现线性模型
def train_linear_model(
    train_x: torch.Tensor,
    train_y: torch.Tensor,
    epochs: int,
    lr: float,
) -> tuple[torch.Tensor, torch.Tensor]:
    """
    用最基础的方式训练一个线性模型:
        y_hat = Xw + b

    这里没有调用 torch.nn.Linear，也没有调用优化器，
    而是手动实现参数、损失、反向传播、梯度下降。
    这样更符合实验里“自主实现模型、损失函数、评价函数”的要求。
    """
    # w 是权重，形状是 (特征数, 1)
    # b 是偏置，形状是 (1,)
    # requires_grad=True 表示:
    # PyTorch 需要帮我们跟踪它们的梯度。
    w = torch.zeros(train_x.shape[1], 1, requires_grad=True)
    b = torch.zeros(1, requires_grad=True)

    for _ in range(epochs):
        # 前向计算: 根据当前参数得到预测值
        pred = train_x @ w + b

        # 计算损失
        loss = mse_loss(pred, train_y)

        # 反向传播: 自动计算 loss 对 w 和 b 的梯度
        loss.backward()

        # 参数更新不能被 autograd 继续记录，所以放在 no_grad 里。
        with torch.no_grad():
            # 这就是最基本的梯度下降:
            # 新参数 = 旧参数 - 学习率 * 梯度
            w -= lr * w.grad
            b -= lr * b.grad

            # 每轮都要把上一轮的梯度清零。
            # 不清零的话，梯度会不断累加。
            w.grad.zero_()
            b.grad.zero_()

    # detach() 的作用是把参数从计算图里分离出来。
    # 后面只是拿它们做预测，不需要继续求梯度。
    return w.detach(), b.detach()


def evaluate_case(
    name: str,
    plot_name: str,
    feature_fn,
    x: torch.Tensor,
    y: torch.Tensor,
    train_size: int,
    epochs: int,
    lr: float,
    seed: int,
) -> dict[str, torch.Tensor | float | str]:
    """
    运行一次完整实验:
    1. 划分数据
    2. 做特征变换
    3. 做标准化
    4. 训练模型
    5. 输出训练集和测试集指标
    """
    train_x, train_y, test_x, test_y = train_test_split(x, y, train_size=train_size, seed=seed)

    # 用不同的特征设计方式，制造不同的拟合效果。
    train_x = feature_fn(train_x)
    test_x = feature_fn(test_x)

    # 标准化可以让训练更稳定。
    train_x, test_x = standardize(train_x, test_x)

    # 训练模型，得到最终参数 w 和 b。
    w, b = train_linear_model(train_x, train_y, epochs=epochs, lr=lr)

    # 用训练好的参数分别预测训练集和测试集。
    train_pred = train_x @ w + b
    test_pred = test_x @ w + b

    print(f"\n{name}")
    print(f"train RMSE: {rmse(train_pred, train_y):.4f}, train R2: {r2_score(train_pred, train_y):.4f}")
    print(f"test  RMSE: {rmse(test_pred, test_y):.4f}, test  R2: {r2_score(test_pred, test_y):.4f}")

    # 返回绘图需要的数据。
    return {
        "name": name,
        "plot_name": plot_name,
        "test_y": test_y.detach(),
        "test_pred": test_pred.detach(),
        "train_r2": r2_score(train_pred, train_y),
        "test_r2": r2_score(test_pred, test_y),
    }


# Step 7: 绘图
# 在一张图中放 3 个子图，分别展示三种情况在测试集上的预测效果。
def draw_result_figure(results: list[dict[str, torch.Tensor | float | str]]) -> None:
    """
    画三张散点图:
    - 横轴是真实值 True y
    - 纵轴是预测值 Predicted y

    如果点大致落在对角线附近，说明预测效果好。
    如果点散得很乱，说明预测效果差。
    """
    fig, axes = plt.subplots(1, 3, figsize=(15, 4.5))

    for ax, result in zip(axes, results):
        # numpy().ravel() 是为了把张量变成 matplotlib 更容易处理的一维数组。
        test_y = result["test_y"].numpy().ravel()
        test_pred = result["test_pred"].numpy().ravel()

        # 画散点图: 每个点代表“一个测试样本的真实值和预测值”。
        ax.scatter(test_y, test_pred, s=18, alpha=0.7)

        # 再画一条参考线 y = x。
        # 如果预测完全正确，点应该靠近这条线。
        line_min = min(test_y.min(), test_pred.min())
        line_max = max(test_y.max(), test_pred.max())
        ax.plot([line_min, line_max], [line_min, line_max], "r--", linewidth=1.5)

        ax.set_title(str(result["plot_name"]))
        ax.set_xlabel("True y")
        ax.set_ylabel("Predicted y")
        ax.text(
            0.05,
            0.92,
            f"test R2 = {result['test_r2']:.4f}",
            transform=ax.transAxes,
            fontsize=10,
            bbox={"facecolor": "white", "alpha": 0.8, "edgecolor": "gray"},
        )

    fig.suptitle("Underfitting vs Good Fitting vs Overfitting", fontsize=14)
    fig.tight_layout()
    fig.savefig(OUTPUT_PATH, dpi=200, bbox_inches="tight")
    plt.close(fig)


def main() -> None:
    # 先生成完整数据集。
    x, y = make_dataset()

    # results 用来保存三种实验结果，后面统一画图。
    results = []

    print("真实函数:")
    print("y = 2.0*x1 - 1.5*x2^2 + 1.2*x3*x4 + 0.8*sin(pi*x5) + 0.6*x1*x5 + 0.3")
    print("数据总维度: 25 维 = 5 个有效特征 + 20 个噪声特征")

    # 1. 欠拟合:
    # 训练样本并不少，但模型表达能力不够。
    results.append(
        evaluate_case(
            name="1. 欠拟合",
            plot_name="1. Underfitting",
            feature_fn=underfit_features,
            x=x,
            y=y,
            train_size=200,
            epochs=400,
            lr=0.05,
            seed=1,
        )
    )

    # 2. 正常拟合:
    # 特征设计合理，模型能学到真实规律。
    results.append(
        evaluate_case(
            name="2. 正常拟合",
            plot_name="2. Good Fitting",
            feature_fn=good_features,
            x=x,
            y=y,
            train_size=200,
            epochs=400,
            lr=0.05,
            seed=1,
        )
    )

    # 3. 过拟合:
    # 训练样本太少，但特征非常多、非常复杂，所以模型容易“死记硬背”。
    results.append(
        evaluate_case(
            name="3. 过拟合",
            plot_name="3. Overfitting",
            feature_fn=overfit_features,
            x=x,
            y=y,
            train_size=30,
            epochs=800,
            lr=0.03,
            seed=2,
        )
    )

    # 统一画图展示三种情况。
    draw_result_figure(results)
    print(f"\n图片已保存到: {OUTPUT_PATH}")


if __name__ == "__main__":
    main()
