统计假设检验框架

一个全面的统计假设检验框架,提供14+种统计测试、自动测试建议和智能缓存系统,适用于A/B测试、业务分析和科学研究。

  • by gatahcha
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 gatahcha/mcp-hypothesis-tester

使用说明

MCP假设测试器v2.0

一个全面的统计假设测试框架,具有干净的OOP架构,作为FastMCP服务器构建。具有14+统计测试、自动测试建议和智能缓存系统。


🎯 这有什么作用

此MCP服务器为LLM和开发人员提供了一个完整的统计假设测试工具包。它分析您的数据,建议适当的测试,检查假设,并提供对业务友好的解释。

非常适合:

  • 📊 A/B测试和实验
  • 📈 销售和业务分析
  • 🔬 科学研究和分析
  • 🎓 用实例学习统计
  • 🤖 LLM驱动的数据分析

✨ 主要特点

🧪 14+统计测试

  • 参数: t检验(一个样本、两个样本、配对),方差分析
  • 非参数: 曼惠特尼U,威尔科克森,克鲁斯卡尔·沃利斯
  • 正常性: 夏皮罗·威尔克、科尔莫哥洛夫、安德森·达林、雅克·贝拉
  • 方差: Levene氏、Bartlett氏、F-test

🤖 智能汽车建议

分析您的数据特征并推荐最合适的测试:

  • 检查正态性、方差相等性、样本量
  • 考虑数据类型(连续、有序)
  • 提供推理和替代方案

💾 智能高速缓存

  • 将详细结果存储在临时JSON文件中
  • 使MCP响应保持轻量级(<5KB)
  • 24小时TTL自动清理
  • 需要时检索完整详细信息

📚 真实世界的例子

来自文档的6个数据集,具有精确的统计数据:

  • 销售示例 (拒绝H₀,p=0.042)
  • 咖啡店流量 (未拒绝,p=0.08)
  • 网站重新设计 (配对检验,p=0.02)
  • 咖啡机评级 (两个样本)
  • 三家店铺 (方差分析)
  • 正态性检验 (假设检查)

🎓 商务友好型口译

每个结果包括:

  • 明确决定(拒绝/不拒绝H₀)
  • 简明英语口译
  • 效应大小(科恩d,η平方)
  • 可采取行动的建议
  • 假设检查和警告

🚀 快速开始

安装

# Clone the repository
git clone https://github.com/yourusername/mcp-hypothesis-tester.git
cd mcp-hypothesis-tester

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Generate example datasets
python generate_datasets.py

# Test the implementation
python test_implementation.py

运行服务器

# Start MCP server
python -m src.mcp_server

# Or use FastMCP CLI
fastmcp run

📖 使用示例

示例1:销售分析(单样本T检验)

问题: “每日销售额是否与我们的5000美元基线有所不同?”

# Step 1: Auto-suggest appropriate test
result = suggest_test(
    dataset_name="sales_example",
    test_params={"mu0": 5000}
)
# Suggests: one_sample_t_test

# Step 2: Run the test
result = run_hypothesis_test(
    test_type="one_sample_t_test",
    dataset_name="sales_example",
    alpha=0.05,
    test_params={"mu0": 5000}
)

# Result:
{
  "summary": {
    "decision": "reject",
    "p_value": 0.0441,
    "significant": true,
    "interpretation": "The sample mean (5150.00) is statistically
                      significantly different from the hypothesized
                      value (5000). This represents a 3.0% change.",
    "effect_size": 0.309,
    "recommendation": "Evidence suggests a significant effect.
                      Investigate what drove this improvement!"
  },
  "cache_id": "abc123...",
  "note": "Full details cached. Use get_cached_result() to retrieve."
}

业务结论: 销售额从5000美元的基线真正增加到5150美元(p=0.044<0.05)。这不是偶然的运气,而是真实发生的事情! 📈


示例2:网站重新设计(配对T检验)

问题: “网站重新设计是否改变了访问时间?”

# Auto-suggest recognizes paired data
result = suggest_test("website_redesign")
# Suggests: paired_t_test (before/after comparison)

# Run test
result = run_hypothesis_test(
    test_type="paired_t_test",
    dataset_name="website_redesign"
)

# If significant:
# "Visit time increased from 5.0 to 5.5 minutes (p=0.02).
#  Analyze WHERE users spend extra time:
#  - Product pages? GOOD (considering purchases)
#  - Help pages? BAD (confused, frustrated)"

示例3:智能工作流

# 1. List available datasets
datasets = list_available_datasets()

