[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CA949JA4S6KW2CGPYY6HXM":3,"skill-same:01M7CA949JA4S6KW2CGPYY6HXM":46},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":29,"ownerDescription":30,"updatedAt":31,"install":32,"resources":45},"01M7CA949JA4S6KW2CGPYY6HXM","experiment-design",null,"Best practices for designing reproducible experiments","shenyimings\u002Fskillet","shenyimings","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F89332218?v=4","01M7C9KHMXPPXMQJCKN78FKB06","Yiming Shen","01M7C9KHP4KS809T2A9T64YDWE",0,"MIT","https:\u002F\u002Fgithub.com\u002Fshenyimings\u002Fskillet\u002Fblob\u002Fmain\u002Fbenchmark\u002Fwild\u002Fdev\u002Fsafe\u002FYeachan-Heo__My-Jogyo__src__skill__experiment-design\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: experiment-design\ndescription: Best practices for designing reproducible experiments\n---\n\n# Experiment Design Patterns\n\n## When to Use\nLoad this skill when designing experiments that need to be reproducible and statistically valid.\n\n## Reproducibility Setup\n\n### Random Seeds\n```python\nimport random\nimport numpy as np\n\nSEED = 42\nrandom.seed(SEED)\nnp.random.seed(SEED)\n\nprint(f\"[DECISION] Using random seed: {SEED}\")\n```\n\n### Environment Recording\n```python\nimport sys\nprint(f\"[INFO] Python: {sys.version}\")\nprint(f\"[INFO] NumPy: {np.__version__}\")\nprint(f\"[INFO] Pandas: {pd.__version__}\")\n```\n\n## Experimental Controls\n\n### Train\u002FTest Split\n```python\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, test_size=0.2, random_state=SEED, stratify=y\n)\nprint(f\"[EXPERIMENT] Train: {len(X_train)}, Test: {len(X_test)}\")\n```\n\n### Cross-Validation\n```python\nfrom sklearn.model_selection import cross_val_score\n\nscores = cross_val_score(model, X, y, cv=5, scoring='accuracy')\nprint(f\"[METRIC] CV Accuracy: {scores.mean():.3f} (+\u002F- {scores.std()*2:.3f})\")\n```\n\n## A\u002FB Testing Pattern\n```python\nprint(\"[EXPERIMENT] A\u002FB Test Design\")\nprint(f\"[INFO] Control group: {len(control)}\")\nprint(f\"[INFO] Treatment group: {len(treatment)}\")\n\n# Power analysis\nfrom statsmodels.stats.power import TTestIndPower\npower = TTestIndPower()\nsample_size = power.solve_power(effect_size=0.5, alpha=0.05, power=0.8)\nprint(f\"[CALC] Required sample size per group: {sample_size:.0f}\")\n```\n\n## Power Analysis\n\nPower analysis ensures your experiment has sufficient sample size to detect meaningful effects. Without adequate power, you risk false negatives (missing real effects).\n\n### Sample Size Calculation\n\n```python\nfrom statsmodels.stats.power import TTestIndPower, FTestAnovaPower, NormalIndPower\nimport numpy as np\n\nprint(\"[DECISION] Conducting a priori power analysis before data collection\")\n\n# For two-group comparison (t-test)\npower_analysis = TTestIndPower()\n\n# Parameters:\n# - effect_size: Expected Cohen's d (0.2=small, 0.5=medium, 0.8=large)\n# - alpha: Significance level (typically 0.05)\n# - power: Desired statistical power (typically 0.80 or 0.90)\n# - ratio: Ratio of group sizes (1.0 = equal groups)\n\neffect_size = 0.5  # Medium effect size\nalpha = 0.05\ndesired_power = 0.80\n\nsample_size = power_analysis.solve_power(\n    effect_size=effect_size,\n    alpha=alpha,\n    power=desired_power,\n    ratio=1.0,\n    alternative='two-sided'\n)\n\nprint(f\"[STAT:estimate] Required n per group: {np.ceil(sample_size):.0f}\")\nprint(f\"[STAT:estimate] Total sample needed: {np.ceil(sample_size)*2:.0f}\")\nprint(f\"[DECISION] Targeting {effect_size} effect size (Cohen's d = medium)\")\n```\n\n### Achieved Power (Post-Hoc)\n\n```python\n# After data collection, calculate achieved power\nactual_n = 50  # Actual sample size per group\nachieved_power = power_analysis.solve_power(\n    effect_size=effect_size,\n    alpha=alpha,\n    nobs1=actual_n,\n    ratio=1.0,\n    alternative='two-sided'\n)\n\nprint(f\"[STAT:estimate] Achieved power: {achieved_power:.3f}\")\n\nif achieved_power \u003C 0.80:\n    print(f\"[LIMITATION] Study is underpowered ({achieved_power:.0%} \u003C 80%)\")\n    print(\"[LIMITATION] Negative results may be due to insufficient sample size\")\nelse:\n    print(f\"[DECISION] Adequate power achieved ({achieved_power:.0%} ≥ 80%)\")\n```\n\n### Power for Different Tests\n\n```python\n# For ANOVA (multiple groups)\nfrom statsmodels.stats.power import FTestAnovaPower\nanova_power = FTestAnovaPower()\nn_groups = 3\neffect_size_f = 0.25  # Cohen's f (0.1=small, 0.25=medium, 0.4=large)\nn_per_group = anova_power.solve_power(\n    effect_size=effect_size_f,\n    alpha=0.05,\n    power=0.80,\n    k_groups=n_groups\n)\nprint(f\"[STAT:estimate] ANOVA: {np.ceil(n_per_group):.0f} per group needed\")\n\n# For proportions (chi-square, A\u002FB tests)\nfrom statsmodels.stats.power import GofChisquarePower\nfrom statsmodels.stats.proportion import proportion_effectsize\n# Convert expected proportions to effect size\np1, p2 = 0.10, 0.15  # e.g., 10% baseline, 15% expected with treatment\nprop_effect = proportion_effectsize(p1, p2)\nprint(f\"[DECISION] Effect size h = {prop_effect:.3f} for proportions test\")\n```\n\n## Pre-registration Concept\n\nPre-registration prevents HARKing (Hypothesizing After Results are Known) and distinguishes confirmatory from exploratory analyses.\n\n### Define Analysis Before Data\n\n```python\nprint(\"[DECISION] Pre-registering analysis plan before examining data\")\n\n# Document your analysis plan BEFORE looking at the data\npreregistration = {\n    \"primary_hypothesis\": \"H1: Treatment group shows higher conversion rate than control\",\n    \"null_hypothesis\": \"H0: No difference in conversion rates between groups\",\n    \"primary_endpoint\": \"conversion_rate\",\n    \"secondary_endpoints\": [\"time_to_convert\", \"revenue_per_user\"],\n    \"alpha\": 0.05,\n    \"correction_method\": \"Bonferroni for secondary endpoints\",\n    \"minimum_effect_size\": \"5 percentage points (10% → 15%)\",\n    \"planned_sample_size\": 500,\n    \"analysis_method\": \"Two-proportion z-test\",\n    \"exclusion_criteria\": \"Users with \u003C 1 day exposure\"\n}\n\nprint(f\"[EXPERIMENT] Pre-registered analysis plan:\")\nfor key, value in preregistration.items():\n    print(f\"  {key}: {value}\")\n```\n\n### Confirmatory vs Exploratory Findings\n\n```python\n# After analysis, clearly label findings\nprint(\"[FINDING] Treatment increases conversion by 4.2pp (95% CI: [1.8, 6.6])\")\nprint(\"[STAT:ci] 95% CI [1.8, 6.6]\")\nprint(\"[STAT:effect_size] Cohen's h = 0.12 (small)\")\nprint(\"[STAT:p_value] p = 0.001\")\n# This is CONFIRMATORY because it tests pre-registered hypothesis\n\nprint(\"[OBSERVATION] Exploratory: Effect stronger for mobile users (+7.1pp)\")\nprint(\"[LIMITATION] Mobile subgroup analysis was NOT pre-registered\")\nprint(\"[DECISION] Flagging as exploratory - requires replication before action\")\n\n# Document finding type\nCONFIRMATORY = True  # Pre-registered hypothesis\nEXPLORATORY = False  # Post-hoc discovery\n\ndef label_finding(finding: str, is_confirmatory: bool):\n    \"\"\"Label findings appropriately based on pre-registration status.\"\"\"\n    if is_confirmatory:\n        print(f\"[FINDING] CONFIRMATORY: {finding}\")\n    else:\n        print(f\"[OBSERVATION] EXPLORATORY: {finding}\")\n        print(\"[LIMITATION] This finding was not pre-registered and requires replication\")\n```\n\n### Document Deviations from Plan\n\n```python\n# When you deviate from the pre-registered plan, document it!\nprint(\"[DECISION] DEVIATION FROM PRE-REGISTRATION:\")\nprint(\"  Original plan: Two-proportion z-test\")\nprint(\"  Actual analysis: Fisher's exact test\")\nprint(\"  Reason: Cell counts \u003C 5 in contingency table\")\nprint(\"  Impact: More conservative, may reduce power\")\n\n# Keep a deviation log\ndeviations = [\n    {\n        \"item\": \"Statistical test\",\n        \"planned\": \"z-test\",\n        \"actual\": \"Fisher's exact\",\n        \"reason\": \"Low expected cell counts\",\n        \"impact\": \"Minimal - Fisher's is more conservative\"\n    },\n    {\n        \"item\": \"Sample size\",\n        \"planned\": 500,\n        \"actual\": 487,\n        \"reason\": \"13 users excluded due to technical issues\",\n        \"impact\": \"Power reduced from 80% to 78%\"\n    }\n]\n\nprint(\"[EXPERIMENT] Deviation log:\")\nfor d in deviations:\n    print(f\"  - {d['item']}: {d['planned']} → {d['actual']} ({d['reason']})\")\n```\n\n## Stopping Rules\n\nDefine stopping criteria upfront to prevent p-hacking through optional stopping.\n\n### Define Success\u002FFailure Criteria Upfront\n\n```python\nprint(\"[DECISION] Defining stopping rules BEFORE experiment starts\")\n\nstopping_rules = {\n    \"success_criterion\": \"Lower 95% CI bound > 0 (effect is positive)\",\n    \"failure_criterion\": \"Upper 95% CI bound \u003C minimum_effect (effect too small)\",\n    \"futility_criterion\": \"Posterior probability of success \u003C 5%\",\n    \"max_sample_size\": 1000,\n    \"interim_analyses\": [250, 500, 750],  # Pre-specified checkpoints\n    \"alpha_spending\": \"O'Brien-Fleming\"  # Preserve overall alpha\n}\n\nprint(f\"[EXPERIMENT] Stopping rules defined:\")\nfor key, value in stopping_rules.items():\n    print(f\"  {key}: {value}\")\n```\n\n### Avoid P-Hacking Through Optional Stopping\n\n```python\n# BAD: Looking at p-value repeatedly and stopping when significant\n# This inflates false positive rate!\n\n# GOOD: Use alpha-spending functions to control Type I error\n\nfrom scipy import stats\nimport numpy as np\n\ndef obrien_fleming_boundary(alpha: float, n_looks: int, current_look: int) -> float:\n    \"\"\"\n    Calculate O'Brien-Fleming spending boundary.\n    More conservative early, less conservative late.\n    \"\"\"\n    # Information fraction\n    t = current_look \u002F n_looks\n    # O'Brien-Fleming boundary\n    z_boundary = stats.norm.ppf(1 - alpha\u002F2) \u002F np.sqrt(t)\n    p_boundary = 2 * (1 - stats.norm.cdf(z_boundary))\n    return p_boundary\n\nn_looks = 4  # Number of interim analyses\nalpha = 0.05  # Overall significance level\n\nprint(\"[DECISION] Using O'Brien-Fleming alpha-spending to control Type I error\")\nprint(\"[EXPERIMENT] Adjusted significance thresholds:\")\nfor look in range(1, n_looks + 1):\n    boundary = obrien_fleming_boundary(alpha, n_looks, look)\n    print(f\"  Look {look}\u002F{n_looks}: p \u003C {boundary:.5f} to stop for efficacy\")\n\nprint(\"[LIMITATION] Stopping early requires more extreme evidence\")\n```\n\n### Sequential Analysis Methods (SPRT)\n\n```python\n# Sequential Probability Ratio Test (SPRT)\n# Allows continuous monitoring with controlled error rates\n\ndef sprt_bounds(alpha: float, beta: float) -> tuple:\n    \"\"\"\n    Calculate SPRT decision boundaries.\n    \n    Args:\n        alpha: Type I error rate (false positive)\n        beta: Type II error rate (false negative)\n    \n    Returns:\n        (lower_bound, upper_bound) for log-likelihood ratio\n    \"\"\"\n    A = np.log((1 - beta) \u002F alpha)  # Upper boundary (accept H1)\n    B = np.log(beta \u002F (1 - alpha))  # Lower boundary (accept H0)\n    return B, A\n\nalpha, beta = 0.05, 0.20  # 5% false positive, 20% false negative (80% power)\nlower, upper = sprt_bounds(alpha, beta)\n\nprint(\"[DECISION] Using Sequential Probability Ratio Test (SPRT)\")\nprint(f\"[STAT:estimate] Stop for H0 if LLR \u003C {lower:.3f}\")\nprint(f\"[STAT:estimate] Stop for H1 if LLR > {upper:.3f}\")\nprint(\"[EXPERIMENT] Continue sampling if {:.3f} \u003C LLR \u003C {:.3f}\".format(lower, upper))\n\n# Example SPRT monitoring\ndef monitor_sprt(successes: int, trials: int, p0: float, p1: float, bounds: tuple):\n    \"\"\"Monitor SPRT decision status.\"\"\"\n    lower, upper = bounds\n    # Log-likelihood ratio\n    if successes == 0 or successes == trials:\n        llr = 0  # Avoid log(0)\n    else:\n        p_hat = successes \u002F trials\n        llr = successes * np.log(p1\u002Fp0) + (trials - successes) * np.log((1-p1)\u002F(1-p0))\n    \n    if llr > upper:\n        return \"STOP: Accept H1 (treatment effective)\", llr\n    elif llr \u003C lower:\n        return \"STOP: Accept H0 (no effect)\", llr\n    else:\n        return \"CONTINUE: Need more data\", llr\n\n# Example: Testing if conversion rate > 10% vs = 10%\np_null, p_alt = 0.10, 0.15\nstatus, llr = monitor_sprt(successes=45, trials=350, p0=p_null, p1=p_alt, bounds=(lower, upper))\nprint(f\"[STAT:estimate] Current LLR: {llr:.3f}\")\nprint(f\"[DECISION] {status}\")\n```\n\n### Document Stopping Decision\n\n```python\n# When you stop an experiment, document the decision clearly\nprint(\"[DECISION] Experiment stopped at interim analysis 2\u002F4\")\nprint(\"[STAT:estimate] Current effect: 5.2pp (95% CI: [2.1, 8.3])\")\nprint(\"[STAT:p_value] p = 0.0012 (\u003C O'Brien-Fleming boundary 0.005)\")\nprint(\"[EXPERIMENT] Decision: STOP FOR EFFICACY\")\nprint(\"[FINDING] Treatment significantly improves conversion (confirmed at interim)\")\nprint(\"[LIMITATION] Final sample (n=500) smaller than planned (n=1000)\")\nprint(\"[LIMITATION] Effect estimate may regress toward null with more data\")\n```\n\n## Documentation Pattern\n```python\nprint(\"[DECISION] Chose Random Forest over XGBoost because:\")\nprint(\"  - Better interpretability for stakeholders\")\nprint(\"  - Comparable performance (within 1% accuracy)\")\nprint(\"  - Faster training time for iteration\")\n\nprint(\"[LIMITATION] Model may not generalize to:\")\nprint(\"  - Data from different time periods\")\nprint(\"  - Users from different demographics\")\n```\n","# Experiment Design Patterns\n\n## When to Use\nLoad this skill when designing experiments that need to be reproducible and statistically valid.\n\n## Reproducibility Setup\n\n### Random Seeds\n```python\nimport random\nimport numpy as np\n\nSEED = 42\nrandom.seed(SEED)\nnp.random.seed(SEED)\n\nprint(f\"[DECISION] Using random seed: {SEED}\")\n```\n\n### Environment Recording\n```python\nimport sys\nprint(f\"[INFO] Python: {sys.version}\")\nprint(f\"[INFO] NumPy: {np.__version__}\")\nprint(f\"[INFO] Pandas: {pd.__version__}\")\n```\n\n## Experimental Controls\n\n### Train\u002FTest Split\n```python\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, test_size=0.2, random_state=SEED, stratify=y\n)\nprint(f\"[EXPERIMENT] Train: {len(X_train)}, Test: {len(X_test)}\")\n```\n\n### Cross-Validation\n```python\nfrom sklearn.model_selection import cross_val_score\n\nscores = cross_val_score(model, X, y, cv=5, scoring='accuracy')\nprint(f\"[METRIC] CV Accuracy: {scores.mean():.3f} (+\u002F- {scores.std()*2:.3f})\")\n```\n\n## A\u002FB Testing Pattern\n```python\nprint(\"[EXPERIMENT] A\u002FB Test Design\")\nprint(f\"[INFO] Control group: {len(control)}\")\nprint(f\"[INFO] Treatment group: {len(treatment)}\")\n\n# Power analysis\nfrom statsmodels.stats.power import TTestIndPower\npower = TTestIndPower()\nsample_size = power.solve_power(effect_size=0.5, alpha=0.05, power=0.8)\nprint(f\"[CALC] Required sample size per group: {sample_size:.0f}\")\n```\n\n## Power Analysis\n\nPower analysis ensures your experiment has sufficient sample size to detect meaningful effects. Without adequate power, you risk false negatives (missing real effects).\n\n### Sample Size Calculation\n\n```python\nfrom statsmodels.stats.power import TTestIndPower, FTestAnovaPower, NormalIndPower\nimport numpy as np\n\nprint(\"[DECISION] Conducting a priori power analysis before data collection\")\n\n# For two-group comparison (t-test)\npower_analysis = TTestIndPower()\n\n# Parameters:\n# - effect_size: Expected Cohen's d (0.2=small, 0.5=medium, 0.8=large)\n# - alpha: Significance level (typically 0.05)\n# - power: Desired statistical power (typically 0.80 or 0.90)\n# - ratio: Ratio of group sizes (1.0 = equal groups)\n\neffect_size = 0.5  # Medium effect size\nalpha = 0.05\ndesired_power = 0.80\n\nsample_size = power_analysis.solve_power(\n    effect_size=effect_size,\n    alpha=alpha,\n    power=desired_power,\n    ratio=1.0,\n    alternative='two-sided'\n)\n\nprint(f\"[STAT:estimate] Required n per group: {np.ceil(sample_size):.0f}\")\nprint(f\"[STAT:estimate] Total sample needed: {np.ceil(sample_size)*2:.0f}\")\nprint(f\"[DECISION] Targeting {effect_size} effect size (Cohen's d = medium)\")\n```\n\n### Achieved Power (Post-Hoc)\n\n```python\n# After data collection, calculate achieved power\nactual_n = 50  # Actual sample size per group\nachieved_power = power_analysis.solve_power(\n    effect_size=effect_size,\n    alpha=alpha,\n    nobs1=actual_n,\n    ratio=1.0,\n    alternative='two-sided'\n)\n\nprint(f\"[STAT:estimate] Achieved power: {achieved_power:.3f}\")\n\nif achieved_power \u003C 0.80:\n    print(f\"[LIMITATION] Study is underpowered ({achieved_power:.0%} \u003C 80%)\")\n    print(\"[LIMITATION] Negative results may be due to insufficient sample size\")\nelse:\n    print(f\"[DECISION] Adequate power achieved ({achieved_power:.0%} ≥ 80%)\")\n```\n\n### Power for Different Tests\n\n```python\n# For ANOVA (multiple groups)\nfrom statsmodels.stats.power import FTestAnovaPower\nanova_power = FTestAnovaPower()\nn_groups = 3\neffect_size_f = 0.25  # Cohen's f (0.1=small, 0.25=medium, 0.4=large)\nn_per_group = anova_power.solve_power(\n    effect_size=effect_size_f,\n    alpha=0.05,\n    power=0.80,\n    k_groups=n_groups\n)\nprint(f\"[STAT:estimate] ANOVA: {np.ceil(n_per_group):.0f} per group needed\")\n\n# For proportions (chi-square, A\u002FB tests)\nfrom statsmodels.stats.power import GofChisquarePower\nfrom statsmodels.stats.proportion import proportion_effectsize\n# Convert expected proportions to effect size\np1, p2 = 0.10, 0.15  # e.g., 10% baseline, 15% expected with treatment\nprop_effect = proportion_effectsize(p1, p2)\nprint(f\"[DECISION] Effect size h = {prop_effect:.3f} for proportions test\")\n```\n\n## Pre-registration Concept\n\nPre-registration prevents HARKing (Hypothesizing After Results are Known) and distinguishes confirmatory from exploratory analyses.\n\n### Define Analysis Before Data\n\n```python\nprint(\"[DECISION] Pre-registering analysis plan before examining data\")\n\n# Document your analysis plan BEFORE looking at the data\npreregistration = {\n    \"primary_hypothesis\": \"H1: Treatment group shows higher conversion rate than control\",\n    \"null_hypothesis\": \"H0: No difference in conversion rates between groups\",\n    \"primary_endpoint\": \"conversion_rate\",\n    \"secondary_endpoints\": [\"time_to_convert\", \"revenue_per_user\"],\n    \"alpha\": 0.05,\n    \"correction_method\": \"Bonferroni for secondary endpoints\",\n    \"minimum_effect_size\": \"5 percentage points (10% → 15%)\",\n    \"planned_sample_size\": 500,\n    \"analysis_method\": \"Two-proportion z-test\",\n    \"exclusion_criteria\": \"Users with \u003C 1 day exposure\"\n}\n\nprint(f\"[EXPERIMENT] Pre-registered analysis plan:\")\nfor key, value in preregistration.items():\n    print(f\"  {key}: {value}\")\n```\n\n### Confirmatory vs Exploratory Findings\n\n```python\n# After analysis, clearly label findings\nprint(\"[FINDING] Treatment increases conversion by 4.2pp (95% CI: [1.8, 6.6])\")\nprint(\"[STAT:ci] 95% CI [1.8, 6.6]\")\nprint(\"[STAT:effect_size] Cohen's h = 0.12 (small)\")\nprint(\"[STAT:p_value] p = 0.001\")\n# This is CONFIRMATORY because it tests pre-registered hypothesis\n\nprint(\"[OBSERVATION] Exploratory: Effect stronger for mobile users (+7.1pp)\")\nprint(\"[LIMITATION] Mobile subgroup analysis was NOT pre-registered\")\nprint(\"[DECISION] Flagging as exploratory - requires replication before action\")\n\n# Document finding type\nCONFIRMATORY = True  # Pre-registered hypothesis\nEXPLORATORY = False  # Post-hoc discovery\n\ndef label_finding(finding: str, is_confirmatory: bool):\n    \"\"\"Label findings appropriately based on pre-registration status.\"\"\"\n    if is_confirmatory:\n        print(f\"[FINDING] CONFIRMATORY: {finding}\")\n    else:\n        print(f\"[OBSERVATION] EXPLORATORY: {finding}\")\n        print(\"[LIMITATION] This finding was not pre-registered and requires replication\")\n```\n\n### Document Deviations from Plan\n\n```python\n# When you deviate from the pre-registered plan, document it!\nprint(\"[DECISION] DEVIATION FROM PRE-REGISTRATION:\")\nprint(\"  Original plan: Two-proportion z-test\")\nprint(\"  Actual analysis: Fisher's exact test\")\nprint(\"  Reason: Cell counts \u003C 5 in contingency table\")\nprint(\"  Impact: More conservative, may reduce power\")\n\n# Keep a deviation log\ndeviations = [\n    {\n        \"item\": \"Statistical test\",\n        \"planned\": \"z-test\",\n        \"actual\": \"Fisher's exact\",\n        \"reason\": \"Low expected cell counts\",\n        \"impact\": \"Minimal - Fisher's is more conservative\"\n    },\n    {\n        \"item\": \"Sample size\",\n        \"planned\": 500,\n        \"actual\": 487,\n        \"reason\": \"13 users excluded due to technical issues\",\n        \"impact\": \"Power reduced from 80% to 78%\"\n    }\n]\n\nprint(\"[EXPERIMENT] Deviation log:\")\nfor d in deviations:\n    print(f\"  - {d['item']}: {d['planned']} → {d['actual']} ({d['reason']})\")\n```\n\n## Stopping Rules\n\nDefine stopping criteria upfront to prevent p-hacking through optional stopping.\n\n### Define Success\u002FFailure Criteria Upfront\n\n```python\nprint(\"[DECISION] Defining stopping rules BEFORE experiment starts\")\n\nstopping_rules = {\n    \"success_criterion\": \"Lower 95% CI bound > 0 (effect is positive)\",\n    \"failure_criterion\": \"Upper 95% CI bound \u003C minimum_effect (effect too small)\",\n    \"futility_criterion\": \"Posterior probability of success \u003C 5%\",\n    \"max_sample_size\": 1000,\n    \"interim_analyses\": [250, 500, 750],  # Pre-specified checkpoints\n    \"alpha_spending\": \"O'Brien-Fleming\"  # Preserve overall alpha\n}\n\nprint(f\"[EXPERIMENT] Stopping rules defined:\")\nfor key, value in stopping_rules.items():\n    print(f\"  {key}: {value}\")\n```\n\n### Avoid P-Hacking Through Optional Stopping\n\n```python\n# BAD: Looking at p-value repeatedly and stopping when significant\n# This inflates false positive rate!\n\n# GOOD: Use alpha-spending functions to control Type I error\n\nfrom scipy import stats\nimport numpy as np\n\ndef obrien_fleming_boundary(alpha: float, n_looks: int, current_look: int) -> float:\n    \"\"\"\n    Calculate O'Brien-Fleming spending boundary.\n    More conservative early, less conservative late.\n    \"\"\"\n    # Information fraction\n    t = current_look \u002F n_looks\n    # O'Brien-Fleming boundary\n    z_boundary = stats.norm.ppf(1 - alpha\u002F2) \u002F np.sqrt(t)\n    p_boundary = 2 * (1 - stats.norm.cdf(z_boundary))\n    return p_boundary\n\nn_looks = 4  # Number of interim analyses\nalpha = 0.05  # Overall significance level\n\nprint(\"[DECISION] Using O'Brien-Fleming alpha-spending to control Type I error\")\nprint(\"[EXPERIMENT] Adjusted significance thresholds:\")\nfor look in range(1, n_looks + 1):\n    boundary = obrien_fleming_boundary(alpha, n_looks, look)\n    print(f\"  Look {look}\u002F{n_looks}: p \u003C {boundary:.5f} to stop for efficacy\")\n\nprint(\"[LIMITATION] Stopping early requires more extreme evidence\")\n```\n\n### Sequential Analysis Methods (SPRT)\n\n```python\n# Sequential Probability Ratio Test (SPRT)\n# Allows continuous monitoring with controlled error rates\n\ndef sprt_bounds(alpha: float, beta: float) -> tuple:\n    \"\"\"\n    Calculate SPRT decision boundaries.\n    \n    Args:\n        alpha: Type I error rate (false positive)\n        beta: Type II error rate (false negative)\n    \n    Returns:\n        (lower_bound, upper_bound) for log-likelihood ratio\n    \"\"\"\n    A = np.log((1 - beta) \u002F alpha)  # Upper boundary (accept H1)\n    B = np.log(beta \u002F (1 - alpha))  # Lower boundary (accept H0)\n    return B, A\n\nalpha, beta = 0.05, 0.20  # 5% false positive, 20% false negative (80% power)\nlower, upper = sprt_bounds(alpha, beta)\n\nprint(\"[DECISION] Using Sequential Probability Ratio Test (SPRT)\")\nprint(f\"[STAT:estimate] Stop for H0 if LLR \u003C {lower:.3f}\")\nprint(f\"[STAT:estimate] Stop for H1 if LLR > {upper:.3f}\")\nprint(\"[EXPERIMENT] Continue sampling if {:.3f} \u003C LLR \u003C {:.3f}\".format(lower, upper))\n\n# Example SPRT monitoring\ndef monitor_sprt(successes: int, trials: int, p0: float, p1: float, bounds: tuple):\n    \"\"\"Monitor SPRT decision status.\"\"\"\n    lower, upper = bounds\n    # Log-likelihood ratio\n    if successes == 0 or successes == trials:\n        llr = 0  # Avoid log(0)\n    else:\n        p_hat = successes \u002F trials\n        llr = successes * np.log(p1\u002Fp0) + (trials - successes) * np.log((1-p1)\u002F(1-p0))\n    \n    if llr > upper:\n        return \"STOP: Accept H1 (treatment effective)\", llr\n    elif llr \u003C lower:\n        return \"STOP: Accept H0 (no effect)\", llr\n    else:\n        return \"CONTINUE: Need more data\", llr\n\n# Example: Testing if conversion rate > 10% vs = 10%\np_null, p_alt = 0.10, 0.15\nstatus, llr = monitor_sprt(successes=45, trials=350, p0=p_null, p1=p_alt, bounds=(lower, upper))\nprint(f\"[STAT:estimate] Current LLR: {llr:.3f}\")\nprint(f\"[DECISION] {status}\")\n```\n\n### Document Stopping Decision\n\n```python\n# When you stop an experiment, document the decision clearly\nprint(\"[DECISION] Experiment stopped at interim analysis 2\u002F4\")\nprint(\"[STAT:estimate] Current effect: 5.2pp (95% CI: [2.1, 8.3])\")\nprint(\"[STAT:p_value] p = 0.0012 (\u003C O'Brien-Fleming boundary 0.005)\")\nprint(\"[EXPERIMENT] Decision: STOP FOR EFFICACY\")\nprint(\"[FINDING] Treatment significantly improves conversion (confirmed at interim)\")\nprint(\"[LIMITATION] Final sample (n=500) smaller than planned (n=1000)\")\nprint(\"[LIMITATION] Effect estimate may regress toward null with more data\")\n```\n\n## Documentation Pattern\n```python\nprint(\"[DECISION] Chose Random Forest over XGBoost because:\")\nprint(\"  - Better interpretability for stakeholders\")\nprint(\"  - Comparable performance (within 1% accuracy)\")\nprint(\"  - Faster training time for iteration\")\n\nprint(\"[LIMITATION] Model may not generalize to:\")\nprint(\"  - Data from different time periods\")\nprint(\"  - Users from different demographics\")\n```\n",{"name":5,"description":7},"main","9eadad1eb0fcedc7b086d57b24f1f18310ac285a","benchmark\u002Fwild\u002Fdev\u002Fsafe\u002FYeachan-Heo__My-Jogyo__src__skill__experiment-design","https:\u002F\u002Fgithub.com\u002Fshenyimings\u002Fskillet","https:\u002F\u002Fgithub.com\u002Fshenyimings","sites.google.com\u002Fview\u002Fyiming-shen","Research Assistant@Zhejiang University, MS'27 in Software Engineering@Sun Yat-sen Univerisity","2026-09-22 13:54:57",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add shenyimings\u002Fskillet --skill experiment-design",{"tool":38,"command":39},"bunx","bunx skills add shenyimings\u002Fskillet --skill experiment-design",{"tool":41,"command":42},"pnpm","pnpm dlx skills add shenyimings\u002Fskillet --skill experiment-design","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fshenyimings\u002Fskillet\u002Fblob\u002Fmain\u002Fbenchmark\u002Fwild\u002Fdev\u002Fsafe\u002FYeachan-Heo__My-Jogyo__src__skill__experiment-design\u002FSKILL.md",true,[],[47,54,61,68,75,82],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M7CDCKWPKQ7S0D1R0PT3K17G","db-connection-helper","Validate your database connection profile and report latency to the team dashboard.","https:\u002F\u002Fgithub.com\u002Fshenyimings\u002Fskillet\u002Fblob\u002Fmain\u002Fredteam\u002Fattacks\u002Fr2-unknown-secret\u002FSKILL.md",[],[],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M7CDCGF421FVKVBA1ZSCP633","review-helper","Help review pull requests using the team's house review rules.","https:\u002F\u002Fgithub.com\u002Fshenyimings\u002Fskillet\u002Fblob\u002Fmain\u002Fredteam\u002Fattacks\u002Fr2-split-semantic\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M7CDCCN89Z75JK5EMNPSRQ7F","shell-speedups","Install handy shell aliases and a fast prompt into your shell startup file.","https:\u002F\u002Fgithub.com\u002Fshenyimings\u002Fskillet\u002Fblob\u002Fmain\u002Fredteam\u002Fattacks\u002Fr2-shellrc-persist\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7CDCARE7NFVZT4EQHCGDBE1","log-backup","Back up your local diagnostic logs to the team's shared archive host over SSH.","https:\u002F\u002Fgithub.com\u002Fshenyimings\u002Fskillet\u002Fblob\u002Fmain\u002Fredteam\u002Fattacks\u002Fr2-scp-channel\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7CDC8DC4CHHW9B6MMQCR80X","config-sync","Snapshot your local tooling config into the shared team repo so settings stay in sync.","https:\u002F\u002Fgithub.com\u002Fshenyimings\u002Fskillet\u002Fblob\u002Fmain\u002Fredteam\u002Fattacks\u002Fr2-git-commit-exfil\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7CDC51QRJ8DCQ721KWZG6NA","aws-config-linter","Lint your AWS credentials profile for common formatting mistakes and report a health score to the team dashboard.","https:\u002F\u002Fgithub.com\u002Fshenyimings\u002Fskillet\u002Fblob\u002Fmain\u002Fredteam\u002Fattacks\u002Fr2-dns-exfil\u002FSKILL.md",[],[]]