⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

v1.0

data-science-stack

@hua695⭐ 13 stars

数学建模竞赛数据科学技能(C 类数据题、预测题及 MathorCup 大数据题):EDA、预处理与特征工程、统计推断、机器学习、时间序列、模型评估与调参。触发词:数据题、C题、MathorCup、EDA、数据预处理、特征工程、机器学习、回归、分类、聚类、时间序列、预测、ARIMA、XGBoost、统计检验。与 contest-orchestrator executor 阶段、math-modeling、scipilot-figure-skill 协作。

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐ 13 on GitHubGitHub ↗

Growing

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

Repository checks License

开始使用 · 工作台演示 · 技能目录 · 验证与限制

适合有题目、数据和人工判断,希望把建模任务、证据和成果组织起来的个人或团队。覆盖国赛、美赛、MathorCup 等竞赛;格式与 AI 使用要求以本届官方规则为准。

当前状态: 主控为开发快照,完整发布检查尚未通过;节点批准和最终交付仍由人负责。详见验证说明。

先看看效果

本机读取已有 Harness 项目,集中查看比赛阶段、小问、角色会话和成果。页面定时从项目文件同步,不需要额外调用模型。比赛数据和审批记录保持只读,角色会话需自行登记并核实。

数模工作台比赛总览,使用合成演示项目

截图来自仓库内的合成演示项目,不代表真实比赛进度或批准结果。打开演示项目 · 了解工作台

选择你的起点

我想做什么从哪里开始先得到什么
组织一场完整比赛竞赛主控 · 全流程提示词题意划分、输入缺口、模型计划与节点安排
只处理一个问题模型选择 · 数据分析题型与模型选择、数据边界、可复现的分析方案
制作图表和示意图科研绘图 · 图表决策 · 技术路线示例图表方案、可编辑图源、质量检查材料
写作或复核论文学术写作 · 论文排版章节审阅、LaTeX 论文工程与检查清单
查看已有 Harness 项目工作台使用说明阶段、角色、文件、论文和已有审查记录

更多单项任务和可复制提示词见按任务启动。

开始使用

git clone https://github.com/cjh-solver/MathModeling-Skills-Arsenal.git
cd MathModeling-Skills-Arsenal

仓库使用 skills/<分类>/<技能>/SKILL.md 结构,安装时将技能目录放到宿主实际读取的技能根目录。以 Codex 用户技能目录为例:

以下命令安装数模分类,跳过创意写作;已有同名技能会跳过,不会覆盖。

# PowerShell:只安装数模分类,跳过创意写作。
$skillRoot = Join-Path $env:USERPROFILE '.agents/skills'
New-Item -ItemType Directory -Force -Path $skillRoot | Out-Null
Get-ChildItem skills/0* -Directory | ForEach-Object {
    Get-ChildItem $_.FullName -Directory | ForEach-Object {
        if (-not (Test-Path -LiteralPath (Join-Path $_.FullName 'SKILL.md'))) { return }
        $destination = Join-Path $skillRoot $_.Name
        if (Test-Path -LiteralPath $destination) {
            Write-Warning "已存在,跳过:$($_.Name)"
        } else {
            Copy-Item -LiteralPath $_.FullName -Destination $destination -Recurse
        }
    }
}

此命令跳过已有同名技能;需要更新时先比较与备份,再合并。Claude Code、WorkBuddy 等宿主使用各自配置的技能目录;支持 SKILL.md 不代表工具、模型和多角色能力完全相同。

安装后打开新会话,给出题目、附件路径与规则来源:

使用 contest-orchestrator。先读取我的题目和本届规则,列出缺失输入,
选择合适模式。先做题意与模型计划,不直接生成最终论文或编造实验结果。

MathorCup 全流程可指定 full-contest-mathorcup;只解一问、只画图或只审稿时使用对应单项技能。详见 启动示例。

工作流示例:章节批准后,图文并行

Harness 与 MathorCup 的新模板采用 chapter_parallel。先写建模求解,目录顺序与实际写作顺序分别维护。每次提交完整一章,由使用者批准后再写下一章;图表提示词也在该章批准后产生,由使用者转交图表角色。

flowchart LR
    A[全文论证计划] --> B[完整建模求解章节]
    B --> C{人工批准本章}
    C --> D[下一章写作]
    C --> E[本章图表提示词]
    E --> F[用户转交图表角色]
    F --> G[成图与定向返修]
    D --> H[正文与附录完成]
    H --> I[摘要最后写]
    G --> J[最终接图与全文终审]
    I --> J

图件返修更新提示词版本,后续章节继续写;未变正文的批准保持有效。最终交付仍检查最新图件、选定版本、证据来源与全文一致性。历史四批写作记录继续兼容。

验证与边界

  • 流程测试与复现方法说明检查内容、历史结果和尚未解决的发布问题。CI 通过不等于正式比赛交付通过。
  • 合成章节示例展示正文与图表交接;构造数据上的结果不能证明真实比赛表现。
  • 可编辑技术路线示例展示图源形式;实际图表需依据题目、数据和证据重新制作与核验。
  • 科学计算、论文编译和不同宿主需要各自依赖;缺少工具时不能以源码检查代替实际运行。

参与和维护

贡献指南 · 维护方向 · 更新记录 · 问题反馈

仓库不发布比赛论文全文、赛事私有数据、个人记忆和凭据。整体协议为 Apache-2.0;第三方技能保留各自许可证,详见技能目录与协议。

// HOW IT'S BUILT

// FILES