# 2. Get test suggestion
suggestion = suggest_test("sales_example", {"mu0": 5000})
print(f"Recommended: {suggestion['test_name']}")
print(f"Reason: {suggestion['reason']}")

# 3. Check assumptions
assumptions = check_assumptions("sales_example", "one_sample_t_test")
if not assumptions['all_met']:
    print(f"Warnings: {assumptions['violations']}")
    print(f"Recommendation: {assumptions['recommendation']}")

# 4. Run test
result = run_hypothesis_test(
    suggestion['primary_test'],
    "sales_example",
    test_params=suggestion['parameters']
)

# 5. Get full details if needed
full_result = get_cached_result(result['cache_id'])

🛠️ 可用的MCP工具

1. run_hypothesis_test()

对数据集运行统计测试。返回带有缓存引用的轻量级摘要。

参数:

  • test_type -测试类型(例如,“one_sample_t_test”)
  • dataset_name -数据集文件名(例如“sales_example”)
  • alpha -显著性水平(默认值:0.05)
  • test_params -其他参数(例如,{“mu0”:5000})

退货: 包含p值、决策、解释、效果大小、cache_id的摘要


2. suggest_test()

根据数据特征自动建议适当的测试。

参数:

  • dataset_name -要分析的数据集
  • test_params -可选参数

退货: 推荐具有推理、信心和备选方案的测试


3. check_assumptions()

验证数据集是否符合测试假设。

参数:

  • dataset_name -要检查的数据集
  • test_type -测试以验证

退货: 假设检查、违规行为、建议


4. get_cached_result()

从缓存中检索完整的测试结果。

参数:

  • cache_id -测试结果中的缓存标识符
  • include_raw_data -是否包含原始数据(默认值:false)

退货: 完整的测试分析,包括所有细节


5. list_available_datasets()

列出所有包含元数据的数据集。

退货: 数据集名称、描述、推荐测试、案例参考


6. list_available_tests()

按类别列出所有统计测试。

退货: 按参数、非参数、正态性、方差组织的测试


📊 实施统计测试

参数检验

测试 用例 示例
单样本T检验 将平均值与已知值进行比较 销售额:5150美元对5000美元
双样本T检验 比较两个独立组 旧机器与新机器
配对t检验 比较配对观察结果 重新设计前后
单因素方差分析 比较3+组 各商店的销售额

非参数检验

测试 用例 示例
秩和检验 两组,非正常 满意度评级
威尔科克森签名排名 配对,非正常 前后疼痛
克鲁斯卡尔·沃利斯 3+组,非正常 工作满意度

正常性测试

测试 最适合 样本量
夏皮罗一威尔克 最强 n≤50
柯尔莫哥洛夫斯米尔诺夫 一般分布 任何
安德森·达林 尾部灵敏度 n≥7
雅克贝拉 大样本 n>2000

方差测试

测试 用例 注释
Levene的 等方差检验 对非正态性具有鲁棒性
巴特利特 等方差检查 最适合正常数据
F检验 双样本方差 对非正态性敏感

📁 项目结构

mcp-hypothesis-tester/
├── datasets/                    # 6 documentation-aligned datasets
│   ├── sales_example.json      # Case 1: One-sample t-test
│   ├── coffee_shop_traffic.json # Case 2: Fail to reject
│   ├── website_redesign.json   # Case 3: Paired t-test
│   ├── coffee_machine_ratings.json
│   ├── sales_three_stores.json # ANOVA example
│   └── normality_test_example.json
│
├── src/                         # Source code
│   ├── core/
│   │   ├── base_test.py        # Abstract base class
│   │   └── cache_manager.py    # Temp JSON caching
│   ├── tests/
│   │   ├── parametric/         # T-tests, ANOVA
│   │   ├── non_parametric/     # Mann-Whitney, Wilcoxon, etc.
│   │   ├── normality/          # Shapiro-Wilk, K-S, etc.
│   │   └── variance/           # Levene's, Bartlett's, F-test
│   ├── datasets/
│   │   └── loader.py           # Dataset management
│   ├── utils/
│   │   └── test_suggester.py  # Auto test suggestion
│   └── mcp_server.py           # FastMCP integration
│
├── Documentation/
│   ├── README.md               # This file
│   ├── USAGE_GUIDE.md          # Comprehensive usage guide
│   ├── IMPLEMENTATION-1.md     # Implementation plan
│   ├── IMPLEMENTATION_COMPLETE.md
│   ├── PROJECT_STRUCTURE.md    # Detailed structure
│   ├── LLM_USAGE_GUIDE.md      # For LLM users
│   ├── hypothesis-tester-for-megginners.md
│   └── sample-cases-and-explanation.md
│
├── Scripts/
│   ├── generate_datasets.py    # Generate example datasets
│   └── test_implementation.py  # Test suite
│
└── Configuration/
    ├── fastmcp.json
    ├── requirements.txt
    └── pyproject.toml

