"""线性回归与批次大小练习。

依赖：torch、matplotlib。直接运行此文件即可。
所有实验默认在 CPU 上进行；数据仅用于演示，不是真实学生记录。
运行后在 ../images/regression-loss.png 保存训练/验证损失图。
"""

from pathlib import Path

import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset


def run_experiment(batch_size, epochs, seed=42):
    """每次从相同初始参数开始，返回完整训练记录与模型。"""
    torch.manual_seed(seed)

    # 每行是一位学生：学习时长、练习次数；目标是考试分数。
    X = torch.tensor([[1.0, 5.0], [2.0, 8.0], [3.0, 15.0]])
    y = torch.tensor([[50.0], [58.0], [67.0]])
    X_val = torch.tensor([[2.5, 12.0], [4.0, 20.0]])
    y_val = torch.tensor([[63.0], [76.0]])

    loader = DataLoader(
        TensorDataset(X, y), batch_size=batch_size, shuffle=True
    )
    model = nn.Linear(2, 1)
    optimizer = torch.optim.SGD(model.parameters(), lr=0.001)

    train_losses = []
    val_losses = []
    update_count = 0

    for epoch in range(epochs):
        model.train()

        for batch_X, batch_y in loader:
            optimizer.zero_grad()
            pred = model(batch_X)
            loss = ((pred - batch_y) ** 2).mean()
            loss.backward()
            optimizer.step()
            update_count += 1

        # 每轮使用同一组更新后的参数，检查完整训练集与验证集。
        # 不将最后一个小批次的损失直接当作整轮训练损失。
        model.eval()
        with torch.no_grad():
            train_loss = ((model(X) - y) ** 2).mean()
            val_loss = ((model(X_val) - y_val) ** 2).mean()

        train_losses.append(train_loss.item())
        val_losses.append(val_loss.item())

    with torch.no_grad():
        predictions = model(X)
        val_predictions = model(X_val)

    return {
        "model": model,
        "train_losses": train_losses,
        "val_losses": val_losses,
        "predictions": predictions,
        "val_predictions": val_predictions,
        "update_count": update_count,
    }


def print_result(name, result):
    print(f"\n{name}")
    print("参数更新次数：", result["update_count"])
    print(f"最终训练 MSE：{result['train_losses'][-1]:.6f}")
    print(f"最终验证 MSE：{result['val_losses'][-1]:.6f}")


def main():
    image_dir = Path(__file__).resolve().parent.parent / "images"
    image_dir.mkdir(parents=True, exist_ok=True)

    # 学习率、随机种子、epoch 相同，批次大小不同。
    # 两组更新次数不同；图用于观察曲线形态，不是公平的效率排名。
    full_batch = run_experiment(batch_size=3, epochs=1000)
    mini_batch = run_experiment(batch_size=2, epochs=1000)
    print_result("全批量：每批 3 个样本，1000 轮", full_batch)
    print_result("小批量：每批 2 个样本，1000 轮", mini_batch)

    plt.rcParams.update({"font.size": 11, "axes.titlesize": 12})
    fig, axes = plt.subplots(1, 2, figsize=(11, 4.6), sharex=True, sharey=True)
    experiments = [
        (full_batch, "Full batch: size = 3\n1 update per epoch"),
        (mini_batch, "Mini-batch: size = 2\n2 updates per epoch"),
    ]

    for ax, (result, title) in zip(axes, experiments):
        epochs = range(1, len(result["train_losses"]) + 1)
        ax.plot(epochs, result["train_losses"], label="Training loss", linewidth=1.7)
        ax.plot(
            epochs,
            result["val_losses"],
            label="Validation loss",
            linestyle="--",
            linewidth=1.5,
        )
        ax.set_title(title)
        ax.set_xlabel("Epoch")
        ax.grid(True, alpha=0.25)
        ax.legend(fontsize=10)

    axes[0].set_ylabel("MSE Loss")
    axes[0].set_ylim(bottom=0)
    fig.tight_layout()
    figure_path = image_dir / "regression-loss.png"
    fig.savefig(figure_path, dpi=180, bbox_inches="tight")
    print("损失曲线已保存：", figure_path)

    # 单独延长全批量训练，重现学习过程中的分数预测。
    longer_run = run_experiment(batch_size=3, epochs=10000)
    print_result("全批量：每批 3 个样本，10000 轮", longer_run)
    print("训练集预测：\n", longer_run["predictions"])
    print("验证集预测：\n", longer_run["val_predictions"])
    print("训练后的权重：\n", longer_run["model"].weight)
    print("训练后的偏置：\n", longer_run["model"].bias)

    plt.show()


if __name__ == "__main__":
    main()