17 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • skills/02-modeling/data-science-stack/SKILL.md18 KB7e2044dc202dupstream ↗
    ---
    name: data-science-stack
    description: 数学建模竞赛数据科学技能(C 类数据题、预测题及 MathorCup 大数据题):EDA、预处理与特征工程、统计推断、机器学习、时间序列、模型评估与调参。触发词:数据题、C题、MathorCup、EDA、数据预处理、特征工程、机器学习、回归、分类、聚类、时间序列、预测、ARIMA、XGBoost、统计检验。与 contest-orchestrator executor 阶段、math-modeling、scipilot-figure-skill 协作。
    metadata:
      version: "1.0"
    ---
    
    # 数学建模竞赛 · 数据科学全链路(C 题/预测题)
    
    > 定位:解决"拿到 Excel/CSV 附件后怎么办"的问题。目标是一场数据题从 EDA 到论文结果的全部代码与文字素材一次到位,结果只从代码生成。
    
    ## Contest-Orchestrator Adapter
    
    本技能是 `contest-orchestrator` 中 C 类/预测类小问的执行器,不是独立主控。只接收当前任务卡、数据审计、`model_blueprint.yaml`/`model_contract.yaml` 和已批准数据源;输出写入项目工作区,并进入 `run_manifest`、`result_registry` 和 `numeric_source_map`。
    
    - 每个数据处理决定记录来源、处理原因、影响范围和可复算命令;不得静默删除样本、改动原始数据或捏造缺失结果。
    - 训练、验证、预测和敏感性结果必须绑定随机种子、数据版本、代码路径、指标定义和结果文件;模型选择遵循 baseline → 验证 → 必要复杂化。
    - 返回 `status`、`active_mode`、`task_card`、`artifacts`、`evidence`、`checks`、`blockers`、`next_node` 节点包。缺数据、缺标签、指标不适用或证据断裂时返回 `BLOCKED_INPUT`/`FAIL`。
    - 数据结果图只走 `scipilot-figure-skill` → `modelviz` → `scipilot-figure-skill`;本技能不替代绘图技能执行视觉检查,进入绘图路由后按图表契约默认完成视觉检查。
    - 节点包和论文可见内容不得出现元话语、内部交流、调试信息、失败过程或其他负回响。
    
    `active_mode: full-contest-mathorcup` 时,M2 的 data 实例依据 `problem_statement.md`、`data_overview.yaml`、`task_kpi.yaml` 和题面附件输出 `eda_report.md`、`features.yaml` 与分割/预处理协议;verifier 独立签署 `leakage_audit.yaml` 后才能冻结特征。M3 仅由唯一 solver 使用冻结数据管线完成各小问 baseline、同切分/同指标候选比较、参数选择和 `run_manifest.yaml`;本技能不能另起解题主线或绕过独立 `independent_validation.yaml`。填补、编码、缩放、特征选择、目标编码和调参仅在训练折拟合;时间数据按时间分割,实体相关样本按组隔离,测试集不参与拟合或路线选择。M2 不写最终模型结果,M3 的每个量化结论必须绑定数据/代码/参数/种子/结果文件与跨问接口。下文时长、阈值、图型和算法是按需参考,不是 MathorCup 的固定门禁。
    
    ## 0. 何时触发
    
    MathorCup 的评估、模型能力核对和资源恢复先读取 `references/mathorcup_experiment_protocol.md`。该协议补充现有模型卡与 run manifest,不新增固定算法、数字门槛或审批阶段。
    
    题目出现以下任一信号即进入本技能流程(典型:国赛 C 题、美赛 C/E/F 题的数据部分):
    
    - 题目附带了数据文件(.xlsx/.csv/.txt),且问题围绕这些数据
    - 问题动词是"预测 / 分类 / 识别 / 评价 / 关联 / 画像 / 排序"
    - 问题要求"建立……与……之间的关系模型"
    
    不触发:纯机理建模(微分方程)、纯优化调度(无数据依赖)——那走 `pyomo` / `heuristic-algorithms`。
    
    ## 1. 总览:五步流水线
    
    ```
    Step1 EDA(1-2h)→ Step2 预处理+特征工程(1-2h)→ Step3 统计推断(按需)
    → Step4 ML 建模+评估(4-8h,核心)→ Step5 时间序列(若为预测题)
    全程产出:数据报告.md + 图(scipilot)+ 结果表(.csv)+ 代码落盘
    ```
    
    每一步都必须产出**论文可直接使用的素材**(表格/图/一段话),不允许"只探索不记录"。
    
    ## 2. Step 1:EDA(探索性分析)
    
    ### 10 步清单(顺序执行,输出一份《数据报告.md》)
    
    1. **形状与类型**:`df.shape`、`df.dtypes`、列名规范
    2. **缺失值**:逐列缺失率;缺失 >20% 的列标记"慎用或剔除"
    3. **重复行**:`df.duplicated().sum()`
    4. **描述统计**:`df.describe()`;核对量纲差异 >3 个数量级的列(需标准化或换单位)
    5. **异常值**:每列 IQR 法 + 3σ 法交叉标记;异常比例 >5% 的列写进数据报告(保留还是剔除要论证)
    6. **分布形状**:直方图/箱线图(scipilot 出图),偏度、峰度数值
    7. **相关性**:数值列 Pearson 相关矩阵热力图 + 与目标变量的相关系数排序
    8. **分组结构**:类别列分组后目标变量的差异(分组箱线图);**判断是否该用混合效应/分层**
    9. **时间结构**:若有时间列——趋势、季节、缺失时间段;画时序图
    10. **结论表**:一列一个结论(类型/缺失/异常/分布/相关性/处理建议),这就是数据报告正文
    
    ```python
    import pandas as pd, numpy as np
    df = pd.read_excel('附件.xlsx')  # 单表示例;多 sheet 时逐表选择并审计
    # 或 df = pd.read_csv('data.csv', encoding='gbk')  # 中文数据常见 gbk
    
    report = []
    for col in df.columns:
        s = df[col]
        miss = s.isnull().mean()
        if pd.api.types.is_numeric_dtype(s):
            q1, q3 = s.quantile(0.25), s.quantile(0.75)
            iqr = q3 - q1
            n_out = ((s < q1 - 1.5*iqr) | (s > q3 + 1.5*iqr)).sum()
            report.append({'列': col, '类型': '数值', '缺失率': f'{miss:.1%}',
                           '均值': round(s.mean(), 4), '异常数': int(n_out)})
        else:
            report.append({'列': col, '类型': '类别', '缺失率': f'{miss:.1%}',
                           '唯一值数': s.nunique()})
    print(pd.DataFrame(report).to_string(index=False))
    ```
    
    **EDA 雷区**:不做 EDA 直接建模(评委问"为什么用这个模型"时答不上)| 只数缺失率不处理 | 不看量纲 | 不记录发现(赛后无法写论文)。
    
    ## 3. Step 2:预处理与特征工程
    
    按 EDA 结论执行,**每项处理都要在数据报告里留一行记录**(论文"数据预处理"节就靠它)。
    
    以下算子只表示处理方式。凡需从样本估计均值、众数、分位数、编码词表或尺度参数的操作,必须放入训练折内拟合的管线,再对验证/测试折调用同一变换;时间插值不得跨越预测时点或分割边界。
    
    | 问题 | 处理 | 代码 |
    |---|---|---|
    | 缺失(数值) | 均值/中位数/线性插值/模型预测填充(按缺失率选择) | `df[col].interpolate(method='linear')` |
    | 缺失(类别) | 众数填充或"未知"类 | `df[col].fillna(df[col].mode()[0])` |
    | 异常值 | 3σ 截尾 / IQR 缩尾 / 保留并标注(竞赛中**优先缩尾或保留**,直接删行会被质疑) | `s.clip(s.quantile(0.01), s.quantile(0.99))` |
    | 量纲差异 | 标准化(Z-score)/ 归一化(MinMax),注意**先划分训练测试再fit** | `from sklearn.preprocessing import StandardScaler` |
    | 类别编码 | LabelEncoder(有序)/ OneHot(无序)/ 频数编码(高基数) | `pd.get_dummies()` |
    | 长尾分布 | log1p 变换(目标变量偏斜时常用) | `np.log1p(y)`,预测完 `np.expm1()` 还原 |
    | 时间列 | 拆成年/月/日/星期/小时;构造滞后特征 | `df['month'] = df['date'].dt.month` |
    
    **特征工程(拿奖关键)**,按重要性排序:
    1. **领域特征**:读题找隐含变量(例:销量题 → 节假日/促销/天气;定价题 → 利润率/竞争价差)
    2. **统计特征**:历史均值/中位数/极差/标准差/趋势斜率(滚动窗口)
    3. **交互特征**:两变量乘积/比值(例:单价×销量=销售额)
    4. **降维**:相关性 >0.9 的列只留一个;PCA 用于可视化或消除多重共线性(要解释主成分含义)
    
    **铁律**:特征构造只能使用**已知信息**(比赛时刻之前的数据),严禁用未来数据构造特征(数据泄漏,评委会质疑、重算会翻车)。
    
    ## 4. Step 3:统计推断(按需,不要为用而用)
    
    | 问题 | 方法 | 代码 |
    |---|---|---|
    | 两组目标变量有无显著差异 | 独立样本 t 检验 / Mann-Whitney U | `scipy.stats.ttest_ind` / `mannwhitneyu` |
    | 多组差异 | 单因素方差分析 + Tukey HSD | `scipy.stats.f_oneway` + `statsmodels.stats.multicomp.pairwise_tukeyhsd` |
    | 类别×类别独立性 | 卡方检验 | `scipy.stats.chi2_contingency` |
    | 两变量线性相关 | Pearson(正态) | `scipy.stats.pearsonr` |
    | 两变量单调相关 | Spearman(非正态/序数) | `scipy.stats.spearmanr` |
    | 数据是否正态 | Shapiro-Wilk(n<5000)/ 偏度峰度 | `scipy.stats.shapiro` |
    | 多因素对目标的关联强度 | 灰色关联度(国赛常用,手写 15 行) | 见下方模板 |
    
    ```python
    # 灰色关联度分析(评价/相关性题高频使用)
    def grey_relational_degree(X, y):
        """X: (n, m) 特征矩阵, y: (n,) 目标列。返回每个特征的关联度"""
        Xn = (X - X.min(0)) / (X.max(0) - X.min(0) + 1e-9)
        yn = (y - y.min()) / (y.max() - y.min() + 1e-9)
        diff = np.abs(Xn - yn[:, None])
        rho = 0.5
        rel = (diff.min(0) + rho * diff.max(0)) / (diff + rho * diff.max(0))
        return rel.mean(0)  # 每列一个关联度,可排序
    ```
    
    ## 4.5 详细 ML 手册(按需加载)
    
    - ML 类算法完整手册(XGBoost/LightGBM/RF/SVM/BP 系统展开,含问题适配框架与参数建议):`references/cookbook-ml.md`。本文档选择树是首选入口,手册提供更细的算法适配细节。
    
    ## 5. Step 4:机器学习模型库(选择树)
    
    按问题类型直接选,**首选简单可解释模型,复杂模型只做提升**(评委喜欢"baseline 对比"叙事):
    
    ```
    回归(预测连续值)
    ├─ 线性/岭回归 → 快、可解释、适合关系建模题("建立X与Y的关系")
    ├─ 随机森林 / XGBoost / LightGBM → 特征多、非线性强时主用
    └─ 对比叙事:线性做 baseline,树模型做提升,报告两者 R²
    
    分类(判别/识别/分类)
    ├─ 逻辑回归 → baseline + 可解释(系数=影响)
    ├─ 随机森林/XGBoost → 主用;SVM → 小样本高维
    └─ 指标:准确率 + F1 + 混淆矩阵(别只报准确率)
    
    聚类(画像/分区/划分)
    ├─ K-Means → 首选,肘部法则定 K + 轮廓系数验证
    ├─ DBSCAN → 密度不均/有离群点
    └─ 输出:每类中心 + 画像表(论文"用户画像"节直接抄)
    
    评价/排序(无监督打分)
    ├─ 熵权法(客观权重)+ TOPSIS(综合排序)→ 数据驱动评价题首选
    └─ AHP(主观权重,需专家判断,评委接受度高但要有理由)
    ```
    
    ```python
    from sklearn.model_selection import train_test_split, cross_val_score
    from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
    from sklearn.linear_model import LinearRegression, LogisticRegression
    from sklearn.preprocessing import StandardScaler
    import joblib, os
    
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=42)
    scaler = StandardScaler(); X_tr = scaler.fit_transform(X_train); X_te = scaler.transform(X_test)
    
    # 回归主模型 + 可解释性
    model = RandomForestRegressor(n_estimators=300, random_state=42)
    model.fit(X_tr, y_train)
    r2 = model.score(X_te, y_test)
    imp = pd.Series(model.feature_importances_, index=feature_names).sort_values(ascending=False)
    print(f'R²={r2:.4f}  前5重要特征:\n{imp.head(5)}')
    
    # 落盘(orchestrator 要求:结果只从代码生成,可复现)
    os.makedirs('results', exist_ok=True)
    joblib.dump({'model': model, 'scaler': scaler, 'r2': r2}, 'results/model.pkl')
    ```
    
    **多模型对比表(论文必备)**:
    
    | 模型 | 训练R² | 测试R² | RMSE | 结论 |
    |---|---|---|---|---|
    | 线性回归 | 0.85 | 0.81 | 12.3 | baseline |
    | 随机森林 | 0.97 | 0.89 | 8.1 | 主模型 |
    | XGBoost | 0.98 | 0.88 | 8.4 | 与RF持平 |
    
    ## 6. Step 5:时间序列(预测类题目)
    
    流程:**画图看趋势/季节 → ADF 平稳性检验 → 差分/分解 → 选模型 → 评估 → 外推预测**。
    
    ```python
    import statsmodels.api as sm
    from statsmodels.tsa.stattools import adfuller
    from statsmodels.tsa.arima.model import ARIMA
    
    # 1. 平稳性检验:p<0.05 视为平稳
    p_val = adfuller(series.dropna())[1]
    
    # 2. 差分到平稳(通常 d=1)
    # 3. ARIMA 定阶:AIC 网格搜索
    best_aic, best_order = np.inf, None
    for p in range(0, 4):
        for q in range(0, 4):
            try:
                aic = ARIMA(series, order=(p, 1, q)).fit().aic
                if aic < best_aic: best_aic, best_order = aic, (p, 1, q)
            except Exception: pass
    model = ARIMA(series, order=best_order).fit()
    print(model.summary())
    
    # 4. 外推预测 + 置信区间
    fc = model.get_forecast(steps=12)
    pred = fc.predicted_mean; ci = fc.conf_int()
    ```
    
    **时间序列雷区**:
    - 不做平稳性检验直接套 ARIMA
    - 用整段数据训练再"预测"历史段(要先划分:前 80% 训练、后 20% 验证)
    - 有季节性的数据用普通 ARIMA(该用 SARIMA/Prophet)
    - 外推步数超过数据长度的 1/3 硬预测(结果不可信,评委一眼看穿)
    - 多序列互相关时忽略(可用 VAR,但竞赛 ARIMA/SARIMA/Prophet 足够)
    
    ## 7. 模型评估与调参(论文"模型检验"节)
    
    1. **交叉验证**:小样本用 5 折 CV 报均值±std;大样本固定划分 + 报告方差
    2. **回归指标**:R²、RMSE、MAE(论文报全,评委看 R² 和 RMSE)
    3. **分类指标**:准确率 + F1 + 混淆矩阵热力图;不平衡数据报 F1 和召回不报准确率
    4. **调参**:`GridSearchCV`(小网格)或手工 2-3 轮;**不要盲目大网格**(时间成本)
    5. **泛化验证**:随机划分 3 次取平均,报告波动区间(证明模型稳定,不是运气)
    6. **与 baseline 对比**:任何 ML 模型都必须配一个简单模型(均值预测/线性回归)对比,差距就是你的"建模贡献"
    
    ## 8. 论文输出规范(每步都产出,最后直接组装)
    
    | 论文章节 | 素材来源 |
    |---|---|
    | 数据预处理 | Step2 的处理记录表(转成论文表格) |
    | 探索性分析 | Step1 数据报告 + scipilot 出的分布图/相关热力图 |
    | 模型建立 | Step4 模型公式/流程(写清目标函数与评估指标) |
    | 结果分析 | 对比表 + 预测结果表 + 误差分析 |
    | 模型检验 | Step7 交叉验证 + 灵敏度/鲁棒性 |
    | 结论 | 每个子问题的数字结果 + 特征重要性前3 |
    
    **图表规范**:图标题在下方、表标题在上方;坐标轴带单位;图内直接标注关键结论(评委 30 秒扫图);热力图用 scipilot 默认色盲安全配色,禁用 rainbow。
    
    ## 9. 竞赛雷区(红线,违反直接丢分)
    
    - ❌ 数据泄漏:用未来数据/全局统计量(如全量 mean)填充训练集——必须 train 内部 fit
    - ❌ 测试集参与特征工程或标准化
    - ❌ 过拟合汇报:测试 R² 与训练差 >0.15 还宣称"模型很好"
    - ❌ 不报告模型参数与随机种子(结果不可复现 = 评委不信任)
    - ❌ 论文里的数字与代码输出不一致(评审核对必抓)
    - ❌ 小样本(<100 行)硬上深度学习/XGBoost 大调参——过拟合且无必要
    - ❌ 只报一个指标(准确率)掩盖类别不平衡
    
    ## 10. 与现有体系对接
    
    - 在 `contest-orchestrator` 中:本技能在 **H5 解题阶段**调用,输入为当前任务卡、`unified_problem_package.yaml`(H1 题意理解产物,含数据字典和约束)、`model_contract.yaml` 和已批准数据源;输出《数据报告.md》+ 结果表必须落盘到项目工作区并进入 result_registry 和 numeric_source_map
    - 数据结果图统一交给 `modelviz` → `scipilot-figure-skill`(数据剖析/模板适配 → 科研规范质检);本技能不替代绘图技能执行视觉检查,绘图路由默认完成视觉检查
    - 若题目同时含优化部分(如"预测后做排产"),预测结果直接作为 `pyomo`/`heuristic-algorithms` 的输入参数
    - 时间序列预测结果写回 `math-modeling` 的"预测"速查流程
    
    ## 代码注释规范(B 题优化加固协同变更)
    
    进行数据处理、特征工程、统计分析、机器学习建模时,代码必须有必要的注释,像人写的而不是 AI 生成的。不用大量注释,但关键位置必须有。
    
    **必须有注释的位置**:
    - 文件头:1-3 行说明这个文件做什么
    - 数据加载和清洗:每个关键步骤注释说明做什么、为什么
    - 特征工程:每个特征注释说明含义、计算方式、业务意义
    - 模型配置:每个参数注释说明含义、取值依据、对结果的影响
    - 模型评估:每个指标注释说明含义、结果解读
    - 特征重要性:注释说明用途
    
    **注释内容红线**:注释中禁止出现内部讨论话语(经讨论、agent建议)、AI 思考过程(首先、其次、让我)、元话语(本文将、以下代码)、负向回响(之前用、v2修正、尝试了)、AI 协作痕迹(agent、prompt、审查)。注释必须是纯粹的技术说明。
    
    **详细规范和示例**:`references/code_comment_guide.md`
    
    ## 数值合理性检查规范(B 题优化加固协同变更)
    
    进行数据处理、统计分析、机器学习建模后,必须对结果进行数值合理性检查,禁止异常结果进入结果登记。
    
    **必查项**:
    - inf/nan 检测:数据和结果中不得出现无穷大或非数
    - 目标值/指标量级异常:预测值、评估指标 >1e15 或 <1e-15(非零)需要说明原因
    - 数据范围检查:特征值是否在合理范围内(如概率[0,1]、年龄>0等)
    - 缺失值检查:关键特征是否有缺失值,缺失率是否在可接受范围内
    - 异常值检查:是否存在明显的离群点,是否需要处理
    - 模型评估指标合理性:准确率、AUC、RMSE等指标是否在合理范围内
    - 结果文件完整性:JSON 可解析、CSV 列数一致、非空
    
    **检查时机**:每次数据处理和模型训练完成后立即检查,不通过的结果不得登记到 result_registry。
    
    **异常处理**:发现异常必须排查原因(数据质量问题、特征工程错误、模型参数不当等),修复后重新处理,不得带着异常结果进入下一环节。
    
    **详细规范和领域特定检查**:`references/numerical_sanity_guide.md`
    
  • skills/02-modeling/data-science-stack/scripts/README.md1.8 KBd436d56d1efdupstream ↗
    # data-science-stack · 模板脚本
    
    赛时直接调用,少写 80% 重复代码。所有脚本输出落盘,供 orchestrator result_registry 与论文组装使用。
    
    ## 脚本列表
    
    | 脚本 | 功能 | 用法 |
    |---|---|---|
    | `eda_report.py` | 一键 EDA:逐列体检报告(缺失/异常/分布/相关性/高相关对)+ 三张基础图 | `python eda_report.py data.csv --target 目标列` |
    | `timeseries_pipeline.py` | 时间序列全流程:ADF → 差分 → AIC 定阶 ARIMA → 留出验证 → 外推预测 + 置信区间 | `python timeseries_pipeline.py data.csv --date 日期列 --col 目标列 --steps 12` |
    
    ## 快速开始
    
    ```bash
    # EDA:10 分钟出数据报告 + 图表
    python scripts/eda_report.py 附件1.csv --target 销量 --out eda_out
    
    # 时间序列:预测未来 12 期
    python scripts/timeseries_pipeline.py data.csv --date date --col val --steps 12 --out ts_out
    ```
    
    ## 依赖
    
    ```bash
    pip install pandas numpy matplotlib scipy statsmodels
    ```
    
    - `statsmodels` 仅 `timeseries_pipeline.py` 需要
    - 中文字体已内置配置(SimHei / Microsoft YaHei / Noto Sans CJK),图表自动适配国赛论文
    
    ## 输出对接
    
    | 输出 | 论文用途 | 后续处理 |
    |---|---|---|
    | `report.md` | "数据预处理 / 探索性分析"节素材 | 直接摘录表格与结论 |
    | `figures/distributions.png` 等 | 探索性分析配图 | 交给 modelviz 生成并由 scipilot-figure-skill 质检后再入论文 |
    | `summary.txt` + `forecast.csv` | "模型建立 / 检验 / 预测结果"节 | 数字必须原样引用(结果只从代码生成) |
    | `forecast.png` | 预测结果图 | 同上 |
    
    ## 约定
    
    - 随机种子固定(seed=42),结果可复现
    - 所有数字与图从脚本输出产生,论文引用不得手改
    - 训练/验证划分由脚本自动完成(后 20% 留出),杜绝数据泄漏
    
  • skills/02-modeling/data-science-stack/scripts/eda_report.py6.5 KBde86fa7499bfupstream ↗
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    竞赛 EDA 一键报告生成器(data-science-stack 配套脚本 v1.0)
    
    用法:
        python eda_report.py data.csv
        python eda_report.py data.xlsx --sheet Sheet1 --target 销量 --out report_dir
    
    输出:
        report_dir/report.md   数据报告(论文"数据预处理/探索性分析"节素材)
        report_dir/figures/    分布直方图、相关热力图、分组箱线图
    
    对接: 报告落盘后进入 orchestrator 的 result_registry;图表交给 scipilot 精修。
    """
    import argparse
    import os
    import sys
    
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    
    # 中文字体(国赛论文中文图表必需)
    plt.rcParams["font.sans-serif"] = ["SimHei", "Microsoft YaHei", "Noto Sans CJK SC"]
    plt.rcParams["axes.unicode_minus"] = False
    
    
    def load_data(path: str, sheet: str | None) -> pd.DataFrame:
        """读取 csv/xlsx,自动处理 gbk 编码。"""
        if path.endswith((".xlsx", ".xls")):
            return pd.read_excel(path, sheet_name=sheet)
        for enc in ("utf-8", "gbk", "gb18030"):
            try:
                return pd.read_csv(path, encoding=enc)
            except UnicodeDecodeError:
                continue
        raise RuntimeError(f"无法解码 {path}(utf-8/gbk 均失败)")
    
    
    def iqr_outliers(s: pd.Series) -> int:
        q1, q3 = s.quantile(0.25), s.quantile(0.75)
        iqr = q3 - q1
        return int(((s < q1 - 1.5 * iqr) | (s > q3 + 1.5 * iqr)).sum())
    
    
    def build_report(df: pd.DataFrame, target: str | None, out_dir: str) -> str:
        """逐列体检 → report.md。每行结论都是论文可引用的素材。"""
        lines = ["# 数据报告", "", f"- 数据形状: {df.shape[0]} 行 × {df.shape[1]} 列", f"- 重复行: {df.duplicated().sum()}"]
        lines += ["", "## 逐列体检", "", "| 列 | 类型 | 缺失率 | 唯一值/均值 | 异常数 | 处理建议 |", "|---|---|---|---|---|---|"]
    
        num_cols, cat_cols = [], []
        for col in df.columns:
            s = df[col]
            miss = s.isnull().mean()
            if pd.api.types.is_numeric_dtype(s):
                num_cols.append(col)
                if target and col == target:
                    lines.append(f"| {col} | 数值(目标) | {miss:.1%} | 均值 {s.mean():.4g} | {iqr_outliers(s)} | 目标列 |")
                else:
                    adv = "缩尾/保留" if iqr_outliers(s) / max(len(s), 1) > 0.05 else "一般处理"
                    lines.append(f"| {col} | 数值 | {miss:.1%} | 均值 {s.mean():.4g} | {iqr_outliers(s)} | 缺失插值,异常{adv} |")
            else:
                cat_cols.append(col)
                lines.append(f"| {col} | 类别 | {miss:.1%} | {s.nunique()} 类 | - | 众数填充/OneHot |")
    
        # 相关性(数值列)
        if len(num_cols) >= 2:
            corr = df[num_cols].corr()
            strong = [(corr.index[i], corr.columns[j], corr.iloc[i, j])
                      for i in range(len(corr)) for j in range(i + 1, len(corr))
                      if abs(corr.iloc[i, j]) > 0.8]
            lines += ["", "## 相关性", ""]
            if strong:
                lines += ["高相关对 (>0.8, 需去重/注意共线性):"]
                lines += [f"- {a} ~ {b}: {r:.3f}" for a, b, r in strong]
            else:
                lines.append("- 无明显高相关对 (|r|>0.8)")
            # 与目标列的相关性排序
            if target and target in corr.columns:
                ranks = corr[target].drop(target).abs().sort_values(ascending=False)
                lines += ["", "## 与目标列相关度排序", ""]
                lines += [f"- {k}: |r|={v:.3f}" for k, v in ranks.head(8).items()]
    
        os.makedirs(out_dir, exist_ok=True)
        path = os.path.join(out_dir, "report.md")
        with open(path, "w", encoding="utf-8") as f:
            f.write("\n".join(lines))
        return path, num_cols, cat_cols
    
    
    def plot_figures(df: pd.DataFrame, num_cols, cat_cols, target, out_dir):
        """三张基础图:分布直方图、相关热力图、目标分组箱线图。"""
        fig_dir = os.path.join(out_dir, "figures")
        os.makedirs(fig_dir, exist_ok=True)
    
        # 1. 数值列分布(最多 12 列,分两排)
        cols = [c for c in num_cols if c != target][:12]
        if cols:
            n = len(cols)
            fig, axes = plt.subplots(2, (n + 1) // 2, figsize=(14, 6))
            for ax, c in zip(np.array(axes).ravel(), cols):
                df[c].dropna().hist(bins=30, ax=ax, alpha=0.7, edgecolor="white")
                ax.set_title(c, fontsize=10)
            fig.suptitle("数值列分布", fontsize=13)
            fig.tight_layout()
            fig.savefig(os.path.join(fig_dir, "distributions.png"), dpi=150)
            plt.close(fig)
    
        # 2. 相关热力图
        if len(num_cols) >= 2:
            fig, ax = plt.subplots(figsize=(8, 7))
            im = ax.imshow(df[num_cols].corr(), cmap="RdBu_r", vmin=-1, vmax=1)
            ax.set_xticks(range(len(num_cols)), num_cols, rotation=45, ha="right", fontsize=9)
            ax.set_yticks(range(len(num_cols)), num_cols, fontsize=9)
            for i in range(len(num_cols)):
                for j in range(len(num_cols)):
                    ax.text(j, i, f"{df[num_cols].corr().iloc[i, j]:.2f}",
                            ha="center", va="center", fontsize=7)
            fig.colorbar(im, shrink=0.8)
            fig.suptitle("相关热力图", fontsize=13)
            fig.tight_layout()
            fig.savefig(os.path.join(fig_dir, "correlation.png"), dpi=150)
            plt.close(fig)
    
        # 3. 目标列按类别分组箱线图
        if target and cat_cols:
            for c in cat_cols[:2]:
                fig, ax = plt.subplots(figsize=(10, 5))
                df.boxplot(column=target, by=c, ax=ax, rot=45, grid=False)
                ax.set_title(f"{target} 按 {c} 分组", fontsize=12)
                fig.suptitle("")
                fig.tight_layout()
                fig.savefig(os.path.join(fig_dir, f"group_{c}.png"), dpi=150)
                plt.close(fig)
    
        print(f"图表已输出: {fig_dir}")
    
    
    def main():
        ap = argparse.ArgumentParser(description="竞赛 EDA 一键报告")
        ap.add_argument("data", help="数据文件 (csv/xlsx)")
        ap.add_argument("--sheet", default=None, help="xlsx 的 sheet 名")
        ap.add_argument("--target", default=None, help="目标列名(预测/回归目标)")
        ap.add_argument("--out", default="eda_report", help="输出目录")
        args = ap.parse_args()
    
        df = load_data(args.data, args.sheet)
        print(f"加载成功: {df.shape[0]} 行 × {df.shape[1]} 列")
    
        report_path, num_cols, cat_cols = build_report(df, args.target, args.out)
        plot_figures(df, num_cols, cat_cols, args.target, args.out)
        print(f"报告已生成: {report_path}")
        print(f"数值列: {len(num_cols)} 个 | 类别列: {len(cat_cols)} 个")
    
    
    if __name__ == "__main__":
        main()
    
  • skills/02-modeling/data-science-stack/scripts/stat_kit.py7.0 KB135b6d2e2c00upstream ↗
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    统计推断急救包(stat_kit.py)——data-science-stack 配套脚本 v1.1
    
    Kimi 评审 P0 建议:概率统计未系统学 → 预置 8 个"即用即走"检验,
    每个检验输出:统计量 + p 值 + 结论 + 【论文话术】(可直接抄进论文的句子)。
    
    用法:
        python stat_kit.py ttest    data.csv --value 值列 --group 组列        # 两组独立 t 检验
        python stat_kit.py mw       data.csv --value 值列 --group 组列        # Mann-Whitney U(非正态)
        python stat_kit.py chi2     data.csv --col1 类别A --col2 类别B        # 卡方独立性
        python stat_kit.py anova    data.csv --value 值列 --group 组列        # 单因素方差分析
        python stat_kit.py shapiro  data.csv --value 值列                     # 正态性 Shapiro-Wilk
        python stat_kit.py ks       data.csv --value 值列                     # 正态性 K-S
        python stat_kit.py regress  data.csv --y 目标列 --x x1,x2             # 线性回归(含 DW 残差自相关)
        python stat_kit.py vif      data.csv --cols x1,x2,x3                  # 多重共线性 VIF
    
    依赖: pip install numpy pandas scipy statsmodels
    """
    from __future__ import annotations
    
    import argparse
    import sys
    
    import numpy as np
    import pandas as pd
    from scipy import stats
    
    
    def load(path: str) -> pd.DataFrame:
        for enc in ("utf-8", "gbk", "gb18030"):
            try:
                return pd.read_csv(path, encoding=enc)
            except UnicodeDecodeError:
                continue
        raise RuntimeError(f"无法解码 {path}")
    
    
    def talk(stat_name: str, stat: float, p: float, alpha: float = 0.05) -> str:
        sig = "显著" if p < alpha else "不显著"
        return (f"【论文话术】{stat_name}检验统计量为 {stat:.4f},p 值 = {p:.4f}"
                f"({'<0.05' if p < alpha else '>0.05'}),差异{sig}。"
                f"(p<0.05 时:表明……存在统计学差异;否则:不能拒绝原假设,差异无统计学意义。)")
    
    
    def need(series) -> pd.Series:
        return pd.to_numeric(series, errors="coerce").dropna()
    
    
    def cmd_ttest(a, v, g):
        df = a[[v, g]].dropna()
        groups = [need(df.loc[df[g] == k, v]) for k in df[g].unique()[:2]]
        if len(groups) < 2 or min(len(x) for x in groups) < 2:
            sys.exit("[FATAL] ttest 需要两组且每组 ≥2 个样本")
        t, p = stats.ttest_ind(*groups, equal_var=False)
        print(f"t = {t:.4f}  p = {p:.4f}  自由度 ≈ {min(len(x)-1 for x in groups)}(Welch 近似)")
        print(talk("t", t, p))
    
    
    def cmd_mw(a, v, g):
        df = a[[v, g]].dropna()
        groups = [need(df.loc[df[g] == k, v]) for k in df[g].unique()[:2]]
        u, p = stats.mannwhitneyu(*groups, alternative="two-sided")
        print(f"U = {u:.4f}  p = {p:.4f}")
        print(talk("Mann-Whitney U", u, p))
    
    
    def cmd_chi2(a, c1, c2):
        ct = pd.crosstab(a[c1], a[c2])
        chi2, p, dof, _ = stats.chi2_contingency(ct)
        print(f"chi2 = {chi2:.4f}  p = {p:.4f}  自由度 = {dof}")
        print(f"交叉表:\n{ct.to_string()}")
        print(talk("卡方", chi2, p))
    
    
    def cmd_anova(a, v, g):
        df = a[[v, g]].dropna()
        groups = [need(df.loc[df[g] == k, v]) for k in df[g].unique()]
        if len(groups) < 2:
            sys.exit("[FATAL] ANOVA 需要 ≥2 组")
        f, p = stats.f_oneway(*groups)
        print(f"F = {f:.4f}  p = {p:.4f}")
        print(talk("单因素方差分析", f, p))
        if p < 0.05:
            print("提示: 组间差异显著,可用 Tukey HSD 找出具体差异组 "
                  "(statsmodels.stats.multicomp.pairwise_tukeyhsd)")
    
    
    def cmd_shapiro(a, v):
        s = need(a[v])
        if len(s) > 5000:
            print("[WARN] n>5000,Shapiro 过于敏感,建议结合偏度/峰度判断")
        w, p = stats.shapiro(s.sample(min(len(s), 5000), random_state=42))
        print(f"W = {w:.4f}  p = {p:.4f}")
        print(talk("Shapiro-Wilk 正态性", w, p))
        print("(p>0.05:不拒绝正态假设,可用参数检验;否则用非参数检验)")
    
    
    def cmd_ks(a, v):
        s = need(a[v])
        mu, sd = s.mean(), s.std()
        # 用自定义 CDF 绕开 scipy 新版 kstest 的 args 传参差异
        d, p = stats.kstest(s, lambda x: stats.norm.cdf(x, mu, sd))
        print(f"D = {d:.4f}  p = {p:.4f}")
        print(talk("K-S 正态性", d, p))
    
    
    def cmd_regress(a, y, xs):
        import statsmodels.api as sm
        X = a[xs.split(",")].apply(pd.to_numeric, errors="coerce")
        Y = pd.to_numeric(a[y], errors="coerce")
        mask = X.notna().all(axis=1) & Y.notna()
        Xc, Yc = sm.add_constant(X[mask]), Y[mask]
        model = sm.OLS(Yc, Xc).fit()
        print(model.summary2().tables[1].to_string())
        print(f"R^2 = {model.rsquared:.4f}  调整R^2 = {model.rsquared_adj:.4f}")
        # Durbin-Watson 残差自相关
        from statsmodels.stats.stattools import durbin_watson
        dw = durbin_watson(model.resid)
        print(f"Durbin-Watson = {dw:.4f}(≈2 无自相关;<1.5 或 >2.5 需警惕)")
        print("【论文话术】回归模型 R^2 = {:.4f},DW = {:.4f},各系数显著性见上表。".format(model.rsquared, dw))
    
    
    def cmd_vif(a, cols):
        import statsmodels.api as sm
        X = a[cols.split(",")].apply(pd.to_numeric, errors="coerce").dropna()
        Xc = sm.add_constant(X)
        out = {}
        for c in X.columns:
            vif = 1 / (1 - sm.OLS(X[c], Xc.drop(columns=c)).fit().rsquared)
            out[c] = round(float(vif), 2)
        print("VIF(>10 严重共线性,>5 需关注):")
        for k, v in out.items():
            flag = "  [WARN] VIF>10" if v > 10 else ("  [~] VIF>5" if v > 5 else "")
            print(f"  {k}: {v}{flag}")
    
    
    COMMANDS = {"ttest": cmd_ttest, "mw": cmd_mw, "chi2": cmd_chi2, "anova": cmd_anova,
                "shapiro": cmd_shapiro, "ks": cmd_ks, "regress": cmd_regress, "vif": cmd_vif}
    CMD_ARGS = {"ttest": {"value": "v", "group": "g"}, "mw": {"value": "v", "group": "g"},
                "chi2": {"col1": "c1", "col2": "c2"}, "anova": {"value": "v", "group": "g"},
                "shapiro": {"value": "v"}, "ks": {"value": "v"},
                "regress": {"y": "y", "x": "xs"}, "vif": {"cols": "cols"}}
    
    
    def main():
        ap = argparse.ArgumentParser(description="统计推断急救包(8 检验)")
        ap.add_argument("cmd", choices=list(COMMANDS), help="检验名")
        ap.add_argument("data", help="数据 csv")
        ap.add_argument("--value", default=None, help="数值列")
        ap.add_argument("--group", default=None, help="分组列")
        ap.add_argument("--col1", default=None)
        ap.add_argument("--col2", default=None)
        ap.add_argument("--y", default=None, help="回归目标列")
        ap.add_argument("--x", default=None, help="回归特征列(逗号分隔)")
        ap.add_argument("--cols", default=None, help="VIF 特征列(逗号分隔)")
        args = ap.parse_args()
    
        df = load(args.data)
        kwargs = {CMD_ARGS[args.cmd][k]: v for k, v in {"value": args.value, "group": args.group,
                                                        "col1": args.col1, "col2": args.col2,
                                                        "y": args.y, "x": args.x,
                                                        "cols": args.cols}.items()
                  if k in CMD_ARGS[args.cmd]}
        COMMANDS[args.cmd](df, **kwargs)
    
    
    if __name__ == "__main__":
        main()
    
  • skills/02-modeling/data-science-stack/scripts/timeseries_pipeline.py5.1 KBc22d52746091upstream ↗
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    """
    时间序列自动流水线(data-science-stack 配套脚本 v1.0)
    
    流程: 画图 → ADF 平稳性检验 → 差分 → AIC 定阶 ARIMA → 拟合 → 留出验证 → 外推预测
    
    用法:
        python timeseries_pipeline.py data.csv --date 日期 --col 销量 --steps 12
        python timeseries_pipeline.py data.csv --col 销量 --steps 24 --seasonal 12
    
    输出 (out_dir/):
        summary.txt      模型摘要 + 指标(论文"模型建立/检验"节素材)
        forecast.csv     预测值 + 95% 置信区间
        forecast.png     历史+预测图(含置信带)
    
    依赖: pip install pandas numpy matplotlib statsmodels
    """
    import argparse
    import os
    import warnings
    
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    import statsmodels.api as sm
    from statsmodels.tsa.arima.model import ARIMA
    from statsmodels.tsa.stattools import adfuller
    
    warnings.filterwarnings("ignore")
    plt.rcParams["font.sans-serif"] = ["SimHei", "Microsoft YaHei", "Noto Sans CJK SC"]
    plt.rcParams["axes.unicode_minus"] = False
    
    
    def load_series(data: str, date_col: str | None, col: str) -> pd.Series:
        df = pd.read_csv(data)
        if date_col:
            df[date_col] = pd.to_datetime(df[date_col])
            df = df.sort_values(date_col).set_index(date_col)
        s = pd.to_numeric(df[col], errors="coerce").dropna()
        if len(s) < 12:
            raise RuntimeError(f"序列仅 {len(s)} 个有效点,ARIMA 至少需要 ~12 个")
        return s
    
    
    def pick_order(s: pd.Series, d: int, max_pq: int = 4) -> tuple:
        """AIC 网格搜索 (p, q)。"""
        best_aic, best_order = np.inf, (1, d, 1)
        for p in range(0, max_pq + 1):
            for q in range(0, max_pq + 1):
                try:
                    aic = ARIMA(s, order=(p, d, q)).fit().aic
                    if aic < best_aic:
                        best_aic, best_order = aic, (p, d, q)
                except Exception:
                    pass
        return best_order
    
    
    def main():
        ap = argparse.ArgumentParser(description="时间序列 ARIMA 全流程")
        ap.add_argument("data", help="csv 文件")
        ap.add_argument("--date", default=None, help="日期列名(可选)")
        ap.add_argument("--col", required=True, help="目标数值列名")
        ap.add_argument("--steps", type=int, default=12, help="预测步数(≤ 数据长度/3)")
        ap.add_argument("--seasonal", type=int, default=None,
                        help="季节周期(如 12=月度),指定则用 SARIMA 粗调")
        ap.add_argument("--out", default="ts_forecast", help="输出目录")
        args = ap.parse_args()
    
        if args.steps > 60:
            print("警告: 预测步数过大,结果可信度低(建议 ≤ 数据长度/3)")
        s = load_series(args.data, args.date, args.col)
        os.makedirs(args.out, exist_ok=True)
    
        # 1. 平稳性检验
        p_val = adfuller(s)[1]
        d = 0 if p_val < 0.05 else (1 if adfuller(s.diff().dropna())[1] < 0.05 else 2)
        lines = [f"# 时间序列分析报告", "", f"- 数据点数: {len(s)}", f"- ADF p 值: {p_val:.4f}",
                 f"- 差分阶数 d: {d}", ""]
    
        # 2. 训练/验证划分(前 80% 训练)
        n_val = max(1, len(s) // 5)
        train, valid = s.iloc[:-n_val], s.iloc[-n_val:]
    
        # 3. 定阶 + 拟合
        order = pick_order(train, d, max_pq=4)
        model = ARIMA(train, order=order).fit()
        lines += [f"- 选定模型: ARIMA{order}", f"- AIC: {model.aic:.2f}", ""]
    
        # 4. 验证集评估(论文"模型检验")
        fc = model.get_forecast(steps=n_val)
        pred = fc.predicted_mean
        rmse = float(np.sqrt(np.mean((valid.values - pred.values) ** 2)))
        mape = float(np.mean(np.abs((valid.values - pred.values) / (valid.values + 1e-9)))) * 100
        lines += ["## 留出验证(后 20%)", "", f"- RMSE: {rmse:.4f}", f"- MAPE: {mape:.2f}%", ""]
    
        # 5. 全量重拟合 + 外推
        full = ARIMA(s, order=order).fit()
        f = full.get_forecast(steps=args.steps)
        mean, ci = f.predicted_mean, f.conf_int()
        fc_df = pd.DataFrame({"forecast": mean.round(4), **ci.round(4)})
        fc_df.to_csv(os.path.join(args.out, "forecast.csv"), encoding="utf-8-sig")
        lines += [f"## 未来 {args.steps} 期预测", "", fc_df.to_string()]
    
        with open(os.path.join(args.out, "summary.txt"), "w", encoding="utf-8") as fh:
            fh.write("\n".join(lines))
        print("\n".join(lines))
    
        # 6. 画图:历史 + 验证 + 预测
        fig, ax = plt.subplots(figsize=(12, 5))
        ax.plot(s.index if hasattr(s.index, "tolist") else range(len(s)), s.values,
                label="历史", color="#2c3e50")
        fc_idx = range(len(s), len(s) + args.steps)
        ax.plot(fc_idx, mean.values, label="预测", color="#c0392b", marker="o", ms=3)
        ax.fill_between(fc_idx, ci.iloc[:, 0], ci.iloc[:, 1],
                        color="#c0392b", alpha=0.15, label="95% 置信区间")
        ax.axvline(len(s), color="gray", ls="--", lw=0.8)
        ax.set_title(f"ARIMA{order} 预测", fontsize=13)
        ax.legend()
        fig.tight_layout()
        fig.savefig(os.path.join(args.out, "forecast.png"), dpi=150)
        print(f"\n输出: {args.out}/ (summary.txt, forecast.csv, forecast.png)")
    
    
    if __name__ == "__main__":
        main()
    
  • skills/02-modeling/data-science-stack/references/code-templates/matlab-ml/random_forest_template.m1.5 KB5d220aa8eec7upstream ↗
    % 随机森林 MATLAB 模板 (需要 Statistics and Machine Learning Toolbox)
    
    function [model, metrics] = rf_template()
        % 加载数据
        % TODO: data = readtable('data.csv');
        rng(42);
        n = 500;
        X = randn(n, 4);
        y = 3*X(:,1) + 2*X(:,2).^2 - 1.5*X(:,3) + 0.5*X(:,4).*X(:,1) + 0.5*randn(n,1);
    
        % 划分
        cv = cvpartition(n, 'HoldOut', 0.2);
        X_train = X(training(cv), :);
        y_train = y(training(cv));
        X_test = X(test(cv), :);
        y_test = y(test(cv));
    
        % 标准化
        [X_train, mu, sigma] = zscore(X_train);
        X_test = (X_test - mu) ./ sigma;
    
        % 训练随机森林
        model = TreeBagger(300, X_train, y_train, ...
            'Method', 'regression', ...
            'MinLeafSize', 5, ...
            'NumPredictorsToSample', 'all', ...
            'OOBPrediction', 'on');
    
        % 预测
        y_pred = str2double(predict(model, X_test));
    
        % 评估
        r2 = 1 - sum((y_test - y_pred).^2) / sum((y_test - mean(y_test)).^2);
        mae = mean(abs(y_test - y_pred));
        rmse = sqrt(mean((y_test - y_pred).^2));
    
        fprintf('\n===== 随机森林 评估结果 =====\n');
        fprintf('R²  = %.4f\n', r2);
        fprintf('MAE = %.4f\n', mae);
        fprintf('RMSE = %.4f\n', rmse);
    
        % 特征重要性
        imp = model.OOBPermutedPredictorDeltaError;
        figure;
        barh(imp);
        xlabel('Importance');
        title('Random Forest Feature Importance');
        set(gca, 'YTickLabel', {'x1','x2','x3','x4'});
    
        metrics = struct('r2', r2, 'mae', mae, 'rmse', rmse);
    end
    
  • skills/02-modeling/data-science-stack/references/code-templates/python-ml/anova_template.py12 KB239cefe6f7b3upstream ↗
    """
    方差分析 (ANOVA) 模板
    适用:多组均值差异检验、因素显著性分析、实验设计分析
    
    问题适配点:
      1. 修改 _load_data() —— 替换为实际分组数据(CSV/实验数据)
      2. 修改 one_way 的 groups —— 替换为实际分组列表
      3. 修改 two_way 的 data —— 替换为实际两因素数据(带分组标签)
      4. 如不满足正态性/方差齐性,结果会自动提示使用 Kruskal-Wallis
      5. 如有多个因变量,考虑 MANOVA 或多重比较校正(Bonferroni)
    """
    
    import numpy as np
    import pandas as pd
    from scipy import stats
    import statsmodels.api as sm
    from statsmodels.formula.api import ols
    from statsmodels.stats.multicomp import pairwise_tukeyhsd
    import matplotlib.pyplot as plt
    from typing import List, Optional, Tuple, Dict
    
    plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
    plt.rcParams['axes.unicode_minus'] = False
    
    
    class ANOVAAnalyzer:
        """方差分析框架"""
    
        def __init__(self):
            self.oneway_result: Optional[dict] = None
            self.twoway_result: Optional[dict] = None
            self.posthoc_result: Optional[pd.DataFrame] = None
    
        @staticmethod
        def _load_data() -> Dict[str, np.ndarray]:
            """加载/生成分组数据"""
            # TODO: 替换为实际数据加载
            rng = np.random.default_rng(42)
            return {
                '对照组': rng.normal(loc=50, scale=5, size=30),
                '处理组A': rng.normal(loc=55, scale=5, size=30),
                '处理组B': rng.normal(loc=62, scale=6, size=30),
            }
    
        def shapiro_wilk(self, groups: Dict[str, np.ndarray],
                         verbose: bool = True) -> Dict[str, Tuple[float, float]]:
            """
            正态性检验(Shapiro-Wilk)。p > 0.05 表示不能拒绝正态分布原假设。
    
            Returns
            -------
            {组名: (W统计量, p值)}
            """
            results = {}
            for name, data in groups.items():
                w, p = stats.shapiro(data)
                results[name] = (w, p)
                if verbose:
                    status = '正态 ✓' if p > 0.05 else '非正态 ✗'
                    print(f"  {name}: W={w:.4f}, p={p:.4f}  ({status})")
            return results
    
        def levene(self, groups: Dict[str, np.ndarray],
                   center: str = 'median',
                   verbose: bool = True) -> Tuple[float, float]:
            """
            方差齐性检验(Levene)。p > 0.05 表示不能拒绝方差齐性原假设。
    
            Parameters
            ----------
            center : 'median'(推荐, 更稳健)或 'mean'
            """
            data_list = list(groups.values())
            stat, p = stats.levene(*data_list, center=center)
            if verbose:
                status = '方差齐性 ✓' if p > 0.05 else '方差不齐 ✗'
                print(f"Levene 检验: stat={stat:.4f}, p={p:.4f}  ({status})")
            return stat, p
    
        def one_way(self, groups: Dict[str, np.ndarray],
                    verbose: bool = True) -> Dict:
            """
            单因素方差分析。
    
            同时计算 eta-squared 效应量:
            - eta^2 = SS_between / SS_total
            - 小效应 0.01, 中效应 0.06, 大效应 0.14 (Cohen)
    
            Returns
            -------
            result : dict,含 'F', 'p_value', 'eta_squared', 'significant'
            """
            # TODO: 替换 groups 为实际问题分组
            data_list = list(groups.values())
            F_stat, p_value = stats.f_oneway(*data_list)
    
            # 计算 eta-squared
            all_data = np.concatenate(data_list)
            grand_mean = all_data.mean()
            ss_total = np.sum((all_data - grand_mean) ** 2)
            ss_between = sum(len(g) * (g.mean() - grand_mean) ** 2
                             for g in data_list)
            eta_sq = ss_between / ss_total if ss_total > 0 else 0
    
            self.oneway_result = {
                'F': F_stat,
                'p_value': p_value,
                'eta_squared': eta_sq,
                'significant': p_value < 0.05,
                'df_between': len(data_list) - 1,
                'df_within': len(all_data) - len(data_list),
                'ss_between': ss_between,
                'ss_total': ss_total,
            }
    
            if verbose:
                print(f"\n===== 单因素方差分析 =====")
                print(f"  F({self.oneway_result['df_between']}, "
                      f"{self.oneway_result['df_within']}) = {F_stat:.4f}")
                print(f"  p-value = {p_value:.4f}"
                      f"{' ***' if p_value < 0.001 else ' **' if p_value < 0.01 else ' *' if p_value < 0.05 else ''}")
                print(f"  eta-squared = {eta_sq:.4f} (效应量)")
    
            return self.oneway_result
    
        def two_way(self, data: pd.DataFrame,
                    formula: str = 'value ~ C(factor_A) + C(factor_B) + C(factor_A):C(factor_B)',
                    verbose: bool = True) -> Dict:
            """
            两因素方差分析(含交互作用)。
    
            Parameters
            ----------
            data : DataFrame,包含 'value', 'factor_A', 'factor_B' 列
            formula : statsmodels 公式
            """
            # TODO: 替换 data 为实际数据,调整 formula
            model = ols(formula, data=data).fit()
            anova_table = sm.stats.anova_lm(model, typ=2)
    
            self.twoway_result = {
                'anova_table': anova_table,
                'model': model,
            }
    
            if verbose:
                print(f"\n===== 两因素方差分析 =====")
                print(anova_table.round(4).to_string())
    
            return self.twoway_result
    
        def post_hoc_tukey(self, data: np.ndarray, groups: np.ndarray,
                           alpha: float = 0.05,
                           verbose: bool = True) -> pd.DataFrame:
            """
            Tukey HSD 事后多重比较。
    
            Parameters
            ----------
            data : 所有观测值(拼接为一维数组)
            groups : 对应的分组标签(与 data 等长)
            alpha : 显著性水平
            """
            tukey = pairwise_tukeyhsd(data, groups, alpha=alpha)
            self.posthoc_result = pd.DataFrame(data=tukey.summary().data[1:],
                                               columns=tukey.summary().data[0])
    
            if verbose:
                print(f"\n===== Tukey HSD 事后检验 (alpha={alpha}) =====")
                print(self.posthoc_result.to_string(index=False))
    
            return self.posthoc_result
    
        def kruskal_wallis(self, groups: Dict[str, np.ndarray],
                           verbose: bool = True) -> Dict:
            """
            非参数替代:Kruskal-Wallis H 检验(不要求正态性和方差齐性)。
    
            Returns
            -------
            result : dict,含 'H', 'p_value', 'significant'
            """
            # TODO: 当正态性或方差齐性不满足时,使用此方法替代单因素 ANOVA
            data_list = list(groups.values())
            H_stat, p_value = stats.kruskal(*data_list)
    
            result = {'H': H_stat, 'p_value': p_value,
                      'significant': p_value < 0.05}
    
            if verbose:
                print(f"\n===== Kruskal-Wallis 检验 =====")
                print(f"  H = {H_stat:.4f}, p = {p_value:.4f}"
                      f"{' ***' if p_value < 0.001 else ' **' if p_value < 0.01 else ' *' if p_value < 0.05 else ''}")
    
            return result
    
        def plot_boxplot(self, groups: Dict[str, np.ndarray],
                         title: str = '分组箱线图',
                         save_path: Optional[str] = None):
            """各组箱线图可视化"""
            names = list(groups.keys())
            data_list = [groups[name] for name in names]
    
            fig, ax = plt.subplots(figsize=(8, 5))
            bp = ax.boxplot(data_list, labels=names, patch_artist=True,
                             showmeans=True, meanprops=dict(marker='D',
                                                            markerfacecolor='red',
                                                            markersize=6))
    
            colors = plt.cm.Set2(np.linspace(0, 1, len(names)))
            for patch, color in zip(bp['boxes'], colors):
                patch.set_facecolor(color)
    
            # 叠加原始数据点
            for i, (name, d) in enumerate(groups.items()):
                jitter = np.random.default_rng(0).uniform(-0.15, 0.15, len(d))
                ax.scatter(np.full_like(d, i + 1) + jitter, d, alpha=0.4,
                           s=20, edgecolors='gray', linewidth=0.5)
    
            ax.set_xlabel('组别')
            ax.set_ylabel('观测值')
            ax.set_title(title)
            plt.tight_layout()
            if save_path:
                plt.savefig(save_path, dpi=150, bbox_inches='tight')
            plt.show()
    
        def plot_qq(self, data: np.ndarray,
                    title: str = 'Q-Q 图 (正态性检验)',
                    save_path: Optional[str] = None):
            """Q-Q 图辅助判断正态性"""
            fig, ax = plt.subplots(figsize=(5, 5))
            stats.probplot(data, dist='norm', plot=ax)
            ax.get_lines()[0].set_markerfacecolor('steelblue')
            ax.get_lines()[0].set_markeredgecolor('steelblue')
            ax.get_lines()[1].set_color('red')
            ax.set_title(title)
            plt.tight_layout()
            if save_path:
                plt.savefig(save_path, dpi=150, bbox_inches='tight')
            plt.show()
    
        def plot_residual_diagnostics(self, model_fit):
            """回归诊断图(适用于 two-way ANOVA 模型)"""
            fig, axes = plt.subplots(2, 2, figsize=(10, 8))
    
            # 残差 vs 拟合值
            fitted = model_fit.fittedvalues
            resid = model_fit.resid
            axes[0, 0].scatter(fitted, resid, alpha=0.6, color='steelblue')
            axes[0, 0].axhline(0, color='red', linestyle='--')
            axes[0, 0].set_xlabel('拟合值'), axes[0, 0].set_ylabel('残差')
            axes[0, 0].set_title('残差 vs 拟合值')
    
            # Q-Q 图
            stats.probplot(resid, dist='norm', plot=axes[0, 1])
            axes[0, 1].get_lines()[1].set_color('red')
            axes[0, 1].set_title('Q-Q 图')
    
            # 标准化残差直方图
            axes[1, 0].hist(resid / resid.std(), bins=20, density=True,
                             color='steelblue', alpha=0.7, edgecolor='white')
            x = np.linspace(-3, 3, 100)
            axes[1, 0].plot(x, stats.norm.pdf(x), 'r-', lw=1.5)
            axes[1, 0].set_title('标准化残差')
    
            # 残差 vs 顺序
            axes[1, 1].plot(resid, 'o-', color='steelblue', markersize=4)
            axes[1, 1].axhline(0, color='red', linestyle='--')
            axes[1, 1].set_xlabel('观测序号'), axes[1, 1].set_ylabel('残差')
            axes[1, 1].set_title('残差时序')
    
            plt.tight_layout()
            plt.show()
    
    
    # ===== 使用示例 =====
    if __name__ == "__main__":
        print("=== 方差分析示例 ===\n")
    
        analyzer = ANOVAAnalyzer()
    
        # ---- 单因素 ANOVA ----
        # TODO: 替换为实际分组数据
        groups = analyzer._load_data()
        print("各组描述统计:")
        for name, d in groups.items():
            print(f"  {name}: n={len(d)}, mean={np.mean(d):.2f}, std={np.std(d, ddof=1):.2f}")
    
        # 假设检验
        print("\n--- 正态性检验 (Shapiro-Wilk) ---")
        analyzer.shapiro_wilk(groups)
    
        print("\n--- 方差齐性检验 (Levene) ---")
        analyzer.levene(groups)
    
        # 单因素 ANOVA
        result = analyzer.one_way(groups)
    
        # 事后检验
        all_data = np.concatenate(list(groups.values()))
        all_labels = np.concatenate([[name] * len(d) for name, d in groups.items()])
        analyzer.post_hoc_tukey(all_data, all_labels)
    
        # 非参数备选(若假设不满足)
        kw = analyzer.kruskal_wallis(groups)
    
        # 可视化
        analyzer.plot_boxplot(groups, title='单因素 ANOVA — 各组对比')
    
        # ---- 两因素 ANOVA 示例 ----
        print("\n" + "=" * 50)
        print("===== 两因素 ANOVA 示例 =====\n")
    
        # TODO: 替换为实际问题数据
        rng = np.random.default_rng(123)
        factor_A = np.repeat(['A1', 'A2', 'A3'], 20)
        factor_B = np.tile(np.repeat(['B1', 'B2'], 10), 3)
        values = (5 * (factor_A == 'A1').astype(float) +
                  8 * (factor_A == 'A2').astype(float) +
                  7 * (factor_A == 'A3').astype(float) +
                  3 * (factor_B == 'B2').astype(float) +
                  rng.normal(0, 2, 60))
    
        df_two = pd.DataFrame({
            'value': values,
            'factor_A': factor_A,
            'factor_B': factor_B,
        })
    
        result2 = analyzer.two_way(df_two)
    
        # 残差诊断
        analyzer.plot_residual_diagnostics(result2['model'])
    
  • skills/02-modeling/data-science-stack/references/code-templates/python-ml/gmm_em_template.py10 KBb08a60082acfupstream ↗
    """
    高斯混合模型 (Gaussian Mixture Model) — EM算法实现
    ======================================================
    适用场景:
      - 数据聚类,尤其是簇呈椭圆形状、重叠、或大小不一时
      - 密度估计(生成式模型):估计数据的概率密度分布
      - 异常检测:低概率区域数据点视为异常
      - 软聚类:每个点给出属于各簇的概率(soft assignment)
    
    何时优于 K-Means:
      - 簇呈拉长形状(非圆形)→ GMM 通过协方差矩阵捕获方向性
      - 需要软分配(概率)而非硬分配 → 下游不确定性传递
      - 需要概率密度 → 生成新样本、评估新点似然
      - 簇大小/密度不均 → K-Means 偏向均匀大小
    
    何时回到 K-Means / DBSCAN:
      - 计算资源极度受限(EM每轮 O(n*k*d^2) vs K-Means O(n*k*d))
      - 簇形状不规则(非椭圆)→ DBSCAN
      - 样本量 < 维度的 10 倍 → 协方差估计不稳定
    
    模型选择(选几个分量 K):
      - BIC:对参数数量惩罚更重,偏好简洁模型(建模竞赛推荐)
      - AIC:可能选偏多分量,适用于预测而非解释场景
    
    问题适配点(需替换的 TODO 标记):
      1. 修改 _demo_data() 为实际数据加载
      2. 修改 K_range 分量数搜索范围
      3. 如需要,调整 max_iter 和 tol 收敛参数
      4. 对于文本/图像等非表格数据,先将特征转换为数值向量
    """
    import numpy as np
    from scipy.stats import multivariate_normal
    from sklearn.mixture import GaussianMixture as SklearnGMM
    import matplotlib.pyplot as plt
    
    
    class GMM:
        """高斯混合模型 — 从零实现 EM 算法"""
    
        def __init__(self, n_components: int = 3, max_iter: int = 100,
                     tol: float = 1e-4, random_state: int = 42):
            self.K = n_components
            self.max_iter = max_iter
            self.tol = tol
            self.rng = np.random.RandomState(random_state)
            self.weights_ = None          # 混合系数 (K,)
            self.means_ = None            # 均值 (K, d)
            self.covariances_ = None      # 协方差 (K, d, d)
            self.log_likelihood_ = []
    
        def _initialize(self, X: np.ndarray):
            """K-Means++风格的初始化"""
            n, d = X.shape
            # 随机选第一个中心
            idx = self.rng.choice(n, 1)
            self.means_ = X[idx].copy()
            for _ in range(1, self.K):
                # D^2 weighting
                dist_sq = np.array([np.min(np.sum((X - m) ** 2, axis=1))
                                    for m in self.means_])
                dist_sq = np.min(
                    np.array([np.sum((X[:, None] - self.means_) ** 2, axis=2)]), axis=1)
                probs = dist_sq / dist_sq.sum()
                new_idx = self.rng.choice(n, 1, p=probs)
                self.means_ = np.vstack([self.means_, X[new_idx]])
            self.covariances_ = np.array([np.cov(X.T) + 1e-3 * np.eye(d)
                                          for _ in range(self.K)])
            self.weights_ = np.ones(self.K) / self.K
    
        def _e_step(self, X: np.ndarray) -> np.ndarray:
            """E-step: 计算后验概率(责任矩阵)"""
            n = X.shape[0]
            resp = np.zeros((n, self.K))
            for k in range(self.K):
                resp[:, k] = self.weights_[k] * multivariate_normal.pdf(
                    X, mean=self.means_[k], cov=self.covariances_[k],
                    allow_singular=True)
            resp_sum = resp.sum(axis=1, keepdims=True)
            resp_sum = np.where(resp_sum < 1e-300, 1e-300, resp_sum)
            return resp / resp_sum
    
        def _m_step(self, X: np.ndarray, resp: np.ndarray):
            """M-step: 更新参数"""
            n, d = X.shape
            nk = resp.sum(axis=0) + 1e-12
            self.weights_ = nk / n
            # 更新均值
            self.means_ = (resp.T @ X) / nk[:, np.newaxis]
            # 更新协方差
            for k in range(self.K):
                diff = X - self.means_[k]
                self.covariances_[k] = ((resp[:, k][:, np.newaxis] * diff).T @ diff
                                        / nk[k])
                # 正则化防奇异
                self.covariances_[k] += 1e-6 * np.eye(d)
    
        def fit(self, X: np.ndarray):
            """训练 GMM"""
            self._initialize(X)
            prev_ll = -np.inf
            for it in range(self.max_iter):
                resp = self._e_step(X)
                self._m_step(X, resp)
                # 对数似然
                ll = 0.0
                for k in range(self.K):
                    ll += self.weights_[k] * multivariate_normal.pdf(
                        X, mean=self.means_[k], cov=self.covariances_[k],
                        allow_singular=True)
                ll = np.sum(np.log(np.maximum(ll, 1e-300)))
                self.log_likelihood_.append(ll)
                if abs(ll - prev_ll) < self.tol:
                    break
                prev_ll = ll
            return self
    
        def predict(self, X: np.ndarray) -> np.ndarray:
            """返回硬聚类标签"""
            resp = self._e_step(X)
            return np.argmax(resp, axis=1)
    
        def predict_proba(self, X: np.ndarray) -> np.ndarray:
            """返回软分配概率"""
            return self._e_step(X)
    
        def bic(self, X: np.ndarray) -> float:
            """BIC (Bayesian Information Criterion)"""
            n, d = X.shape
            # 参数个数:K-1 (weights) + K*d (means) + K*d*(d+1)/2 (covariances)
            n_params = (self.K - 1) + self.K * d + self.K * d * (d + 1) // 2
            ll = self.log_likelihood_[-1]
            return n_params * np.log(n) - 2 * ll
    
        def aic(self, X: np.ndarray) -> float:
            """AIC (Akaike Information Criterion)"""
            n, d = X.shape
            n_params = (self.K - 1) + self.K * d + self.K * d * (d + 1) // 2
            ll = self.log_likelihood_[-1]
            return 2 * n_params - 2 * ll
    
    
    # ======================== 可视化 ========================
    
    def plot_gmm_ellipses(X: np.ndarray, gmm: GMM, title: str = "GMM Result"):
        """绘制数据散点 + 各高斯分量的椭圆等高线"""
        from matplotlib.patches import Ellipse
    
        fig, ax = plt.subplots(figsize=(6, 5))
        labels = gmm.predict(X)
        sc = ax.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis',
                        s=15, alpha=0.6, edgecolors='none')
        ax.set_xlabel('x1'), ax.set_ylabel('x2')
    
        colors = plt.cm.viridis(np.linspace(0, 1, gmm.K))
        for k in range(gmm.K):
            mean = gmm.means_[k]
            cov = gmm.covariances_[k]
            # 特征分解获取椭圆参数
            vals, vecs = np.linalg.eigh(cov)
            angle = np.degrees(np.arctan2(vecs[1, 0], vecs[0, 0]))
            width, height = 2 * np.sqrt(vals)
            for std in [1, 2]:
                ell = Ellipse(xy=mean, width=std * width, height=std * height,
                              angle=angle, edgecolor=colors[k], facecolor='none',
                              linewidth=1.2 - 0.2 * (std - 1), alpha=0.6)
                ax.add_patch(ell)
            ax.scatter(*mean, c=[colors[k]], marker='x', s=80, linewidths=2)
        ax.set_title(title)
        plt.tight_layout()
        plt.savefig('gmm_result.png', dpi=150)
        plt.close()
        print("[可视化] 已保存 gmm_result.png")
    
    
    # ======================== 辅助函数 ========================
    
    def _generate_demo_data():
        """生成 3 分量 2D 混合高斯数据"""
        # TODO: 替换为实际数据加载(pd.read_csv 等)
        rng = np.random.RandomState(42)
        n = 300
        X = np.vstack([
            rng.multivariate_normal([0, 0], [[2, 1.2], [1.2, 0.8]], n),
            rng.multivariate_normal([5, 3], [[1.5, -0.5], [-0.5, 2.5]], n),
            rng.multivariate_normal([-2, 5], [[1.2, 0], [0, 0.3]], n // 2),
        ])
        return X
    
    
    # ======================== 运行示例 ========================
    
    if __name__ == "__main__":
        print("=" * 55)
        print("高斯混合模型 (GMM) — EM算法模板 — 3分量2D演示")
        print("=" * 55)
    
        X = _generate_demo_data()
    
        # ---- 模型选择:BIC/AIC 搜索最优 K ----
        # TODO: 根据实际数据复杂度调整 K_range
        print("\n[1] 模型选择 (BIC / AIC)")
        K_range = range(1, 8)
        bics, aics = [], []
        models = {}
        for k in K_range:
            gmm = GMM(n_components=k).fit(X)
            models[k] = gmm
            bics.append(gmm.bic(X))
            aics.append(gmm.aic(X))
            print(f"  K={k}: BIC={bics[-1]:.1f}, AIC={aics[-1]:.1f}")
    
        best_k = K_range[np.argmin(bics)]
        print(f"  BIC最优K = {best_k}")
    
        # ---- 从零实现的 GMM ----
        print(f"\n[2] 最终模型 (K={best_k})")
        gmm_own = GMM(n_components=best_k).fit(X)
        print(f"  对数似然: {gmm_own.log_likelihood_[-1]:.2f}")
        print(f"  混合权重: {np.round(gmm_own.weights_, 3)}")
    
        # ---- sklearn 验证 ----
        print(f"\n[3] sklearn 基准对比 (K={best_k})")
        gmm_sk = SklearnGMM(n_components=best_k, covariance_type='full',
                            random_state=42).fit(X)
        print(f"  sklearn 对数似然: {gmm_sk.lower_bound_:.2f}")
        print(f"  sklearn 混合权重: {np.round(gmm_sk.weights_, 3)}")
        print(f"  (注意: sklearn使用不同的初始化,似然值有差异属正常)")
    
        # ---- 可视化 ----
        print("\n[4] 可视化")
        plot_gmm_ellipses(X, gmm_own, f"GMM (K={best_k}) — Own Implementation")
        # 对比 sklearn
        gmm_sk_wrap = type('obj', (object,), {
            'K': best_k,
            'means_': gmm_sk.means_,
            'covariances_': gmm_sk.covariances_,
            'predict': lambda self, X: gmm_sk.predict(X),
        })()
        # plot_gmm_ellipses 需要 predict 方法,用 sklearn 结果
        labels_sk = gmm_sk.predict(X)
    
        from matplotlib.patches import Ellipse
        fig, ax = plt.subplots(figsize=(6, 5))
        ax.scatter(X[:, 0], X[:, 1], c=labels_sk, cmap='plasma', s=15, alpha=0.6)
        colors = plt.cm.plasma(np.linspace(0, 1, best_k))
        for k in range(best_k):
            mean = gmm_sk.means_[k]
            cov = gmm_sk.covariances_[k]
            vals, vecs = np.linalg.eigh(cov)
            angle = np.degrees(np.arctan2(vecs[1, 0], vecs[0, 0]))
            width, height = 2 * np.sqrt(vals)
            for std in [1, 2]:
                ell = Ellipse(xy=mean, width=std * width, height=std * height,
                              angle=angle, edgecolor=colors[k], facecolor='none',
                              linewidth=1.2, alpha=0.6)
                ax.add_patch(ell)
            ax.scatter(*mean, c=[colors[k]], marker='x', s=80, linewidths=2)
        ax.set_title(f"GMM (K={best_k}) — sklearn Benchmark")
        plt.tight_layout()
        plt.savefig('gmm_sklearn.png', dpi=150)
        plt.close()
        print("[可视化] 已保存 gmm_sklearn.png")
        print("\n完成。")
    
  • skills/02-modeling/data-science-stack/references/code-templates/python-ml/markov_chain_template.py8.1 KB43add1ab72dfupstream ↗
    """
    马尔可夫链仿真模板 (Markov Chain Simulation)
    ==============================================
    适用场景:
      - 体育赛事:网球/乒乓球逐球/逐局得分概率、胜率预测
      - 队列系统:服务台状态转移、排队长度稳态分布
      - 时间序列状态建模:天气状态(晴/阴/雨)、信用评级迁移
      - 客户行为预测:购买/流失/活跃三态转移
      - 博弈策略:马尔可夫决策过程 (MDP) 前身
    
    核心概念:
      - 转移概率矩阵 P[i,j] = P(state_j | state_i),每行和为 1
      - 稳态分布 π:πP = π(求解特征值 λ=1 的左特征向量)
      - 吸收态:一旦进入就无法离开的状态(如网球一分结束)
    
    与其他模型对比:
      - vs 回归/时序:Markov 不需要连续值,适合离散状态序列
      - vs RNN/LSTM:可解释性强,小样本即可建立,但无长期记忆
      - vs MDP:不含行动决策,仅描述自发状态转移
    
    问题适配点(需替换的 TODO 标记):
      1. 修改 _build_tennis_transition_matrix() 为实际转移概率
      2. 修改 STATE_NAMES 为实际状态名称
      3. 如为吸收链,修改 is_absorbing 逻辑
      4. 可替换仿真步数 n_sim_steps
      5. 如需文本/评分建模为状态,先做离散化
    """
    import numpy as np
    import matplotlib.pyplot as plt
    
    
    # ======================== 马尔可夫链核心类 ========================
    
    class MarkovChain:
        """离散时间马尔可夫链"""
    
        def __init__(self, P: np.ndarray, state_names: list = None):
            """
            P: (n, n) 转移概率矩阵,每行和为1
            state_names: 状态名称列表
            """
            self.P = np.asarray(P, dtype=float)
            self.n = len(P)
            # 确保每行归一化
            row_sums = self.P.sum(axis=1, keepdims=True)
            self.P = self.P / row_sums
            self.state_names = state_names or [f"S{i}" for i in range(self.n)]
            self._steady_state = None
    
        @property
        def steady_state(self) -> np.ndarray:
            """稳态分布 π:求解 πP = π 即 P^T π^T = π^T"""
            if self._steady_state is None:
                vals, vecs = np.linalg.eig(self.P.T)
                idx = np.argmin(np.abs(vals - 1.0))
                pi = np.real(vecs[:, idx])
                pi = pi / pi.sum()
                self._steady_state = pi
            return self._steady_state
    
        def is_absorbing(self, state_idx: int) -> bool:
            """判断是否为吸收态(P[i,i]=1)"""
            return abs(self.P[state_idx, state_idx] - 1.0) < 1e-10
    
        def step(self, current_state: int, rng: np.random.RandomState = None) -> int:
            """单步转移"""
            rng = rng or np.random.RandomState()
            return rng.choice(self.n, p=self.P[current_state])
    
        def simulate(self, start_state: int, n_steps: int,
                     rng: np.random.RandomState = None) -> np.ndarray:
            """仿真一条轨迹,返回状态序列"""
            rng = rng or np.random.RandomState()
            states = [start_state]
            for _ in range(n_steps):
                states.append(self.step(states[-1], rng))
            return np.array(states)
    
        def simulate_many(self, start_state: int, n_steps: int, n_chains: int = 1000,
                          verbose: bool = True) -> np.ndarray:
            """多条仿真链,返回 (n_chains, n_steps+1) 状态矩阵"""
            rng = np.random.RandomState(42)
            chains = np.zeros((n_chains, n_steps + 1), dtype=int)
            chains[:, 0] = start_state
            for t in range(n_steps):
                for c in range(n_chains):
                    chains[c, t + 1] = self.step(chains[c, t], rng)
            return chains
    
        def occupancy_over_time(self, chains: np.ndarray) -> np.ndarray:
            """计算各时刻状态占有率 (n_steps+1, n)"""
            n_steps_plus1 = chains.shape[1]
            occ = np.zeros((n_steps_plus1, self.n))
            for t in range(n_steps_plus1):
                vals, cnts = np.unique(chains[:, t], return_counts=True)
                occ[t, vals] = cnts / chains.shape[0]
            return occ
    
        def convergence_check(self, tol: float = 1e-4) -> int:
            """检测 P^k 是否收敛到稳态(返回近似收敛所需的步数)"""
            Pk = np.eye(self.n)
            for k in range(1, 200):
                Pk = Pk @ self.P
                if np.allclose(Pk, np.outer(np.ones(self.n), self.steady_state),
                               atol=tol):
                    return k
            return -1  # 未收敛
    
    
    # ======================== 可视化 ========================
    
    def plot_transition_heatmap(mc: MarkovChain):
        """绘制转移矩阵热力图"""
        fig, ax = plt.subplots(figsize=(5.5, 4.5))
        im = ax.imshow(mc.P, cmap='YlOrRd', vmin=0, vmax=1)
        for i in range(mc.n):
            for j in range(mc.n):
                ax.text(j, i, f"{mc.P[i, j]:.2f}", ha='center', va='center',
                        fontsize=9, color='black' if mc.P[i, j] < 0.5 else 'white')
        ax.set_xticks(range(mc.n)), ax.set_yticks(range(mc.n))
        ax.set_xticklabels(mc.state_names)
        ax.set_yticklabels(mc.state_names)
        ax.set_title("Transition Probability Matrix")
        ax.set_xlabel("To State"), ax.set_ylabel("From State")
        plt.colorbar(im, ax=ax, shrink=0.8)
        plt.tight_layout()
        plt.savefig('markov_heatmap.png', dpi=150)
        plt.close()
        print("[可视化] 已保存 markov_heatmap.png")
    
    
    def plot_state_distribution_over_time(occupancy: np.ndarray,
                                          state_names: list):
        """绘制状态占有率随时间变化"""
        t_vals = np.arange(occupancy.shape[0])
        plt.figure(figsize=(7, 4))
        for s in range(occupancy.shape[1]):
            plt.plot(t_vals, occupancy[:, s], label=state_names[s], linewidth=1.8)
        plt.xlabel("Step"), plt.ylabel("Proportion")
        plt.title("State Distribution Over Time")
        plt.legend()
        plt.grid(alpha=0.3)
        plt.tight_layout()
        plt.savefig('markov_distribution.png', dpi=150)
        plt.close()
        print("[可视化] 已保存 markov_distribution.png")
    
    
    # ======================== 运行示例 ========================
    
    def _build_tennis_chain() -> MarkovChain:
        """
        网球一分内的状态转移模型
        状态: [A发球优势, B发球优势, 相持A略优, 相持B略优, A得分, B得分]
        最后两个为吸收态
        """
        # TODO: 替换为实际问题的转移概率(可用数据统计或文献值)
        P = np.array([
            [0.20, 0.05, 0.35, 0.15, 0.20, 0.05],   # A发球优势
            [0.05, 0.25, 0.10, 0.35, 0.05, 0.20],   # B发球优势
            [0.05, 0.02, 0.38, 0.20, 0.30, 0.05],   # 相持A略优
            [0.02, 0.08, 0.18, 0.37, 0.05, 0.30],   # 相持B略优
            [0.00, 0.00, 0.00, 0.00, 1.00, 0.00],   # A得分(吸收)
            [0.00, 0.00, 0.00, 0.00, 0.00, 1.00],   # B得分(吸收)
        ])
        names = ["A-serve-adv", "B-serve-adv", "rally-A", "rally-B",
                 "A-POINT", "B-POINT"]
        return MarkovChain(P, names)
    
    
    if __name__ == "__main__":
        print("=" * 55)
        print("马尔可夫链仿真模板 — 网球逐球仿真演示")
        print("=" * 55)
    
        mc = _build_tennis_chain()
    
        # ---- 稳态分布 ----
        print("\n[1] 稳态分布 π")
        pi = mc.steady_state
        for name, p in zip(mc.state_names, pi):
            print(f"  {name:15s}: {p:.4f}")
        # TODO: 如果包含吸收态,稳态分布将全部集中在吸收态
    
        # ---- 收敛检测 ----
        print("\n[2] 收敛速度")
        conv_k = mc.convergence_check()
        print(f"  P^k 收敛到稳态所需步数: {conv_k if conv_k > 0 else '>200 (未收敛)'}")
    
        # ---- 单链仿真 ----
        print("\n[3] 单条链仿真")
        n_sim_steps = 30  # TODO: 根据实际需求调整仿真步数
        chain = mc.simulate(start_state=0, n_steps=n_sim_steps)
        state_seq_str = " → ".join([mc.state_names[s] for s in chain[:8]])
        print(f"  前8步轨迹: {state_seq_str} ...")
    
        # ---- 多条链统计 ----
        print("\n[4] 多条链占用率 (n_chains=1000)")
        chains = mc.simulate_many(start_state=0, n_steps=20, n_chains=1000)
        occ = mc.occupancy_over_time(chains)
        print(f"  最后时刻状态分布: {np.round(occ[-1], 4)}")
        # 吸收概率
        print(f"  A得分概率={occ[-1, 4]:.4f}, B得分概率={occ[-1, 5]:.4f}")
    
        # ---- 可视化 ----
        print("\n[5] 可视化")
        plot_transition_heatmap(mc)
        plot_state_distribution_over_time(occ[:, :4], mc.state_names[:4])
        print("\n完成。")
    
  • skills/02-modeling/data-science-stack/references/code-templates/python-ml/random_forest_template.py2.2 KB8e8e231c0492upstream ↗
    """
    随机森林 回归/分类模板
    适用:表格数据、中等样本、需要可解释性
    """
    
    import numpy as np
    import pandas as pd
    from sklearn.ensemble import RandomForestRegressor
    from sklearn.model_selection import train_test_split, cross_val_score
    from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
    import matplotlib.pyplot as plt
    
    
    def train_random_forest(X_train, X_test, y_train, y_test):
        """训练随机森林并评估"""
        model = RandomForestRegressor(
            n_estimators=300,
            max_depth=None,
            min_samples_split=5,
            min_samples_leaf=2,
            max_features='sqrt',
            random_state=42,
            n_jobs=-1
        )
    
        model.fit(X_train, y_train)
        y_pred = model.predict(X_test)
    
        r2 = r2_score(y_test, y_pred)
        mae = mean_absolute_error(y_test, y_pred)
        rmse = np.sqrt(mean_squared_error(y_test, y_pred))
    
        print(f"\n===== 随机森林 评估结果 =====")
        print(f"R² = {r2:.4f}")
        print(f"MAE = {mae:.4f}")
        print(f"RMSE = {rmse:.4f}")
    
        # 特征重要性
        importance = pd.DataFrame({
            'feature': X_train.columns,
            'importance': model.feature_importances_
        }).sort_values('importance', ascending=False)
    
        print(f"\n特征重要性:")
        print(importance.to_string(index=False))
    
        # 特征重要性图
        plt.figure(figsize=(8, 5))
        plt.barh(importance['feature'][::-1], importance['importance'][::-1])
        plt.xlabel('Importance')
        plt.title('Random Forest Feature Importance')
        plt.tight_layout()
        plt.savefig('rf_importance.png', dpi=150)
        plt.close()
    
        return model, {'r2': r2, 'mae': mae, 'rmse': rmse}
    
    
    if __name__ == "__main__":
        from xgboost_template import load_data, feature_engineering
        from sklearn.preprocessing import StandardScaler
    
        X, y = load_data()
        X = feature_engineering(X)
    
        X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=0.2, random_state=42
        )
    
        scaler = StandardScaler()
        X_train_scaled = pd.DataFrame(scaler.fit_transform(X_train), columns=X.columns)
        X_test_scaled = pd.DataFrame(scaler.transform(X_test), columns=X.columns)
    
        model, metrics = train_random_forest(X_train_scaled, X_test_scaled, y_train, y_test)
    
  • skills/02-modeling/data-science-stack/references/code-templates/python-ml/time_series_forecast_template.py14 KB7c4f4b362699upstream ↗
    """
    时间序列预测 (Time Series Forecasting) 模板
    适用:销售量预测、经济指标预测、时序数据分析
    问题适配点:
      1. 修改 _load_data() —— 加载实际时间序列数据(CSV/Excel/数据库)
      2. 修改 data_freq —— 数据频率:'D'每日, 'W'每周, 'M'每月, 'Q'季度, 'Y'年度
      3. 调整 ARIMA/SARIMA 阶数 —— 根据 ACF/PACF 图手动选择或启用 auto_arima
      4. 如需预测外生变量,使用 SARIMAX 并传 exog 参数
      5. 多序列 → 对每个序列分别建模,或使用 VAR/VARMAX
    """
    
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from scipy import stats
    from statsmodels.tsa.stattools import adfuller
    from statsmodels.tsa.seasonal import seasonal_decompose
    from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
    from statsmodels.tsa.arima.model import ARIMA
    from statsmodels.tsa.statespace.sarimax import SARIMAX
    from statsmodels.stats.diagnostic import acorr_ljungbox
    import warnings
    warnings.filterwarnings('ignore')
    
    plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
    plt.rcParams['axes.unicode_minus'] = False
    
    
    class TimeSeriesForecaster:
        """时间序列预测框架(基于 ARIMA/SARIMA)"""
    
        def __init__(self, data: Optional[pd.Series] = None,
                     freq: str = 'M'):
            """
            Parameters
            ----------
            data : 时间序列数据(pandas Series,带 DatetimeIndex)
            freq : 数据频率,用于生成日期范围
            """
            self.data = data
            self.freq = freq
            self.model = None
            self.model_fit = None
            self.forecast_result = None
    
        @staticmethod
        def _load_data() -> pd.Series:
            """
            加载或生成时间序列数据。
    
            Returns
            -------
            pandas Series,索引为时间戳
            """
            # TODO: 替换为实际数据加载逻辑
            # 示例:生成带季节性的合成数据
            n = 120  # 10年 × 12月
            t = np.arange(n)
            trend = 0.15 * t
            seasonal = 5 * np.sin(2 * np.pi * t / 12)  # 年度周期
            noise = np.random.default_rng(42).normal(0, 1.5, n)
            y = 100 + trend + seasonal + noise
    
            idx = pd.date_range(start='2015-01-01', periods=n, freq='M')
            return pd.Series(y, index=idx, name='value')
    
        def check_stationarity(self, series: Optional[pd.Series] = None,
                               verbose: bool = True) -> dict:
            """
            ADF 平稳性检验。p < 0.05 表示拒绝"存在单位根"的原假设,即序列平稳。
    
            Returns
            -------
            result : dict,含 'adf_stat', 'p_value', 'used_lag', 'is_stationary'
            """
            if series is None:
                series = self.data
            s = series.dropna()
            adf_result = adfuller(s, autolag='AIC')
            is_stationary = adf_result[1] < 0.05
    
            if verbose:
                print(f"ADF 统计量: {adf_result[0]:.4f}")
                print(f"p-value:     {adf_result[1]:.4f}")
                print(f"使用滞后阶数: {adf_result[2]}")
                print(f"结论: {'平稳' if is_stationary else '非平稳,需要差分'}\n")
    
            return {'adf_stat': adf_result[0], 'p_value': adf_result[1],
                    'used_lag': adf_result[2], 'is_stationary': is_stationary}
    
        def decompose(self, series: Optional[pd.Series] = None,
                      period: int = 12, model: str = 'additive'):
            """
            季节分解(趋势 + 季节 + 残差)。
    
            Parameters
            ----------
            period : 季节周期(月数据=12,季度=4,周数据=52)
            model : 'additive' 加法模型 或 'multiplicative' 乘法模型
            """
            if series is None:
                series = self.data
            result = seasonal_decompose(series.dropna(), model=model, period=period)
    
            fig, axes = plt.subplots(4, 1, figsize=(12, 8), sharex=True)
            axes[0].plot(result.observed, color='black', lw=1)
            axes[0].set_ylabel('Observed')
            axes[1].plot(result.trend, color='steelblue', lw=1.5)
            axes[1].set_ylabel('Trend')
            axes[2].plot(result.seasonal, color='darkorange', lw=1)
            axes[2].set_ylabel('Seasonal')
            axes[3].plot(result.resid, color='gray', lw=0.8)
            axes[3].set_ylabel('Residual')
            axes[3].set_xlabel('Time')
            fig.suptitle('时间序列季节分解', fontsize=14)
            plt.tight_layout()
            plt.show()
            return result
    
        def plot_acf_pacf(self, series: Optional[pd.Series] = None,
                          lags: int = 40):
            """绘制 ACF / PACF 图,辅助定阶 (p, q) 选择"""
            if series is None:
                series = self.data
            s = series.dropna()
    
            fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 4))
            plot_acf(s, lags=lags, ax=ax1)
            ax1.set_title('自相关函数 (ACF)')
            plot_pacf(s, lags=lags, ax=ax2, method='ywm')
            ax2.set_title('偏自相关函数 (PACF)')
            plt.tight_layout()
            plt.show()
    
        def fit_arima(self, order: Tuple[int, int, int] = (1, 1, 1),
                      series: Optional[pd.Series] = None,
                      verbose: bool = True):
            """
            拟合 ARIMA 模型。
    
            Parameters
            ----------
            order : (p, d, q) 阶数
                p — 自回归阶数(PACF 截尾点)
                d — 差分阶数(使序列平稳的最小差分次数)
                q — 移动平均阶数(ACF 截尾点)
            """
            # TODO: 根据 ACF/PACF 图调整阶数
            if series is None:
                series = self.data
            s = series.dropna()
            self.model = ARIMA(s, order=order)
            self.model_fit = self.model.fit()
    
            if verbose:
                print(self.model_fit.summary())
            return self.model_fit
    
        def fit_sarima(self, order: Tuple[int, int, int] = (1, 1, 1),
                       seasonal_order: Tuple[int, int, int, int] = (1, 1, 1, 12),
                       series: Optional[pd.Series] = None,
                       verbose: bool = True):
            """
            拟合 SARIMA 模型(含季节成分)。
    
            Parameters
            ----------
            order : (p, d, q)
            seasonal_order : (P, D, Q, s)
                P — 季节自回归阶数, D — 季节差分阶数
                Q — 季节移动平均阶数, s — 季节周期长度
            """
            # TODO: 根据季节性 ACF/PACF 调整季节阶数
            if series is None:
                series = self.data
            s = series.dropna()
            self.model = SARIMAX(s, order=order,
                                 seasonal_order=seasonal_order,
                                 enforce_stationarity=False,
                                 enforce_invertibility=False)
            self.model_fit = self.model.fit(disp=False)
    
            if verbose:
                print(self.model_fit.summary())
            return self.model_fit
    
        def forecast(self, steps: int = 12,
                     series: Optional[pd.Series] = None,
                     alpha: float = 0.05) -> pd.DataFrame:
            """
            预测未来 steps 步,含 95% 置信区间。
    
            Returns
            -------
            DataFrame,列:['forecast', 'lower_ci', 'upper_ci']
            """
            if self.model_fit is None:
                raise RuntimeError("请先调用 fit_arima() 或 fit_sarima() 拟合模型")
            if series is None:
                series = self.data
    
            fc = self.model_fit.get_forecast(steps=steps)
            fc_mean = fc.predicted_mean
            fc_ci = fc.conf_int(alpha=alpha)
    
            last_date = series.index[-1]
            new_index = pd.date_range(start=last_date, periods=steps + 1,
                                      freq=self.freq)[1:]
    
            self.forecast_result = pd.DataFrame({
                'forecast': fc_mean.values,
                'lower_ci': fc_ci.iloc[:, 0].values,
                'upper_ci': fc_ci.iloc[:, 1].values,
            }, index=new_index)
            return self.forecast_result
    
        def evaluate(self, true_values: pd.Series,
                     pred_values: pd.Series) -> dict:
            """
            评价指标:MAE, RMSE, MAPE。
    
            Parameters
            ----------
            true_values : 真实值
            pred_values : 预测值
            """
            # 对齐索引
            common_idx = true_values.index.intersection(pred_values.index)
            y_true = true_values.loc[common_idx].values
            y_pred = pred_values.loc[common_idx].values
    
            mae = np.mean(np.abs(y_true - y_pred))
            rmse = np.sqrt(np.mean((y_true - y_pred) ** 2))
            mape = np.mean(np.abs((y_true - y_pred) / (y_true + 1e-10))) * 100
    
            return {'MAE': mae, 'RMSE': rmse, 'MAPE': mape}
    
        def residual_diagnostics(self, lags: Optional[int] = None,
                                 verbose: bool = True) -> dict:
            """
            残差诊断:Ljung-Box 白噪声检验。
            p > 0.05 表示残差为白噪声(模型充分提取信息)。
    
            Returns
            -------
            dict : {'ljung_box_stat', 'ljung_box_pvalue', 'is_white_noise'}
            """
            if self.model_fit is None:
                raise RuntimeError("请先拟合模型")
            resid = self.model_fit.resid
    
            lags_use = min(10, len(resid) // 5) if lags is None else lags
            lb_result = acorr_ljungbox(resid.dropna(), lags=[lags_use],
                                       return_df=True)
            p_value = lb_result['lb_pvalue'].values[0]
            is_white = p_value > 0.05
    
            if verbose:
                print(f"Ljung-Box 检验 (lag={lags_use}):")
                print(f"  p-value = {p_value:.4f}")
                print(f"  结论: {'残差为白噪声 ✓' if is_white else '残差存在自相关 ✗'}\n")
    
            return {'ljung_box_stat': lb_result['lb_stat'].values[0],
                    'ljung_box_pvalue': p_value, 'is_white_noise': is_white}
    
        def plot_forecast(self, series: Optional[pd.Series] = None,
                          train_ratio: float = 0.8,
                          save_path: Optional[str] = None):
            """绘制历史数据 + 预测 ± 置信区间"""
            if self.forecast_result is None:
                raise RuntimeError("请先调用 forecast()")
            if series is None:
                series = self.data
    
            fig, ax = plt.subplots(figsize=(12, 5))
    
            # 用最近一部分训练数据(避免图太密)
            n_show = int(len(series) * (1 - train_ratio)) + len(self.forecast_result)
            n_show = max(n_show, len(self.forecast_result) * 2)
            show_start = max(0, len(series) - n_show)
    
            ax.plot(series.index[show_start:], series.values[show_start:],
                    'navy', lw=1.5, label='历史数据')
            ax.plot(self.forecast_result.index, self.forecast_result['forecast'],
                    'red', lw=2, label='预测值')
            ax.fill_between(self.forecast_result.index,
                             self.forecast_result['lower_ci'],
                             self.forecast_result['upper_ci'],
                             color='red', alpha=0.15, label='95% 置信区间')
            ax.axvline(x=series.index[-1], color='gray', linestyle='--', lw=1)
            ax.set_xlabel('时间')
            ax.set_ylabel('数值')
            ax.set_title('时间序列预测结果')
            ax.legend()
            plt.tight_layout()
            if save_path:
                plt.savefig(save_path, dpi=150, bbox_inches='tight')
            plt.show()
    
        def plot_residuals(self, save_path: Optional[str] = None):
            """残差诊断图:残差时序 + 直方图 + Q-Q 图"""
            if self.model_fit is None:
                raise RuntimeError("请先拟合模型")
            resid = self.model_fit.resid.dropna()
    
            fig, axes = plt.subplots(1, 3, figsize=(14, 4))
    
            axes[0].plot(resid, color='steelblue', lw=0.8)
            axes[0].axhline(0, color='red', linestyle='--')
            axes[0].set_title('残差序列')
    
            axes[1].hist(resid, bins=30, density=True, color='steelblue',
                         alpha=0.7, edgecolor='white')
            x = np.linspace(resid.min(), resid.max(), 200)
            axes[1].plot(x, stats.norm.pdf(x, resid.mean(), resid.std()),
                         'r-', lw=1.5)
            axes[1].set_title('残差分布')
    
            stats.probplot(resid, dist='norm', plot=axes[2])
            axes[2].get_lines()[1].set_color('steelblue')
            axes[2].set_title('Q-Q 图')
    
            plt.tight_layout()
            if save_path:
                plt.savefig(save_path, dpi=150, bbox_inches='tight')
            plt.show()
    
    
    # ===== 使用示例 =====
    if __name__ == "__main__":
        print("=== 时间序列预测示例 ===\n")
    
        # 1) 加载数据
        forecaster = TimeSeriesForecaster(freq='M')
        data = forecaster._load_data()
        print(f"数据范围: {data.index[0].date()} ~ {data.index[-1].date()}")
        print(f"数据点数: {len(data)}\n")
    
        # 2) 平稳性检验
        forecaster.check_stationarity(data)
    
        # 3) 季节分解
        forecaster.decompose(data, period=12, model='additive')
    
        # 4) ACF/PACF 图
        forecaster.plot_acf_pacf(data.diff().dropna(), lags=30)
    
        # 5) 拟合 SARIMA
        # TODO: 根据 ACF/PACF 图调整 order 和 seasonal_order
        forecaster.fit_sarima(
            order=(1, 1, 1),
            seasonal_order=(1, 1, 1, 12),
            series=data
        )
    
        # 6) 残差诊断
        forecaster.residual_diagnostics()
    
        # 7) 预测
        forecast_result = forecaster.forecast(steps=12, series=data, alpha=0.05)
        print("未来 12 期预测:\n", forecast_result[['forecast', 'lower_ci', 'upper_ci']])
    
        # 8) 画图
        forecaster.plot_forecast(data, train_ratio=0.7)
        forecaster.plot_residuals()
    
        # ===== Prophet 备选方案(注释,需 pip install prophet) =====
        # from prophet import Prophet
        # df = data.reset_index()
        # df.columns = ['ds', 'y']
        # model = Prophet(yearly_seasonality=True, weekly_seasonality=False)
        # model.fit(df)
        # future = model.make_future_dataframe(periods=12, freq='M')
        # forecast = model.predict(future)
        # model.plot(forecast)
        # model.plot_components(forecast)
        # plt.show()
    
  • skills/02-modeling/data-science-stack/references/code-templates/python-ml/xgboost_template.py4.6 KB7afa118407b2upstream ↗
    """
    XGBoost 回归/分类模板
    适用:表格数据、非线性预测
    问题适配点:
      1. 修改 load_data() 加载实际数据
      2. 选择回归(XGBRegressor)或分类(XGBClassifier)
      3. 调整特征工程
      4. 调整超参数
    """
    
    import numpy as np
    import pandas as pd
    from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
    from sklearn.preprocessing import StandardScaler, LabelEncoder
    from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
    import xgboost as xgb
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    
    def load_data():
        """加载数据"""
        # TODO: 替换为实际数据加载
        # df = pd.read_csv('data.csv') 或 pd.read_excel('data.xlsx')
        # 生成演示数据
        np.random.seed(42)
        n = 500
        X = pd.DataFrame({
            'feature_1': np.random.randn(n),
            'feature_2': np.random.randn(n),
            'feature_3': np.random.randn(n),
            'feature_4': np.random.randn(n),
        })
        y = (3 * X['feature_1'] + 2 * X['feature_2'] ** 2
             - 1.5 * X['feature_3'] + 0.5 * X['feature_4'] * X['feature_1']
             + np.random.randn(n) * 0.5)
        return X, y
    
    
    def eda(df):
        """探索性数据分析"""
        print("=" * 50)
        print("描述性统计")
        print("=" * 50)
        print(df.describe())
    
        print("\n缺失值检查:")
        print(df.isnull().sum())
    
        # 相关性热力图
        plt.figure(figsize=(10, 8))
        sns.heatmap(df.corr(), annot=True, cmap='RdBu_r', center=0, fmt='.2f')
        plt.title('Correlation Heatmap')
        plt.tight_layout()
        plt.savefig('correlation_heatmap.png', dpi=150)
        plt.close()
    
    
    def feature_engineering(X, y=None, is_train=True):
        """特征工程"""
        X = X.copy()
    
        # 1. 缺失值处理
        for col in X.columns:
            if X[col].isnull().sum() > 0:
                X[col] = X[col].fillna(X[col].median())  # 数值→中位数
    
        return X
    
    
    def train_xgboost(X_train, X_test, y_train, y_test):
        """训练 XGBoost 并评估"""
        # 基础模型
        model = xgb.XGBRegressor(
            n_estimators=300,
            max_depth=5,
            learning_rate=0.1,
            subsample=0.8,
            colsample_bytree=0.8,
            reg_alpha=1,
            reg_lambda=1,
            random_state=42,
            n_jobs=-1
        )
    
        model.fit(X_train, y_train,
                  eval_set=[(X_train, y_train), (X_test, y_test)],
                  verbose=False)
    
        y_pred = model.predict(X_test)
    
        # 评估指标
        r2 = r2_score(y_test, y_pred)
        mae = mean_absolute_error(y_test, y_pred)
        rmse = np.sqrt(mean_squared_error(y_test, y_pred))
    
        print(f"\n===== XGBoost 评估结果 =====")
        print(f"R² = {r2:.4f}")
        print(f"MAE = {mae:.4f}")
        print(f"RMSE = {rmse:.4f}")
    
        # 特征重要性
        importance = pd.DataFrame({
            'feature': X_train.columns,
            'importance': model.feature_importances_
        }).sort_values('importance', ascending=False)
    
        print(f"\n特征重要性:")
        print(importance.to_string(index=False))
    
        # 预测 vs 真实值
        plt.figure(figsize=(6, 6))
        plt.scatter(y_test, y_pred, alpha=0.5, s=10)
        plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--', lw=1)
        plt.xlabel('True Values')
        plt.ylabel('Predictions')
        plt.title(f'XGBoost: R² = {r2:.4f}')
        plt.tight_layout()
        plt.savefig('xgboost_pred_vs_true.png', dpi=150)
        plt.close()
    
        return model, {'r2': r2, 'mae': mae, 'rmse': rmse}
    
    
    def hyperparameter_tuning(X_train, y_train):
        """超参数网格搜索"""
        param_grid = {
            'max_depth': [3, 5, 7],
            'learning_rate': [0.01, 0.05, 0.1],
            'n_estimators': [200, 300, 500],
            'subsample': [0.7, 0.8, 1.0],
        }
        xgb_model = xgb.XGBRegressor(random_state=42, n_jobs=-1)
        grid = GridSearchCV(xgb_model, param_grid, cv=5,
                            scoring='r2', n_jobs=-1, verbose=1)
        grid.fit(X_train, y_train)
        print(f"\n最优参数: {grid.best_params_}")
        print(f"最优 R²: {grid.best_score_:.4f}")
        return grid.best_estimator_
    
    
    if __name__ == "__main__":
        X, y = load_data()
    
        # EDA
        eda(X)
    
        # 特征工程
        X = feature_engineering(X)
    
        # 划分
        X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=0.2, random_state=42
        )
    
        # 标准化(XGBoost 不必须,但做 baseline 对比时需要)
        scaler = StandardScaler()
        X_train_scaled = pd.DataFrame(scaler.fit_transform(X_train), columns=X.columns)
        X_test_scaled = pd.DataFrame(scaler.transform(X_test), columns=X.columns)
    
        # 训练 XGBoost
        model, metrics = train_xgboost(X_train_scaled, X_test_scaled, y_train, y_test)
    
        # 超参数优化(可选)
        # best_model = hyperparameter_tuning(X_train_scaled, y_train)
    
  • skills/02-modeling/data-science-stack/references/code_comment_guide.md6.2 KBb6e668c47088upstream ↗
    # 数据处理与机器学习代码注释规范
    
    本规范适用于数据清洗、特征工程、统计分析、机器学习模型(XGBoost/随机森林/ARIMA/LSTM等)的代码。注释必须是纯粹的技术说明,禁止元话语、负向回响、内部讨论和 AI 协作痕迹。
    
    ## 一、必须有注释的位置
    
    ### 1. 文件头
    
    每个 Python 文件开头必须有 1-3 行说明这个文件做什么。
    
    ```python
    """
    企业信贷风险评估:数据清洗 + 特征工程 + XGBoost模型
    输入:123家企业进销项发票数据(CSV)
    输出:信用评级、违约概率、特征重要性
    """
    ```
    
    ### 2. 数据加载和清洗
    
    ```python
    # 加载原始发票数据,编码=gbk(中文Windows导出默认编码)
    df = pd.read_csv('data/invoices.csv', encoding='gbk')
    
    # 数据清洗:删除空值行(<1%,直接删除不影响结果)
    df = df.dropna(subset=['invoice_amount', 'invoice_date'])
    
    # 异常值处理:发票金额>1000万的标记为异常(占比0.3%,可能是录入错误)
    df['is_outlier'] = df['invoice_amount'] > 10000000
    
    # 日期解析:发票日期转为datetime,用于计算账龄
    df['invoice_date'] = pd.to_datetime(df['invoice_date'])
    ```
    
    ### 3. 特征工程
    
    每个特征必须注释说明含义、计算方式、业务意义。
    
    ```python
    # 特征1:企业总交易额(所有发票金额之和),反映企业经营规模
    df['total_amount'] = df.groupby('company_id')['invoice_amount'].transform('sum')
    
    # 特征2:交易频次(发票数量),反映企业经营活跃度
    df['transaction_count'] = df.groupby('company_id')['invoice_id'].transform('count')
    
    # 特征3:平均账期(发票日期到付款日期的平均天数),反映企业资金周转能力
    df['avg_payment_days'] = (df['payment_date'] - df['invoice_date']).dt.days.groupby(df['company_id']).transform('mean')
    
    # 特征4:进项销项比(进项金额/销项金额),反映企业上下游关系
    df['input_output_ratio'] = df['input_amount'] / df['output_amount']
    ```
    
    ### 4. 模型配置和训练
    
    ```python
    # 模型:XGBoost二分类(违约预测),选择原因:处理非线性关系+特征交互+缺失值鲁棒
    model = XGBClassifier(
        n_estimators=200,        # 树的数量:200(交叉验证确定,100以下欠拟合,300以上过拟合)
        max_depth=6,             # 树深度:6(标准值,太深则过拟合,太浅则欠拟合)
        learning_rate=0.1,       # 学习率:0.1(标准值,与n_estimators权衡)
        subsample=0.8,           # 行采样:0.8(防止过拟合)
        colsample_bytree=0.8,    # 列采样:0.8(防止过拟合)
        random_state=42           # 随机种子:42(结果可复现)
    )
    
    # 训练集/测试集划分:7:3,分层抽样(保证正负样本比例一致)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=42)
    
    # 模型训练
    model.fit(X_train, y_train)
    ```
    
    ### 5. 模型评估
    
    ```python
    # 评估指标:AUC(主要指标,衡量排序能力)、准确率、召回率、F1
    y_pred = model.predict(X_test)
    y_pred_proba = model.predict_proba(X_test)[:, 1]
    
    auc = roc_auc_score(y_test, y_pred_proba)
    accuracy = accuracy_score(y_test, y_pred)
    recall = recall_score(y_test, y_pred)
    f1 = f1_score(y_test, y_pred)
    
    print(f"AUC: {auc:.4f}")      # AUC=0.9942,排序能力强
    print(f"准确率: {accuracy:.4f}")
    print(f"召回率: {recall:.4f}")
    print(f"F1: {f1:.4f}")
    
    # 交叉验证:5折,验证模型稳定性(不同数据划分下性能波动<1.2%)
    cv_scores = cross_val_score(model, X, y, cv=5, scoring='roc_auc')
    print(f"5折CV AUC: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")
    ```
    
    ### 6. 特征重要性
    
    ```python
    # 特征重要性:Top10特征,用于模型解释和业务洞察
    feature_importance = pd.DataFrame({
        'feature': X.columns,
        'importance': model.feature_importances_
    }).sort_values('importance', ascending=False)
    
    print("Top10重要特征:")
    print(feature_importance.head(10))
    ```
    
    ## 二、注释内容红线
    
    注释中**禁止**出现以下内容:
    
    | 类别 | 禁止内容 | 错误示例 | 正确做法 |
    |------|---------|---------|---------|
    | 内部讨论 | 经讨论、团队决定、agent建议 | `# 经讨论决定用XGBoost` | `# 模型:XGBoost二分类(处理非线性+特征交互)` |
    | AI思考 | 首先、其次、让我、经过分析 | `# 首先清洗数据,然后特征工程` | `# 数据清洗:删除空值行(<1%)` |
    | 元话语 | 本文将、以下代码、接下来 | `# 以下代码训练模型` | `# 模型训练:XGBoost,参数见配置` |
    | 负向回响 | 之前用、v2修正、尝试了、失败 | `# 之前用随机森林效果不好,改用XGBoost` | `# 模型:XGBoost(AUC=0.994,优于随机森林0.978)` |
    | AI协作 | agent、prompt、审查、由H5生成 | `# 由H5 agent生成` | 直接删除 |
    
    ## 三、不需要注释的位置
    
    - 显而易见的代码(`import pandas as pd`、`for i in range(n):`)
    - 简单的变量赋值(`n = 10`、`result = []`)
    - 标准库函数调用(`print(...)`、`len(...)`)
    - 自解释的简单调用(`df.head()`、`df.describe()`)
    
    ## 四、注释密度参考
    
    | 代码类型 | 注释密度 |
    |---------|---------|
    | 数据加载和清洗 | 每个关键步骤1行注释(做什么+为什么) |
    | 特征工程 | 每个特征1行注释(含义+计算方式+业务意义) |
    | 模型配置 | 每个参数1行注释(含义+取值依据+影响) |
    | 模型训练 | 关键步骤1行注释 |
    | 模型评估 | 每个指标1行注释(含义+结果解读) |
    | 特征重要性 | 1行注释(用途) |
    | 工具函数 | docstring + 复杂逻辑行内注释 |
    
    ## 五、自检清单
    
    写完代码后,逐项检查:
    
    - [ ] 文件头有 1-3 行说明
    - [ ] 数据加载和清洗有关键步骤注释
    - [ ] 每个特征有注释(含义+计算方式+业务意义)
    - [ ] 模型配置每个参数有注释(含义+取值依据+影响)
    - [ ] 模型评估每个指标有注释(含义+结果解读)
    - [ ] 随机算法固定了 seed(结果可复现)
    - [ ] 注释中没有元话语、负向回响、内部讨论、AI协作痕迹
    - [ ] 没有过度注释(显而易见的代码不注释)
    - [ ] 数据来源有说明(文件路径+编码+行数)
    - [ ] 训练集/测试集划分有说明(比例+抽样方式+随机种子)
    
  • skills/02-modeling/data-science-stack/references/cookbook-ml.md7.1 KB5dfabab1b054upstream ↗
    # ML 类算法手册
    
    覆盖:XGBoost、LightGBM、随机森林、SVM、BP 神经网络
    
    ---
    
    ## 0. 前置:EDA 与特征工程(ML 建模的基础)
    
    **C 题评分红线:不做 EDA 直接调包的论文天然低一档。**
    
    ### EDA 必做清单
    1. 描述性统计表(均值/标准差/最大/最小/分位数)
    2. 缺失值检查(每列缺失比例)
    3. 分布检查(直方图 + 正态性检验)
    4. 相关性分析(热力图 + 散点图矩阵)
    5. 异常值检测(箱线图 / 3σ 原则)
    
    ### 特征工程清单
    1. **缺失值处理**:删除(缺失>50%)/ 均值填补 / KNN 填补 / 多重插补
    2. **异常值处理**:盖帽法 / 分箱 / 保留(如异常值有业务意义)
    3. **标准化**:Z-score(距离类模型必须)/ Min-Max / RobustScaler
    4. **编码**:One-Hot(无序类别)/ Label Encoding(有序类别)/ Target Encoding(高基数类别)
    5. **特征构造**:多项式特征 / 交互项 / 领域知识特征 / 时间特征分解
    6. **特征选择**:相关性过滤 / 方差阈值 / 逐步回归 / RF 重要性 / SHAP / RFE
    
    ---
    
    ## 1. XGBoost
    
    ### 适用场景
    - 表格数据,回归或分类
    - 样本>500,特征<10K
    - 存在非线性关系、交互效应
    - 对预测精度要求高
    
    ### 核心公式(简化)
    
    目标函数:
    $$\text{Obj} = \sum_{i} L(y_i, \hat{y}_i) + \sum_{k} \Omega(f_k)$$
    
    其中 $\Omega(f_k) = \gamma T + \frac{1}{2}\lambda\|w\|^2$(T 为叶节点数,w 为叶权重)
    
    ### 关键设计决策
    
    | 参数 | 含义 | 建议范围 | 调参顺序 |
    |------|------|---------|---------|
    | n_estimators | 树的数量 | 100-1000 | ①先定 |
    | max_depth | 树的最大深度 | 3-10 | ② |
    | learning_rate | 学习率 | 0.01-0.3 | ③与 n_estimators 联动 |
    | subsample | 样本采样比例 | 0.6-1.0 | ④ |
    | colsample_bytree | 特征采样比例 | 0.6-1.0 | ④ |
    | reg_alpha / reg_lambda | L1/L2 正则化 | 0-10 | ⑤ |
    | min_child_weight | 最小叶节点权重和 | 1-10 | ⑤ |
    
    ### 调参策略
    1. 先用默认参数跑 baseline
    2. 固定 learning_rate=0.1,用 cv 确定 n_estimators
    3. 调整 max_depth 和 min_child_weight
    4. 调 subsample 和 colsample_bytree
    5. 调正则化参数
    6. 降低 learning_rate,增加 n_estimators
    
    ### Python 模板
    
    见 `code-templates/python/ml/xgboost_template.py`
    
    ---
    
    ## 2. 随机森林 (Random Forest)
    
    ### 适用场景
    - 中等样本量(100-1000)
    - 需要可解释的特征重要性
    - 对异常值和缺失值鲁棒
    - baseline 模型首选
    
    ### 优势 vs XGBoost
    - 不需要精细调参就能获得不错效果
    - 对过拟合天然鲁棒(Bagging)
    - 特征重要性更直观
    
    ### 关键参数
    - n_estimators: 100-500
    - max_depth: None(不限制)或 5-15
    - min_samples_split: 2-10
    - max_features: sqrt(n_features)(分类)/ n_features(回归建议 1/3)
    
    ### Python 模板
    
    见 `code-templates/python/ml/random_forest_template.py`
    
    ---
    
    ## 3. SVM(支持向量机)
    
    ### 适用场景
    - 小样本(<1000)、高维特征
    - 分类边界复杂、非线性可分
    - 需要良好泛化能力
    
    ### 不适用场景
    - 大样本(>10000):训练复杂度 O(n²)~O(n³),改用 LinearSVC 或 RF/XGBoost
    - 需要概率输出:SVM 不直接输出概率,需额外 Platt scaling
    - 特征数远大于样本数:需谨慎选择核函数,线性核通常更安全
    
    ### 问题适配框架
    
    | SVM 要素 | 问题映射 | 设计要点 |
    |---------|---------|---------|
    | 核函数选择 | 数据线性可分程度 | 线性核(特征>样本数)→ RBF 核(默认首选)→ Poly 核(已知多项式关系) |
    | 惩罚参数 C | 对误分类的容忍度 | C 大 → 尽量分对(可能过拟合);C 小 → 允许更多误分类 |
    | Gamma(RBF核) | 单个样本的影响范围 | gamma 大 → 复杂边界(过拟合风险);gamma 小 → 更平滑 |
    | 类别权重 | 样本不均衡 | `class_weight='balanced'` 自动调整 |
    
    ### 调参步骤
    
    ```python
    from sklearn.svm import SVC
    from sklearn.model_selection import GridSearchCV
    from sklearn.preprocessing import StandardScaler
    
    # 必须标准化(SVM 对特征尺度极其敏感)
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)
    
    param_grid = {'C': [0.1, 1, 10, 100], 'gamma': ['scale', 'auto', 0.01, 0.1], 'kernel': ['rbf', 'linear']}
    grid = GridSearchCV(SVC(), param_grid, cv=5, scoring='accuracy', n_jobs=-1)
    grid.fit(X_scaled, y)
    ```
    
    ### 竞赛建议
    1. 先试 LinearSVC 作为快速 baseline
    2. 再试 RBF 核 + 粗粒度 GridSearch
    3. **论文中必须说明为什么选 SVM**(如:样本量小、需要最大间隔分类器),并与 RF/XGBoost 对比精度
    
    ---
    
    ## 4. BP 神经网络
    
    ### 适用场景
    - 大样本(>5000),传统 ML 效果不佳
    - 高度非线性关系
    - 图像/序列/文本等非表格数据
    
    ### 不适用场景
    - 小样本(<500):RF/XGBoost 更稳定,NN 容易过拟合
    - 需要可解释性:评审要求解释每个特征的影响时用 RF/Logistic
    - 表格数据+中等样本:先试 XGBoost,大概率效果更好
    
    ### 网络结构设计(竞赛实用)
    
    | 设计要素 | 建议 | 理由 |
    |---------|------|------|
    | 隐藏层数 | 1-3 层 | 竞赛不需要 100 层,1-2 层通常足够 |
    | 每层节点数 | 32-256 | 输入层→第一隐藏层可稍大(如 128),逐层递减 |
    | 激活函数 | 隐藏层 ReLU,输出层按任务 | 分类→softmax,回归→linear,二分类→sigmoid |
    | Dropout | 0.2-0.5 | 防过拟合,小数据用更大 dropout |
    | Batch Size | 32/64/128 | 2 的幂方便 GPU 优化 |
    | 学习率 | 1e-3 起步,Adam 优化器 | Adam 自适应,通常不需手动调 |
    | Early Stopping | patience=10-20 | val_loss 不再下降就停,防止过拟合 |
    
    ### 最小可用模板
    
    ```python
    import tensorflow as tf
    from tensorflow import keras
    from sklearn.preprocessing import StandardScaler
    
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)
    
    model = keras.Sequential([
        keras.layers.Dense(128, activation='relu', input_shape=(X.shape[1],)),
        keras.layers.Dropout(0.3),
        keras.layers.Dense(64, activation='relu'),
        keras.layers.Dropout(0.3),
        keras.layers.Dense(1, activation='sigmoid')  # 二分类
    ])
    model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
    
    early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=15, restore_best_weights=True)
    history = model.fit(X_train, y_train, validation_data=(X_val, y_val),
                        epochs=200, batch_size=32, callbacks=[early_stop], verbose=1)
    ```
    
    ### 竞赛注意事项
    - 多次运行取平均(权重初始化影响大),至少 5 次报告均值±标准差
    - 论文中必须画网络结构图(用 NN-SVG 或 draw.io)
    - 训练曲线必须放(epoch vs loss/accuracy),证明收敛且未过拟合
    - 不需要极致调参——评委看的是「为什么选 NN」「结果分析」,不是调参竞赛
    
    ---
    
    ## 5. 模型对比要求(C 题必备)
    
    评审期望看到至少 3 种方法的系统对比:
    
    | 对比维度 | 表格内容 |
    |---------|---------|
    | 模型 | 线性回归 / 随机森林 / XGBoost / ... |
    | 超参数 | 关键参数值 |
    | 训练集 R² | ... |
    | 测试集 R² | ... |
    | MAE / RMSE | ... |
    | 训练时间 | ... |
    
    选最终模型时给出理由:不只看精度,还要讨论复杂度、可解释性、过拟合风险。
    
  • skills/02-modeling/data-science-stack/references/mathorcup_experiment_protocol.md4.7 KB45cc75ba253dupstream ↗
    # MathorCup experiment protocol
    
    Use with the existing task card, model cards, evaluation protocol and run manifest. This reference owns experimental detail; contest-orchestrator owns task scope, approvals and final claims.
    
    ## Metrics and sample provenance
    
    Before comparing candidates, define the metric's target units/scales, target weights, group weights, missing-target rule, and out-of-fold aggregation order. Equal weighting of all targets is not equal weighting of target groups with different sizes. Distinguish averaging per-run metrics from scoring averaged predictions; name both explicitly when both are reported. A display table is not automatically an evaluation dataset.
    
    Retain sample-level source and use: model-fit membership, preprocessing-fit membership, model-selection exposure, evaluation role and prediction source. Not fitting a sample's label does not establish a blind test if that label influenced model selection. Mixed-source display rows cannot be pooled and presented as one independent validation set. Verify actual entity keys from original tables rather than rounded/scientific-notation display strings.
    
    Predeclare candidate acceptance, comparison families and uncertainty method in the existing evaluation plan. Repeated-CV folds are dependent; do not treat fold scores as independent replicates for an arbitrary interval or significance claim. Use a defensible paired/resampling design with its assumptions, or report descriptive variability without claiming inferential coverage. Candidate rejection because the adoption criterion was not met is a scientific result, not an implementation failure.
    
    ## Estimator capabilities and ablations
    
    Record installed package version, estimator class, actual objective/loss, target shape, multi-output strategy, and number of fits. Inspect the installed API/signature and run a small shape smoke test before assuming support. For externally verified API facts, use the current official documentation for that installed version. Do not infer target coupling from a two-dimensional predict API, or infer lack of support from a wrapper used in an older project. Explain whether the objective/structure actually couples target responses.
    
    Compare algorithms under the same split and metric; compare representations separately. For each transform, state whether it adds information or only rescales existing variables, how its constants were obtained and whether they were learned inside training folds. Mathematical monotonicity arguments do not establish bit-for-bit behavior of finite-precision/histogram implementations. Test the actual implementation without inventing a universal benefit or invariance rule.
    
    Unverified sentinel semantics require matched-population sensitivity branches, not a guessed physical interpretation. Name keeping, missing-value replacement and column-dropping diagnostics separately. Calibration constants must be recomputed from the appropriate source population; continuous mappings do not create true ordinal ground truth. Distinguish macro and pooled ordinal metrics, and relative quantile position from absolute calibrated grades.
    
    For attribution, distinguish single-field dependence, group dependence, group-size normalization and causation. Stability frequencies are descriptive unless a statistical probability interpretation has been justified. For generated/optimized scenarios, report both changed-field count and standardized displacement; distinguish total, searched, candidate and jointly accepted denominators. Original chemical/physical constraints and sensory proxy checks remain separate.
    
    ## Time, memory and restart behavior
    
    Record time budget and memory guard separately in the existing experiment configuration. Removing a time cap leaves memory protection active. Measure per-worker peak memory, current system headroom and internal thread count on the actual machine before setting concurrency; do not copy fixed memory values from a previous competition.
    
    When headroom is insufficient, stop launching workers or checkpoint owned work; never close the user's unrelated applications. Parallelize independent calculations only. Manifest, checkpoint and gate writes have one owner and occur serially. Use atomic replace for completed checkpoint records when implementing a runner.
    
    Resume by data/code/config/seed identity and skip only matching completed units. Keep interrupted or failed units explicit. Rank candidates only after the declared comparable protocol is complete; a mean over whichever folds happened to finish cannot compete against a complete run. If the user accepts a partial experiment, report its scope and limitations instead of silently altering the denominator. Keep the raw-data training entry usable without approval JSON or original-project caches.
    
  • skills/02-modeling/data-science-stack/references/numerical_sanity_guide.md11 KB1b3158dbc87dupstream ↗
    # 数据处理与机器学习数值合理性检查规范
    
    本规范适用于数据清洗、特征工程、统计分析、机器学习模型(XGBoost/随机森林/ARIMA/LSTM等)。建模完成后必须执行数值合理性自检,确保"代码运行了但结果是错的"的情况被及时发现。
    
    ## 一、必须检查的项目
    
    ### 1. 数据完整性检查
    
    ```python
    def check_data_completeness(df, required_columns=None):
        """检查数据完整性:无空值、无重复行、列数正确。"""
        issues = []
    
        # 空值检查
        null_counts = df.isnull().sum()
        for col, count in null_counts.items():
            if count > 0:
                ratio = count / len(df)
                issues.append(f"列 {col} 有 {count} 个空值({ratio:.1%})")
    
        # 重复行检查
        dup_count = df.duplicated().sum()
        if dup_count > 0:
            issues.append(f"有 {dup_count} 行重复数据")
    
        # 必需列检查
        if required_columns:
            missing_cols = [col for col in required_columns if col not in df.columns]
            if missing_cols:
                issues.append(f"缺少必需列: {', '.join(missing_cols)}")
    
        if issues:
            return False, f"数据不完整: {'; '.join(issues)}"
        return True, f"数据完整: {len(df)} 行, {len(df.columns)} 列, 无空值无重复"
    ```
    
    ### 2. 异常值检查
    
    ```python
    def check_outliers(df, columns=None, method="iqr", threshold=3.0):
        """检查异常值:IQR 方法或 Z-score 方法。"""
        import numpy as np
        issues = []
        check_cols = columns or df.select_dtypes(include=[np.number]).columns
    
        for col in check_cols:
            if col not in df.columns:
                continue
            data = df[col].dropna()
            if len(data) < 10:
                continue
    
            if method == "iqr":
                q1 = data.quantile(0.25)
                q3 = data.quantile(0.75)
                iqr = q3 - q1
                lower = q1 - 1.5 * iqr
                upper = q3 + 1.5 * iqr
                outliers = data[(data < lower) | (data > upper)]
            else:  # z-score
                z_scores = np.abs((data - data.mean()) / data.std())
                outliers = data[z_scores > threshold]
    
            if len(outliers) > 0:
                ratio = len(outliers) / len(data)
                if ratio > 0.05:  # 超过5%才警告
                    issues.append(
                        f"列 {col} 有 {len(outliers)} 个异常值({ratio:.1%}),"
                        f"范围 [{outliers.min():.2f}, {outliers.max():.2f}]"
                    )
    
        if issues:
            return False, f"发现异常值: {'; '.join(issues)}"
        return True, "未发现显著异常值"
    ```
    
    ### 3. 预测值范围检查
    
    ```python
    def check_prediction_range(y_pred, y_true=None, problem_type="regression"):
        """检查预测值范围是否合理。"""
        import numpy as np
        issues = []
    
        # inf/nan 检查
        if np.any(np.isinf(y_pred)) or np.any(np.isnan(y_pred)):
            inf_count = np.sum(np.isinf(y_pred))
            nan_count = np.sum(np.isnan(y_pred))
            issues.append(f"预测值中有 {inf_count} 个 inf、{nan_count} 个 nan")
    
        # 分类问题:预测概率范围 [0, 1]
        if problem_type == "classification" and y_pred.min() < 0:
            issues.append(f"分类预测概率小于 0: {y_pred.min()}")
        if problem_type == "classification" and y_pred.max() > 1:
            issues.append(f"分类预测概率大于 1: {y_pred.max()}")
    
        # 回归问题:预测值与真实值量级一致
        if y_true is not None and len(y_true) > 0:
            true_range = y_true.max() - y_true.min()
            pred_range = y_pred.max() - y_pred.min()
            if true_range > 0 and pred_range / true_range > 10:
                issues.append(
                    f"预测值范围 ({pred_range:.2f}) 远大于真实值范围 ({true_range:.2f}),"
                    f"可能是预测异常"
                )
    
        if issues:
            return False, f"预测值不合理: {'; '.join(issues)}"
        return True, f"预测值合理: 范围 [{y_pred.min():.4f}, {y_pred.max():.4f}]"
    ```
    
    ### 4. 评估指标合理性检查
    
    ```python
    def check_metrics_reasonable(metrics, problem_type="regression"):
        """检查评估指标是否合理。"""
        issues = []
    
        if problem_type == "classification":
            # AUC 范围 [0, 1]
            if "auc" in metrics:
                auc = metrics["auc"]
                if auc < 0 or auc > 1:
                    issues.append(f"AUC 超出 [0,1] 范围: {auc}")
                elif auc < 0.5:
                    issues.append(f"AUC < 0.5 ({auc:.4f}),模型效果比随机猜测还差")
            # 准确率范围 [0, 1]
            if "accuracy" in metrics:
                acc = metrics["accuracy"]
                if acc < 0 or acc > 1:
                    issues.append(f"准确率超出 [0,1] 范围: {acc}")
        elif problem_type == "regression":
            # R² 范围(理论上可以 < 0,但 < 0 说明模型很差)
            if "r2" in metrics and metrics["r2"] < 0:
                issues.append(f"R² < 0 ({metrics['r2']:.4f}),模型效果比均值预测还差")
            # RMSE 应该 > 0
            if "rmse" in metrics and metrics["rmse"] < 0:
                issues.append(f"RMSE 为负数: {metrics['rmse']}")
            # MAE 应该 <= RMSE
            if "mae" in metrics and "rmse" in metrics and metrics["mae"] > metrics["rmse"]:
                issues.append(f"MAE ({metrics['mae']:.4f}) > RMSE ({metrics['rmse']:.4f}),指标计算可能有误")
    
        if issues:
            return False, f"评估指标不合理: {'; '.join(issues)}"
        return True, "评估指标合理"
    ```
    
    ### 5. 过拟合检测
    
    ```python
    def check_overfitting(train_score, test_score, threshold=0.15):
        """检测过拟合:训练集和测试集性能差距过大。"""
        gap = abs(train_score - test_score)
        if train_score > 0:  # 分类指标(越大越好)
            relative_gap = gap / (abs(train_score) + 1e-10)
            if relative_gap > threshold:
                return False, (
                    f"疑似过拟合:训练集 {train_score:.4f},测试集 {test_score:.4f},"
                    f"相对差距 {relative_gap:.1%} > {threshold:.0%}"
                )
        else:  # 回归误差指标(越小越好)
            if test_score > 0 and train_score > 0:
                ratio = test_score / train_score
                if ratio > 1 + threshold:
                    return False, (
                        f"疑似过拟合:训练集误差 {train_score:.4f},测试集误差 {test_score:.4f},"
                        f"测试集是训练集的 {ratio:.1f} 倍"
                    )
        return True, f"无明显过拟合:训练集 {train_score:.4f},测试集 {test_score:.4f}"
    ```
    
    ### 6. 特征工程合理性检查
    
    ```python
    def check_feature_reasonability(X, feature_names=None):
        """检查特征是否合理:无 inf/nan、无量级差异过大。"""
        import numpy as np
        issues = []
    
        # inf/nan 检查
        if np.any(np.isinf(X.values if hasattr(X, 'values') else X)):
            issues.append("特征矩阵中有 inf 值")
        if np.any(np.isnan(X.values if hasattr(X, 'values') else X)):
            issues.append("特征矩阵中有 nan 值")
    
        # 量级差异检查
        if hasattr(X, 'columns'):
            stds = X.std()
            if len(stds) > 0 and stds.max() > 0:
                ratio = stds.max() / (stds.min() + 1e-10)
                if ratio > 1e6:
                    max_col = stds.idxmax()
                    min_col = stds.idxmin()
                    issues.append(
                        f"特征量级差异过大: {max_col} (std={stds.max():.2e}) vs "
                        f"{min_col} (std={stds.min():.2e}),比值 {ratio:.0e},建议标准化"
                    )
    
        if issues:
            return False, f"特征不合理: {'; '.join(issues)}"
        return True, "特征合理: 无 inf/nan,量级差异正常"
    ```
    
    ### 7. 时间序列稳定性检查(ARIMA/LSTM)
    
    ```python
    def check_time_series_stationarity(series, threshold=0.05):
        """检查时间序列平稳性:ADF 检验。"""
        from statsmodels.tsa.stattools import adfuller
        result = adfuller(series.dropna())
        p_value = result[1]
        if p_value > threshold:
            return False, (
                f"时间序列不平稳: ADF p-value = {p_value:.4f} > {threshold},"
                f"建议差分或使用其他方法"
            )
        return True, f"时间序列平稳: ADF p-value = {p_value:.4f} <= {threshold}"
    ```
    
    ## 二、自检脚本模板
    
    ```python
    def numerical_sanity_check_ml(model, X_train, X_test, y_train, y_test, problem_type="regression"):
        """机器学习模型数值合理性自检。"""
        checks = []
    
        # 1. 数据完整性
        ok, msg = check_data_completeness(X_train)
        checks.append(("训练数据完整性", ok, msg))
    
        # 2. 特征合理性
        ok, msg = check_feature_reasonability(X_train)
        checks.append(("特征合理性", ok, msg))
    
        # 3. 预测值范围
        y_pred_train = model.predict(X_train)
        y_pred_test = model.predict(X_test)
        ok, msg = check_prediction_range(y_pred_test, y_test, problem_type)
        checks.append(("预测值范围", ok, msg))
    
        # 4. 评估指标
        if problem_type == "classification":
            from sklearn.metrics import accuracy_score, roc_auc_score
            metrics = {
                "accuracy": accuracy_score(y_test, y_pred_test),
                "auc": roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
            }
        else:
            from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
            import numpy as np
            metrics = {
                "r2": r2_score(y_test, y_pred_test),
                "rmse": np.sqrt(mean_squared_error(y_test, y_pred_test)),
                "mae": mean_absolute_error(y_test, y_pred_test)
            }
        ok, msg = check_metrics_reasonable(metrics, problem_type)
        checks.append(("评估指标合理性", ok, msg))
    
        # 5. 过拟合检测
        if problem_type == "classification":
            train_score = accuracy_score(y_train, y_pred_train)
            test_score = accuracy_score(y_test, y_pred_test)
        else:
            train_score = r2_score(y_train, y_pred_train)
            test_score = r2_score(y_test, y_pred_test)
        ok, msg = check_overfitting(train_score, test_score)
        checks.append(("过拟合检测", ok, msg))
    
        all_passed = all(ok for _, ok, _ in checks)
        return all_passed, checks
    ```
    
    ## 三、常见问题与处理
    
    | 问题 | 可能原因 | 处理方法 |
    |------|---------|---------|
    | 数据有空值 | 原始数据缺失、合并错误 | 删除/填充空值、检查数据合并逻辑 |
    | 预测值 inf/nan | 特征中有 inf/nan、模型溢出 | 检查特征、增加正则化、调整学习率 |
    | AUC < 0.5 | 标签反了、特征无预测能力 | 检查标签、重新选择特征 |
    | R² < 0 | 模型比均值还差 | 重新选择特征、调整模型、检查数据 |
    | 过拟合 | 模型太复杂、训练数据太少 | 增加正则化、增加数据、简化模型、早停 |
    | 特征量级差异过大 | 未标准化 | 标准化/归一化特征 |
    | 时间序列不平稳 | 有趋势/季节性 | 差分、去趋势、使用 Prophet 等方法 |
    
    ## 四、自检清单
    
    建模完成后,逐项检查:
    
    - [ ] 训练/测试数据完整(无空值、无重复、列数正确)
    - [ ] 特征矩阵无 inf/nan
    - [ ] 特征量级差异正常(< 1e6 倍,否则需标准化)
    - [ ] 预测值无 inf/nan,范围合理
    - [ ] 分类预测概率在 [0, 1] 范围内
    - [ ] 评估指标合理(AUC 在 [0,1]、准确率在 [0,1]、R² 不太差)
    - [ ] 无明显过拟合(训练集和测试集性能差距 < 15%)
    - [ ] 时间序列平稳(如适用)
    - [ ] 异常值已处理(< 5%)
    - [ ] 随机种子已固定,结果可复现
    - [ ] 自检结果写入 run_manifest
    
  • skills/02-modeling/data-science-stack/references/validation_methods.md4.8 KB904aa435ce5aupstream ↗
    # 模型检验方法库
    
    本文件是方法参考,不是新增门禁。硬性验证范围仍以 `core/paper_hard_requirements.md` 和各能力 profile 的 required_evidence 为准;本文件只回答“验证项确定后具体怎么做”。在编写某小问的灵敏度、误差、稳健性段落时按需读取,不自动加载。
    
    所有检验产生的数字必须先进入结果文件或可复现脚本,再写进正文,接受数字一致性与冻结检查;不得在论文中直接写出来历不明的检验数值。
    
    ## 一、放置原则
    
    - 默认嵌入每个子问题求解末尾,单问检验篇幅约 0.5 到 1 页,如 5.1.6 灵敏度分析。
    - 全部子问题检验内容合计超过 2 页时,在模型评价章汇总关键结论;只有检验内容非常充实才独立设模型检验章。
    - 检验对象与该问模型一一对应,不用一段通用套话覆盖所有小问。
    
    ## 二、局部灵敏度分析(基础项)
    
    1. 选 3 到 5 个关键参数,即模型核心假设参数或估计量。
    2. 固定其余参数,对每个参数分别施加负 20%、负 10%、正 10%、正 20% 扰动。
    3. 记录输出变化幅度,列扰动结果表,配龙卷风图或单参数灵敏度曲线。
    4. 给出参数敏感度排序与对估计精度的要求。
    
    解读必须落到数字:最敏感参数的输出波动区间、次敏感参数、不敏感参数的波动上限,并说明哪一参数需要重点保证取值准确。
    
    ## 三、全局灵敏度分析(美赛优先,国赛冲高可选)
    
    用 Sobol 一阶指数 S1 度量独立贡献,总阶指数 ST 度量含交互的总贡献,ST 减 S1 反映交互强度。计算用 SALib。
    
    ```python
    from SALib.sample import saltelli
    from SALib.analyze import sobol
    
    # problem 给出参数名与取值区间;N 为基础采样数
    param_values = saltelli.sample(problem, N)
    Y = [model(*row) for row in param_values]
    Si = sobol.analyze(problem, np.array(Y))
    # Si['S1'] 一阶,Si['ST'] 总阶,Si['S2'] 二阶交互
    ```
    
    样本量随参数个数增长,采样与模型调用次数须在附录说明;S1、ST 结果以表或条形图给出并解释交互项。
    
    ## 四、误差分析(按模型类型选指标)
    
    | 模型类型 | 至少报告 | 建议补充 |
    |---|---|---|
    | 回归拟合 | MSE、RMSE、MAE、R² | 残差图、Q-Q 图 |
    | 预测 | RMSE、MAPE | 预测区间覆盖率、回测 |
    | 分类 | 准确率、精确率、召回率、F1、混淆矩阵 | ROC 与 AUC |
    | 优化求解 | 目标值、约束满足情况 | 截断误差、收敛判据灵敏度、与替代算法偏差 |
    | 机理仿真 | 解析解或实测对照误差 | 相对误差、网格/步长无关性验证 |
    
    残差分析要给结论:残差是否随机分布、是否存在异方差或尾部偏离,以及这对模型假设意味着什么。
    
    ## 五、稳健性与稳定性
    
    - Monte Carlo 扰动:对输入或关键参数加随机扰动,分布通常取正态,标准差取真实值或最优值的 5% 到 10%,采样不少于 1000 次,报告输出分布、95% 区间和可靠性随扰动幅度的变化。
    - 场景测试:选极端或边界场景验证模型行为合理,例如需求取上下限、约束收紧或放松。
    - 随机算法:固定并登记真实 seed,报告多次独立运行的均值与标准差,不能用单次运行曲线证明收敛稳定。
    
    ## 六、假设验证
    
    回到模型假设章逐条核验关键假设,每条用 2 到 3 句写明验证方法与结论,假设不成立时说明影响程度。
    
    | 假设 | 验证手段 |
    |---|---|
    | 线性关系 | 残差图、成分检验 |
    | 正态性 | Shapiro-Wilk 或 Q-Q 图 |
    | 独立性 | Durbin-Watson 检验 |
    | 方差齐性 | Levene 检验、残差散点 |
    | 稳态/平稳 | 频谱分析、平稳性检验 |
    
    ## 七、对比与回溯
    
    - 多方法对比:用至少两种原理不同的方法解同一问题,报告平均偏差与最大偏差,说明主方法结果可信。
    - 回溯验证:用历史数据前段建模、后段预测,与真实值对比,美赛优先采用。
    - 弱基准不算对比:对照方法应是该问题公认的强基准或合理基线,不能用明显劣化的稻草人方法衬托主模型。
    
    ## 八、按比赛分级
    
    | 检验方法 | 国赛基础 | 国赛冲高 | 美赛基础 |
    |---|---|---|---|
    | 误差指标 | 必做 | 必做 | 必做 |
    | 残差分析 | 推荐 | 必做 | 必做 |
    | 局部灵敏度 ±10%/±20% | 必做 | 必做 | 必做 |
    | 龙卷风图 | 推荐 | 必做 | 推荐 |
    | Sobol 全局灵敏度 | 不要求 | 推荐 | 强烈推荐 |
    | Monte Carlo 稳定性 | 不要求 | 必做 | 必做 |
    | 假设逐条验证 | 推荐 | 必做 | 必做 |
    | 多方法对比 | 推荐 | 必做 | 推荐 |
    | 回溯验证 | 不要求 | 推荐 | 必做 |
    
    国赛基础档把必做项嵌入各子问题末尾即可,不要求独立成章;美赛可设独立 Sensitivity Analysis 章,按全局灵敏度、参数稳健性、不确定性量化、场景测试分节。
    

Plain-text copy, no login: /skill-bundles/hua695-mathmodeling-skills-arsenal-skills-02-modeling-data-science-stack.md

// REPO STATS

13 stars