🏗️ 建筑

干净的OOP设计

  • 模板方法模式 -基类定义工作流
  • 依赖注入 -将缓存管理器注入测试
  • 闭原则 -易于通过新测试进行扩展
  • 单一责任 -每个类处理一种测试类型

核心组件

基本假设检验 (抽象基类)

class BaseHypothesisTest(ABC):
    def run(self, *args):
        # 1. Validate input
        # 2. Check assumptions
        # 3. Compute statistic
        # 4. Calculate effect size
        # 5. Interpret result
        # 6. Cache details
        # 7. Return TestResult

测试结果 (标准化集装箱)

@dataclass
class TestResult:
    test_name: str
    statistic: float
    p_value: float
    decision: str
    interpretation: str
    effect_size: float
    assumptions_met: Dict[str, bool]
    cache_id: str

缓存管理器 (临时JSON存储)

  • 地点: /tmp/mcp-hypothesis-cache/
  • TTL:24小时自动清理
  • 自动序列化numpy数组

测试建议器 (智能推荐)

  • 分析:正态性、方差、样本量、数据类型
  • 用于测试选择的决策树逻辑
  • 返回:测试名称、推理、置信度、备选方案

📚 文档


🧪 测试

运行综合测试套件:

python test_implementation.py

测试覆盖范围:

  • ✅ 数据集加载(6个数据集)
  • ✅ 单样本t检验(销售额:t=2.073,p=0.044→ 拒绝H₀)
  • ✅ 配对t检验(网站重新设计)
  • ✅ Shapiro-Wilk正态性检验
  • ✅ 汽车测试建议
  • ✅ 缓存管理器

结果: 所有测试通过✅


🎓 学习资源

理解P值

  • p<0.01 -非常有力的证据(高度显著)
  • 0.01≤p<0.05 -有力证据(重要)
  • 0.05≤p<0.10 -证据不足(轻微显著)
  • p≥0.10 -证据不足(不重要)

效应大小解释(Cohen d)

  • |d|<0.2 -可忽略不计
  • 0.2≤|d|<0.5 -小
  • 0.5≤|d|<0.8 -中等
  • |d|≥0.8 -大型

决策规则

  • p < a (0.05) → 拒绝H₀ (效果真实)
  • p ≥ α (0.05) → 拒绝H失败₀ (证据不足)

⚠️ 重要提示: 统计意义≠实际意义!


🔧 依赖项

fastmcp >= 2.12.0      # MCP server framework
numpy >= 1.24.0        # Array operations
scipy >= 1.10.0        # Statistical tests
pandas >= 2.0.0        # Data handling
matplotlib >= 3.7.0    # Plotting (optional)
seaborn >= 0.12.0      # Visualization (optional)
statsmodels >= 0.14.0  # Advanced statistics

📈 演出

  • 响应时间: 大多数测试<100ms
  • 缓存大小: 典型使用情况下<1MB
  • MCP响应: <5KB(仅摘要)
  • 内存: ~50MB运行时间
  • 启动时间: <2秒

🤝 贡献

欢迎投稿!需要改进的领域:

  1. 附加测试:

    • 双因素方差分析
    • 卡方(适合性、独立性)
    • 相关检验(皮尔逊、斯皮尔曼、肯德尔)
    • Z比例试验
  2. 事后测试:

    • 多重比较
    • Bonferroni校正
    • 邓氏试验
  3. 功率分析:

    • 样本量计算
    • 统计功率估计
  4. 可视化:

    • 正态性的Q-Q图
    • 用于比较的方框图
    • 分布直方图

📝 许可证

MIT许可证-有关详细信息,请参阅许可证文件


🙏 致谢

  • 内置 FastMCP
  • 统计测试来自 SciPy
  • 受现实世界业务分析需求的启发
  • 统计教育资源中的文档示例

📞 支持

  • 文档: 看 USAGE_GUIDE.md 详细示例
  • 问题: 在GitHub上打开一个问题
  • 问题: 检查 hypothesis-tester-for-megginners.md 用于解释

⭐ 明星历史

如果你觉得这个项目有用,请考虑给它一颗星! ⭐


内置❤️ 用于数据驱动决策

2.0版本-使用干净的OOP架构进行完全重写