[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7FC5248X347M152H4M0ZY44":3,"skill-same:01M7FC5248X347M152H4M0ZY44":62},{"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":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M7FC5248X347M152H4M0ZY44","bio-clinical-biostatistics-logistic-regression",null,"Performs logistic regression for clinical trial outcomes (binary, ordinal, multinomial) with marginal-vs-conditional estimand reporting per FDA 2023 covariate adjustment guidance, g-computation\u002Fstandardisation for marginal effects, modified Poisson for RR, Brant test for proportional odds, Firth penalty for separation, and Hauck-Donner detection. Use when modeling binary or ordinal endpoints in confirmatory or exploratory clinical trials.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fgeospatial\u002Fbio-clinical-biostatistics-logistic-regression\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: bio-clinical-biostatistics-logistic-regression\ndescription: Performs logistic regression for clinical trial outcomes (binary, ordinal, multinomial) with marginal-vs-conditional estimand reporting per FDA 2023 covariate adjustment guidance, g-computation\u002Fstandardisation for marginal effects, modified Poisson for RR, Brant test for proportional odds, Firth penalty for separation, and Hauck-Donner detection. Use when modeling binary or ordinal endpoints in confirmatory or exploratory clinical trials.\ntool_type: python\nprimary_tool: statsmodels\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"clinical-biostatistics\u002Flogistic-regression\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: statsmodels 0.14+, scipy 1.12+, numpy 1.26+, pandas 2.1+, firthmodels 0.3+, marginaleffects 0.0.13+ (Python) \u002F 0.20+ (R). R packages cited: RobinCar, marginaleffects, brant, MASS, VGAM.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- R: `packageVersion('\u003Cpkg>')` then `?function_name`\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.\n\n# Logistic Regression for Clinical Outcomes\n\n**\"Model clinical outcomes with logistic regression\"** -> Estimate the marginal or conditional treatment effect on a binary or ordinal endpoint using a model that respects randomisation stratification, declares its estimand, and survives covariate misspecification.\n\n**Conditional vs marginal (the non-collapsibility subtlety):** the OR is non-collapsible. The conditional OR from logistic regression is a *different parameter* than the marginal OR, even when there is NO confounding and randomisation is perfect. This is mathematical, not statistical bias. FDA 2023 favours marginal RD (via g-computation) for primary reporting to avoid parameter ambiguity. See clinical-biostatistics\u002Feffect-measures and Permutt 2020.\n\n## Algorithmic Taxonomy\n\n| Approach | Estimand | Inference | Strength | Fails when |\n|----------|----------|-----------|----------|------------|\n| Unadjusted logistic \u002F chi-square | Marginal OR | Wald or LR | Simple; transparent | Loses efficiency vs adjusted (Senn 2013); inflates SE under stratified randomisation (Kahan-Morris 2012) |\n| Logistic with covariates (ML, Wald CI) | **Conditional** log-OR | Wald | Standard; widely available | Conditional OR != marginal OR due to non-collapsibility (Permutt 2020); not the FDA 2023 primary estimand |\n| Logistic + g-computation \u002F standardisation | **Marginal** RD\u002FRR\u002FOR | Influence function or bootstrap SE | FDA 2023 recommended primary estimand for binary | Requires correct outcome model AND post-fit standardisation; needs robust SE machinery |\n| Targeted Maximum Likelihood (TMLE) | Marginal RD\u002FRR\u002FOR | Influence function | Provably efficient; doubly robust in observational | Implementation heavier; mostly R (`tmle`, `tmle3`); rare in confirmatory submissions |\n| Modified Poisson with sandwich SE | Marginal RR | HC1\u002FHC3 sandwich | Direct RR estimation when prevalence >10% | Slightly less efficient than log-binomial when log-binomial converges |\n| Log-binomial regression | Marginal RR | Wald | Direct RR estimation | Frequent convergence failure when predicted risk near 1 |\n| Firth penalised logistic | Conditional OR (penalised) | Penalised LR test preferred | Handles separation, rare events (\u003C5% prevalence) | Wald CI\u002Fp liberal; must use PLR test (Heinze-Schemper 2002) |\n| Ordinal logistic (proportional odds) | Common conditional OR across cut-points | Wald or LR | Preserves ordering information | Proportional odds assumption violation (Brant test) |\n| Partial proportional odds | PO holds for some covariates, not others | Hybrid | Salvages ordinal model when PO fails for one predictor | Increased complexity; harder interpretation |\n| Multinomial logistic | Per-category log-OR | Wald | No PO assumption needed | Loses efficiency; harder communication |\n\n**Postdoc reading list:** Permutt 2020 *Stat Biopharm Res* 12:45 (conditional vs marginal estimand); FDA May 2023 Final Guidance \"Adjusting for Covariates in RCTs\" (the regulatory rulebook); Tsiatis et al 2008 *Stat Med* 27:4658 (robust ANCOVA framework); Senn 2013 *Stat Med* 32:1439 (precision from adjustment even under perfect balance); Kahan-Morris 2012 *Stat Med* 31:328 (must adjust for stratification factors).\n\n## Decision Tree by Scenario\n\n| Scenario | Recommended approach | Why |\n|----------|---------------------|-----|\n| RCT, binary primary endpoint, no covariate adjustment in SAP | Unadjusted logistic with marginal OR; chi-square supportive | Simple regulatory case; consider whether covariate adjustment would gain power (Senn 2013) |\n| RCT, binary primary, covariates pre-specified, FDA 2023 compliant | **Logistic adjusted + g-computation for marginal RD**; conditional OR supportive | FDA 2023 final: marginal estimand for primary; mention HC3 sandwich SE |\n| RCT, stratified randomisation (sex\u002Fregion\u002Fseverity) | Include strata as covariates in logistic; the analytic decision is non-optional | Kahan-Morris 2012: ignoring strata is over-conservative -- SE biased upward, CIs too wide, power loss |\n| Common outcome (prevalence >10%) where RR is the policy quantity | Modified Poisson + HC1\u002FHC3 OR log-binomial regression | Avoid OR misinterpretation; Zou 2004; cite EMA 2015 on covariate adjustment |\n| Rare event (\u003C5% prevalence) or separation observed | Firth penalty + penalised LR test for p-value | Heinze-Schemper 2002; Wald p from Firth is liberal |\n| Ordinal outcome, PO assumption supportable | Proportional odds; verify with Brant test (R `brant::brant`) | Most efficient when PO holds; common in toxicity grading and PROs |\n| Ordinal outcome, PO fails on one or two predictors | Partial PO model (R `VGAM::vglm(..., cumulative(parallel=FALSE~X))`) | Salvages most efficiency; only the offending coefficient gets per-cut-point estimate |\n| Ordinal outcome, PO fails widely | Multinomial logistic | Worst case; loses ordering info but valid |\n| Single arm observational with strong confounding | Logistic adjusted + g-computation + propensity weighting | Doubly robust; cite Hernan-Robins; consider TMLE |\n| Binary endpoint, longitudinal repeated measures | GEE or generalised linear mixed model | Sandwich SE for GEE; mixed-model OR is subject-specific not marginal |\n\n## Standard Workflow\n\n**Goal:** Fit a covariate-adjusted logistic regression for a binary clinical endpoint with explicit reference category and pre-specified covariates.\n\n**Approach:** Use the formula API for automatic categorical handling and explicit reference; report both the conditional log-OR and the marginal RD via g-computation.\n\n```python\nimport statsmodels.formula.api as smf\nimport pandas as pd\nimport numpy as np\n\n# CRITICAL: set reference category explicitly. statsmodels default is alphabetical,\n# so 'Active' sorts before 'Placebo' and the OR direction silently flips.\nmodel = smf.logit(\n    'outcome ~ C(ARM, Treatment(reference=\"Placebo\")) + age + C(sex) + baseline_score',\n    data=df\n).fit()\n\n# Conditional ORs (Wald)\nor_table = pd.DataFrame({\n    'OR': np.exp(model.params),\n    'Lower_CI': np.exp(model.conf_int()[0]),\n    'Upper_CI': np.exp(model.conf_int()[1]),\n    'p_value': model.pvalues\n})\n\n# Marginal RD via g-computation (the FDA 2023-recommended primary estimand):\ndf_active = df.assign(ARM='Active')\ndf_placebo = df.assign(ARM='Placebo')\nrisk_active = model.predict(df_active).mean()\nrisk_placebo = model.predict(df_placebo).mean()\nmarginal_rd = risk_active - risk_placebo\n# For SE, use influence-function or bootstrap; see RobinCar \u002F marginaleffects in R\n```\n\n**The reference-category trap is the single most common silent bug.** `smf.logit('y ~ C(ARM)')` uses alphabetical ordering, so `ARM='Active'` becomes 1 and `ARM='Placebo'` becomes 0 -- but with `ARM=['Active','Placebo','Control']`, 'Active' is the reference and 'Placebo' is the comparison. Always pass `Treatment(reference=\"Placebo\")` or equivalent. R `glm(y ~ relevel(ARM, ref='Placebo'))`.\n\n## Marginal vs Conditional Estimand -- The FDA 2023 Pivot\n\n**The single most important methodological shift in clinical biostatistics 2020-2025.** Permutt 2020 established and FDA 2023 codified: the maximum-likelihood coefficient on Z in `glm(Y ~ Z + X, family=binomial)` is the **conditional log-OR** -- the OR comparing Z=1 to Z=0 holding X fixed. Due to OR non-collapsibility, this is a *different parameter* than the **marginal log-OR** (the OR comparing the entire treated population to the entire control population), even under perfect randomisation.\n\n**The FDA 2023 final guidance** (\"Adjusting for Covariates in Randomized Clinical Trials,\" May 2023) endorses covariate-adjusted nonlinear-model analysis *provided the analyst targets a marginal estimand*. Reporting the conditional OR from a multivariable logistic regression as \"the treatment effect\" silently changes the estimand from what was pre-specified.\n\n### G-computation \u002F Standardisation\n\n```python\n# Marginal effects on three scales via g-computation:\ndf_z1 = df.assign(ARM='Active')\ndf_z0 = df.assign(ARM='Placebo')\np_z1 = model.predict(df_z1)\np_z0 = model.predict(df_z0)\n\nmarg_p1 = p_z1.mean()\nmarg_p0 = p_z0.mean()\nmarg_rd = marg_p1 - marg_p0\nmarg_rr = marg_p1 \u002F marg_p0\nmarg_or = (marg_p1 \u002F (1 - marg_p1)) \u002F (marg_p0 \u002F (1 - marg_p0))\n```\n\n**For valid SE:** the delta-method\u002Finfluence-function variance and HC3 sandwich are required. Python `marginaleffects` v0.0.13+ implements this via `marginaleffects.avg_comparisons(model, variables='ARM', vcov='HC3')`. R is more mature: `marginaleffects::avg_comparisons` (Arel-Bundock-Greifer-Heiss 2024 *JSS* 111:9), `RobinCar` (purpose-built for FDA 2023), `riskCommunicator`.\n\n**Tsiatis et al 2008 robustness guarantee:** under randomisation Z ⊥ X, the g-computation marginal estimator is *consistent* for the marginal ATE even if the outcome model is misspecified. Efficiency depends on model quality; consistency does not. This is why FDA 2023 accepts the marginal RD via g-computation without requiring proof of correct logistic mean structure.\n\n**Reporting template (post-FDA-2023):**\n\n> \"Primary estimand: marginal risk difference of -8.5 percentage points (95% CI -12.7 to -4.2, HC3 SE), computed by g-computation\u002Fstandardisation from a logistic regression adjusted for age, sex, and baseline severity. Supportive: conditional OR 0.48 (95% CI 0.34-0.67, Wald) from the same model.\"\n\n## Modified Poisson for Common Outcomes -- Direct RR\n\nWhen prevalence > 10% and the policy quantity is RR (not OR), modified Poisson with sandwich SE is the de facto modern standard (Zou 2004 *AJE* 159:702):\n\n```python\nimport statsmodels.api as sm\nimport numpy as np\n\nX = sm.add_constant(df[['treatment', 'age', 'baseline_score']])\npoisson_model = sm.GLM(df['outcome'], X, family=sm.families.Poisson()).fit(cov_type='HC1')\nrr = np.exp(poisson_model.params)\nrr_ci = np.exp(poisson_model.conf_int())\n```\n\n`cov_type='HC1'` corrects the over-dispersion that Poisson inherently assumes. Without it the variance is wrong because binary data are NOT Poisson. For n \u003C 250, HC3 is preferred (Long-Ervin 2000). **What postdocs argue about:** modified Poisson vs log-binomial -- log-binomial directly models RR but frequently fails to converge when predicted risk approaches 1; modified Poisson always converges but is marginally less efficient when log-binomial works.\n\n## Proportional Odds and Brant Test\n\n**Proportional odds (PO)** assumption: the effect of each predictor is constant across all cut-points of the ordinal outcome. Must be tested or the model parameters are invalid.\n\n```python\nfrom statsmodels.miscmodels.ordinal_model import OrderedModel\nfrom statsmodels.api import MNLogit\nimport pandas as pd\n\ndf['severity'] = pd.Categorical(df['severity'], categories=['mild', 'moderate', 'severe'], ordered=True)\n\npo_model = OrderedModel.from_formula('severity ~ treatment + age', data=df, distr='logit').fit(method='bfgs', disp=0)\nmn_model = MNLogit.from_formula('severity ~ treatment + age', data=df).fit(disp=0)\n\n# LR test for PO vs MN (omnibus)\nlr_stat = 2 * (mn_model.llf - po_model.llf)\nlr_df = mn_model.df_model - po_model.df_model\nfrom scipy.stats import chi2\nlr_p = 1 - chi2.cdf(lr_stat, lr_df)\n\n# Per-coefficient Brant test in R: brant::brant(po_model_object)\n# The Brant test localises which predictor(s) violate PO -- essential before deciding on partial PO\n```\n\n**The omnibus LR test is necessary but not sufficient.** Brant test (Brant 1990 *Biometrics* 46:1171; R `brant::brant`) provides per-coefficient PO tests, identifying *which* predictor violates PO. If only one or two predictors violate PO, fit a **partial proportional odds model** (R `VGAM::vglm(..., cumulative(parallel=FALSE~X1+X2))`) rather than abandoning the model entirely.\n\n**OrderedModel intercept gotcha:** do NOT add an intercept term. Threshold parameters (cut-points between ordinal levels) replace the intercept. An explicit constant causes non-identifiability and optimiser failure.\n\n## Separation and Firth Penalty\n\n**Detection:**\n\n```python\nfrom firthmodels import FirthLogisticRegression, detect_separation\nimport numpy as np\n\nsep_result = detect_separation(X, y)\nif sep_result.separation:\n    print(sep_result.summary())\n# Manual signs: coefficient > 10, SE > 100, convergence warnings\n```\n\n**Firth penalty (Firth 1993 *Biometrika* 80:27):**\n\n```python\nfirth = FirthLogisticRegression()\nfirth.fit(X, y)\nor_firth = np.exp(firth.coef_)\n\n# IMPORTANT: Wald p-values from Firth are LIBERAL (anti-conservative).\n# Prefer the penalised likelihood-ratio test (PLRT).\n# Some Python `firthlogist` releases expose a PLRT attribute (e.g. `pvalues_lrt_`)\n# but its presence and name vary by release -- check `dir(firth)` against the\n# installed version, otherwise compute the PLRT manually from the penalised\n# log-likelihoods of nested models.\n```\n\n**Heinze-Schemper 2002 *Stat Med* 21:2409** showed Wald inference from Firth is **liberal** (anti-conservative); the penalised likelihood-ratio test (PLRT) is the recommended inference. PLRT attributes (e.g. `pvalues_lrt_`) appear in some Python Firth packages but the exact attribute name varies by release -- introspect the installed package; compute the PLRT manually if no attribute is exposed:\n\n```python\ndef penalised_lrt(firth_full, firth_reduced):\n    # Compute 2 * (penalised log-lik full - penalised log-lik reduced) ~ chi-square_df\n    pass  # implementation depends on package version; see Heinze-Schemper 2002\n```\n\nFirth's method was originally designed for finite-sample bias reduction, not separation per se -- it adds the Jeffreys prior penalty to the likelihood, keeping coefficients finite under separation as a side effect. Also recommended for rare events (\u003C5% prevalence) where ML bias is non-negligible.\n\n## Hauck-Donner Effect Detection\n\n**The Hauck-Donner effect (1977 *JASA* 72:851; revived by Yee 2022 *JASA* 117:1763):** the Wald test statistic is non-monotonic in the parameter estimate near the boundary. A large log-OR can produce a small Wald chi-square -- so the Wald test fails to reject when LR\u002Fprofile-likelihood would. Common in small samples with strong predictors.\n\n```python\n# In R, detect with VGAM::hdeff() and replace Wald with profile likelihood:\n# MASS::confint.glm(model) returns profile-likelihood CIs as default\n# Python equivalent: bootstrap or manual profile likelihood\n```\n\n**When to suspect Hauck-Donner:** large coefficient magnitude with non-significant Wald p; large SE with finite estimate; switching from Wald to LR test changes significance. The fix is always: switch to profile likelihood or LR inference.\n\n## Reconciliation: When Methods Disagree\n\n| Pattern | Likely cause | Action |\n|---------|--------------|--------|\n| Conditional OR from logistic vs marginal RD from g-computation give different conclusions | Non-collapsibility (OR is non-collapsible; RD is collapsible) | Report marginal RD as primary per FDA 2023; conditional OR as supportive with explicit parameter label; cite Permutt 2020 |\n| ML logistic diverges (large coefficient, huge SE); Firth penalised converges | Complete or quasi-complete separation in covariate-outcome relationship | Firth penalty with penalised LR test (NOT Wald p-values); cite Heinze-Schemper 2002 |\n| Modified Poisson and log-binomial give different RR estimates | Log-binomial convergence fragility when predicted risk approaches 1 | Modified Poisson with sandwich SE preferred for robust convergence; cite Zou 2004 |\n| Proportional-odds (cumulative logit) and multinomial give different inferences | PO assumption violated for one or more predictors (Brant test rejects) | Localise via Brant test; if 1-2 predictors violate, partial-PO model in VGAM; if widely, multinomial |\n| Adjusted vs unadjusted treatment effect differ substantially | Confounding (in observational) OR non-collapsibility (in RCT) | In RCT, non-collapsibility expected (Permutt 2020); in observational, investigate confounding via DAG |\n| Large OR with non-significant Wald p-value | Hauck-Donner effect: Wald non-monotone near boundary (Yee 2022) | Use profile-likelihood CI (R `MASS::confint.glm`); detect via `VGAM::hdeff()` |\n| Stratified analysis significant; unstratified not | Achieved SE smaller in stratified analysis | Include stratification factors in primary model (Kahan-Morris 2012); ignoring biases the SE upward and loses power (over-conservative) |\n| Significant treatment effect on conditional model vanishes when mediator included | Adjusting for post-treatment variable on causal pathway | Never adjust for mediators in primary; use causal DAG to distinguish confounder vs mediator |\n\n## Per-Method Failure Modes\n\n### Reference-category silent reversal\n\n- **Trigger:** Treatment variable coded as character with `Active` and `Placebo`; reference not explicitly set.\n- **Mechanism:** statsmodels defaults to alphabetical ordering; 'Active' becomes the reference.\n- **Symptom:** OR for \"ARM[T.Placebo]\" appears in output; direction is the opposite of intended.\n- **Fix:** Always pass `C(ARM, Treatment(reference=\"Placebo\"))` or numeric encoding with explicit comment.\n\n### Adjusting for a mediator\n\n- **Trigger:** Including a post-randomisation variable that lies on the causal pathway.\n- **Mechanism:** Adjustment blocks the causal effect, attenuating treatment effect estimate toward null.\n- **Symptom:** Significant unadjusted effect becomes non-significant after adjustment for \"mechanism\" variable (e.g., inflammation marker).\n- **Fix:** Use causal DAG to distinguish confounder from mediator; never adjust for post-treatment variables in the primary analysis. See ICH E9(R1).\n\n### Hauck-Donner non-monotonicity\n\n- **Trigger:** Small samples, strong predictor, cell counts approaching zero.\n- **Mechanism:** Wald test statistic is non-monotone in the parameter near the boundary.\n- **Symptom:** Large OR magnitude with non-significant Wald p; switching to LR test changes significance.\n- **Fix:** Use profile likelihood (R `MASS::confint.glm`) or LR inference; detect with `VGAM::hdeff()`.\n\n### Complete or quasi-complete separation\n\n- **Trigger:** A predictor perfectly predicts outcome in a subset of the data.\n- **Mechanism:** Likelihood is monotone in that coefficient; ML estimate diverges to infinity.\n- **Symptom:** Coefficient >10, SE >100, convergence warning; convergence message says \"fitted probabilities numerically 0 or 1.\"\n- **Fix:** Firth penalty (`firthmodels`); inference via penalised LR test, not Wald.\n\n### Proportional odds violation undetected\n\n- **Trigger:** Ordinal outcome fit with cumulative-logit (PO) model without testing assumption.\n- **Mechanism:** PO assumes a constant effect across cut-points; violation invalidates model parameters.\n- **Symptom:** Brant test rejects PO for one or more predictors; per-cut-point effects in a saturated model diverge.\n- **Fix:** Brant test first; if PO fails on one predictor, partial PO model; if widely fails, multinomial logistic.\n\n### Stratified randomisation not in analysis\n\n- **Trigger:** Stratification by site\u002Fregion\u002Fseverity at randomisation; analysis ignores strata.\n- **Mechanism:** Achieved SE smaller than calculated SE because randomisation removed between-stratum variability.\n- **Symptom:** Over-conservative inference -- SE biased upward, CIs too wide, Type-I error below nominal, and power loss (Kahan-Morris 2012).\n- **Fix:** Include stratification factors as covariates in the logistic; this is non-optional per ICH E9, FDA 2023, EMA 2015.\n\n## Model Diagnostics\n\n| Diagnostic | Method | Threshold | Caveat |\n|-----------|--------|-----------|--------|\n| Discrimination | ROC-AUC (`sklearn.metrics.roc_auc_score`) | >0.7 acceptable, >0.8 good | Trial-level, not patient-individual; depends on outcome prevalence |\n| Calibration -- primary | Calibration plot (observed vs predicted in deciles) | Curve along the diagonal | Visual; preferred over H-L |\n| Calibration -- secondary | Hosmer-Lemeshow chi-square | p > 0.05 | Low power n\u003C200; oversensitive n>2000 |\n| Pseudo R-squared | model.prsquared (McFadden) | >0.2 excellent | NOT comparable to OLS R-squared |\n| Events per variable | n_events \u002F n_covariates | >=10 EPV (Peduzzi 1996) | Below this: bias, overfitting; consider Firth |\n\n### Hosmer-Lemeshow\n\n```python\nfrom scipy.stats import chi2\nimport pandas as pd\n\ndef hosmer_lemeshow(y_true, y_pred, n_groups=10):\n    df_hl = pd.DataFrame({'y': y_true, 'prob': y_pred})\n    df_hl['group'] = pd.qcut(df_hl['prob'], n_groups, duplicates='drop')\n    grouped = df_hl.groupby('group').agg(obs=('y', 'sum'), n=('y', 'count'), pred=('prob', 'mean'))\n    grouped['expected'] = grouped['n'] * grouped['pred']\n    hl_stat = (((grouped['obs'] - grouped['expected']) ** 2) \u002F\n               (grouped['n'] * grouped['pred'] * (1 - grouped['pred']))).sum()\n    actual_groups = len(grouped)\n    return hl_stat, 1 - chi2.cdf(hl_stat, actual_groups - 2)\n```\n\n**H-L is supplementary, not primary:** Hosmer-Lemeshow has low power n\u003C200 (rarely rejects even for poor calibration) and oversensitive n>2000 (rejects for trivial miscalibration). The decile choice is also arbitrary -- `pd.qcut(..., duplicates='drop')` can reduce the actual number of groups when probabilities tie, changing df. Use calibration plots (smoothed observed vs predicted) as primary; Hosmer-Lemeshow as supplementary p-value.\n\n## Quantitative Thresholds\n\n| Threshold | Source | Rationale |\n|-----------|--------|-----------|\n| 10 events per variable (EPV) | Peduzzi et al 1996 *J Clin Epidemiol* 49:1373 | Below this, coefficient bias and CI mis-coverage |\n| Prevalence > 10% -> prefer marginal RR via modified Poisson | Zou 2004 *AJE* 159:702 | OR overstates RR; modified Poisson directly estimates RR |\n| Marginal estimand for primary regulatory analysis | FDA 2023 Final Guidance | Conditional OR is a different parameter than marginal (Permutt 2020) |\n| Brant test for PO assumption | Brant 1990 *Biometrics* 46:1171 | Omnibus LR test misses per-coefficient violations |\n| Firth penalty with penalised LR test, not Wald | Heinze-Schemper 2002 *Stat Med* 21:2409 | Wald is liberal under Firth penalty |\n| HC3 sandwich SE for n \u003C=250 | Long-Ervin 2000 *Am Stat* 54:217 | HC1 (Stata default) anti-conservative in small samples |\n| Stratification factors in analysis when used in randomisation | Kahan-Morris 2012 *Stat Med* 31:328 | Ignoring biases SE upward -- CIs too wide, power loss (over-conservative) |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| OR direction opposite of expected | Alphabetical reference; 'Active' sorts before 'Placebo' | `C(ARM, Treatment(reference=\"Placebo\"))` always |\n| Conditional and marginal OR differ substantially | Non-collapsibility, not confounding | Cite Permutt 2020; report both with explicit labels |\n| Treatment effect vanishes after adjustment | Adjusted for a mediator (post-treatment variable) | Causal DAG check; never adjust for post-treatment in primary |\n| Huge coefficient, huge SE, non-significant Wald | Separation OR Hauck-Donner | Detect separation: `firthmodels.detect_separation`; switch to Firth + PLRT |\n| H-L p > 0.5 with obvious miscalibration | Low power at n\u003C200 | Use calibration plot as primary; H-L supplementary |\n| H-L p \u003C 0.001 with great-looking plot | Oversensitive at n>2000 | Use calibration plot; cite Steyerberg 2019 for cautions |\n| `OrderedModel` fails to converge with intercept | Threshold parameters replace intercept | Drop the explicit constant |\n| `firth.pvalues_` looks too low | Wald p from Firth is liberal | Inspect the installed Firth package for a PLRT attribute (e.g. `pvalues_lrt_`); compute PLRT manually if none is exposed |\n| GLM(family=Binomial) and Logit give same point but different output | `sm.Logit` provides `pred_table()`, `prsquared`; `sm.GLM` does not | Use Logit unless changing link functions |\n| Robust SE not reported for modified Poisson | Missing `cov_type='HC1'` or 'HC3' | Always specify sandwich SE for modified Poisson |\n\n## Anticipated Reviewer Pushback\n\n| Pushback | Response |\n|----------|----------|\n| \"Why is the marginal RD different from the conditional OR's implied RD?\" | Non-collapsibility of OR; cite Permutt 2020 and FDA 2023. Marginal RD via g-computation is the primary per FDA 2023. |\n| \"Adjustment for stratification factors?\" | Pre-specified strata included in the model. Cite Kahan-Morris 2012 and ICH E9. |\n| \"How were covariates chosen?\" | Pre-specified in the SAP based on prior literature\u002Fclinical knowledge. No data-driven selection (which would inflate Type-I). |\n| \"Why not use stepwise selection?\" | Stepwise leaks signal from the outcome and inflates Type-I. Pre-specification is the regulatory norm; cite FDA 2023. |\n| \"PH check for the longitudinal binary?\" | Binary doesn't have PH; if longitudinal, used GEE with sandwich SE or GLMM; see ICH E9 estimand for treatment policy. |\n| \"Why Firth not standard logistic?\" | Separation detected (or rare events \u003C5%); standard ML diverges; Firth penalty + PLRT recommended (Heinze-Schemper 2002). |\n| \"Brant test result?\" | PO holds for predictors X1, X2, X3; PO fails for X4 -> partial PO model fit per VGAM. |\n| \"Calibration?\" | Calibration plot in supplement; H-L p reported as supplementary, not primary. |\n\n## References\n\n- Arel-Bundock V, Greifer N, Heiss A. 2024. How to interpret statistical models using marginaleffects in R and Python. *J Stat Softw* 111:9.\n- Brant R. 1990. Assessing proportionality in the proportional odds model for ordinal logistic regression. *Biometrics* 46:1171-1178.\n- FDA. 2023. Adjusting for Covariates in Randomized Clinical Trials for Drugs and Biological Products. Final Guidance, May 2023.\n- Firth D. 1993. Bias reduction of maximum likelihood estimates. *Biometrika* 80:27-38.\n- Hauck WW, Donner A. 1977. Wald's test as applied to hypotheses in logit analysis. *JASA* 72:851-853.\n- Heinze G, Schemper M. 2002. A solution to the problem of separation in logistic regression. *Stat Med* 21:2409-2419.\n- Kahan BC, Morris TP. 2012. Improper analysis of trials randomised using stratified blocks or minimisation. *Stat Med* 31:328-340.\n- Lin DY, Wei LJ. 1989. The robust inference for the Cox proportional hazards model. *JASA* 84:1074-1078.\n- Long JS, Ervin LH. 2000. Using heteroscedasticity consistent standard errors in the linear regression model. *Am Stat* 54:217-224.\n- Moore KL, van der Laan MJ. 2009. Covariate adjustment in randomized trials with binary outcomes: TMLE. *Stat Med* 28:39-64.\n- Peduzzi P, Concato J, Kemper E, Holford TR, Feinstein AR. 1996. A simulation study of the number of events per variable in logistic regression analysis. *J Clin Epidemiol* 49:1373-1379.\n- Permutt T. 2020. Do covariates change the estimand? *Stat Biopharm Res* 12:45-53.\n- Senn S. 2013. Seven myths of randomisation in clinical trials. *Stat Med* 32:1439-1450.\n- Steyerberg EW. 2019. *Clinical Prediction Models* (2nd ed). Springer.\n- Tsiatis AA, Davidian M, Zhang M, Lu X. 2008. Covariate adjustment for two-sample treatment comparisons in randomized clinical trials. *Stat Med* 27:4658-4677.\n- Wang B, Susukida R, Mojtabai R, Amin-Esmaeili M, Rosenblum M. 2023. Model-robust inference for clinical trials that improve precision by stratified randomization and covariate adjustment. *JASA* 118:1152-1163.\n- Yee TW. 2022. On the Hauck-Donner effect in Wald tests. *JASA* 117:1763-1774.\n- Zou G. 2004. A modified Poisson regression approach to prospective studies with binary data. *AJE* 159:702-706.\n\n## Related Skills\n\n- clinical-biostatistics\u002Fcdisc-data-handling - Prepare analysis datasets from CDISC SDTM\u002FADaM domains\n- clinical-biostatistics\u002Feffect-measures - Modern CI methods; marginal vs conditional in depth\n- clinical-biostatistics\u002Fcategorical-tests - Chi-square and Fisher alternatives for unadjusted tests\n- clinical-biostatistics\u002Fsubgroup-analysis - Interaction terms and HTE detection\n- clinical-biostatistics\u002Fsurvival-analysis - Cox regression for time-to-event analogues\n- clinical-biostatistics\u002Fmultiplicity-graphical - Bretz-Maurer graphs for multiple endpoints from one logistic model\n- clinical-biostatistics\u002Ftrial-reporting - CONSORT 2025 and ICH E9(R1) reporting of logistic analyses\n","## Version Compatibility\n\nReference examples tested with: statsmodels 0.14+, scipy 1.12+, numpy 1.26+, pandas 2.1+, firthmodels 0.3+, marginaleffects 0.0.13+ (Python) \u002F 0.20+ (R). R packages cited: RobinCar, marginaleffects, brant, MASS, VGAM.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- R: `packageVersion('\u003Cpkg>')` then `?function_name`\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.\n\n# Logistic Regression for Clinical Outcomes\n\n**\"Model clinical outcomes with logistic regression\"** -> Estimate the marginal or conditional treatment effect on a binary or ordinal endpoint using a model that respects randomisation stratification, declares its estimand, and survives covariate misspecification.\n\n**Conditional vs marginal (the non-collapsibility subtlety):** the OR is non-collapsible. The conditional OR from logistic regression is a *different parameter* than the marginal OR, even when there is NO confounding and randomisation is perfect. This is mathematical, not statistical bias. FDA 2023 favours marginal RD (via g-computation) for primary reporting to avoid parameter ambiguity. See clinical-biostatistics\u002Feffect-measures and Permutt 2020.\n\n## Algorithmic Taxonomy\n\n| Approach | Estimand | Inference | Strength | Fails when |\n|----------|----------|-----------|----------|------------|\n| Unadjusted logistic \u002F chi-square | Marginal OR | Wald or LR | Simple; transparent | Loses efficiency vs adjusted (Senn 2013); inflates SE under stratified randomisation (Kahan-Morris 2012) |\n| Logistic with covariates (ML, Wald CI) | **Conditional** log-OR | Wald | Standard; widely available | Conditional OR != marginal OR due to non-collapsibility (Permutt 2020); not the FDA 2023 primary estimand |\n| Logistic + g-computation \u002F standardisation | **Marginal** RD\u002FRR\u002FOR | Influence function or bootstrap SE | FDA 2023 recommended primary estimand for binary | Requires correct outcome model AND post-fit standardisation; needs robust SE machinery |\n| Targeted Maximum Likelihood (TMLE) | Marginal RD\u002FRR\u002FOR | Influence function | Provably efficient; doubly robust in observational | Implementation heavier; mostly R (`tmle`, `tmle3`); rare in confirmatory submissions |\n| Modified Poisson with sandwich SE | Marginal RR | HC1\u002FHC3 sandwich | Direct RR estimation when prevalence >10% | Slightly less efficient than log-binomial when log-binomial converges |\n| Log-binomial regression | Marginal RR | Wald | Direct RR estimation | Frequent convergence failure when predicted risk near 1 |\n| Firth penalised logistic | Conditional OR (penalised) | Penalised LR test preferred | Handles separation, rare events (\u003C5% prevalence) | Wald CI\u002Fp liberal; must use PLR test (Heinze-Schemper 2002) |\n| Ordinal logistic (proportional odds) | Common conditional OR across cut-points | Wald or LR | Preserves ordering information | Proportional odds assumption violation (Brant test) |\n| Partial proportional odds | PO holds for some covariates, not others | Hybrid | Salvages ordinal model when PO fails for one predictor | Increased complexity; harder interpretation |\n| Multinomial logistic | Per-category log-OR | Wald | No PO assumption needed | Loses efficiency; harder communication |\n\n**Postdoc reading list:** Permutt 2020 *Stat Biopharm Res* 12:45 (conditional vs marginal estimand); FDA May 2023 Final Guidance \"Adjusting for Covariates in RCTs\" (the regulatory rulebook); Tsiatis et al 2008 *Stat Med* 27:4658 (robust ANCOVA framework); Senn 2013 *Stat Med* 32:1439 (precision from adjustment even under perfect balance); Kahan-Morris 2012 *Stat Med* 31:328 (must adjust for stratification factors).\n\n## Decision Tree by Scenario\n\n| Scenario | Recommended approach | Why |\n|----------|---------------------|-----|\n| RCT, binary primary endpoint, no covariate adjustment in SAP | Unadjusted logistic with marginal OR; chi-square supportive | Simple regulatory case; consider whether covariate adjustment would gain power (Senn 2013) |\n| RCT, binary primary, covariates pre-specified, FDA 2023 compliant | **Logistic adjusted + g-computation for marginal RD**; conditional OR supportive | FDA 2023 final: marginal estimand for primary; mention HC3 sandwich SE |\n| RCT, stratified randomisation (sex\u002Fregion\u002Fseverity) | Include strata as covariates in logistic; the analytic decision is non-optional | Kahan-Morris 2012: ignoring strata is over-conservative -- SE biased upward, CIs too wide, power loss |\n| Common outcome (prevalence >10%) where RR is the policy quantity | Modified Poisson + HC1\u002FHC3 OR log-binomial regression | Avoid OR misinterpretation; Zou 2004; cite EMA 2015 on covariate adjustment |\n| Rare event (\u003C5% prevalence) or separation observed | Firth penalty + penalised LR test for p-value | Heinze-Schemper 2002; Wald p from Firth is liberal |\n| Ordinal outcome, PO assumption supportable | Proportional odds; verify with Brant test (R `brant::brant`) | Most efficient when PO holds; common in toxicity grading and PROs |\n| Ordinal outcome, PO fails on one or two predictors | Partial PO model (R `VGAM::vglm(..., cumulative(parallel=FALSE~X))`) | Salvages most efficiency; only the offending coefficient gets per-cut-point estimate |\n| Ordinal outcome, PO fails widely | Multinomial logistic | Worst case; loses ordering info but valid |\n| Single arm observational with strong confounding | Logistic adjusted + g-computation + propensity weighting | Doubly robust; cite Hernan-Robins; consider TMLE |\n| Binary endpoint, longitudinal repeated measures | GEE or generalised linear mixed model | Sandwich SE for GEE; mixed-model OR is subject-specific not marginal |\n\n## Standard Workflow\n\n**Goal:** Fit a covariate-adjusted logistic regression for a binary clinical endpoint with explicit reference category and pre-specified covariates.\n\n**Approach:** Use the formula API for automatic categorical handling and explicit reference; report both the conditional log-OR and the marginal RD via g-computation.\n\n```python\nimport statsmodels.formula.api as smf\nimport pandas as pd\nimport numpy as np\n\n# CRITICAL: set reference category explicitly. statsmodels default is alphabetical,\n# so 'Active' sorts before 'Placebo' and the OR direction silently flips.\nmodel = smf.logit(\n    'outcome ~ C(ARM, Treatment(reference=\"Placebo\")) + age + C(sex) + baseline_score',\n    data=df\n).fit()\n\n# Conditional ORs (Wald)\nor_table = pd.DataFrame({\n    'OR': np.exp(model.params),\n    'Lower_CI': np.exp(model.conf_int()[0]),\n    'Upper_CI': np.exp(model.conf_int()[1]),\n    'p_value': model.pvalues\n})\n\n# Marginal RD via g-computation (the FDA 2023-recommended primary estimand):\ndf_active = df.assign(ARM='Active')\ndf_placebo = df.assign(ARM='Placebo')\nrisk_active = model.predict(df_active).mean()\nrisk_placebo = model.predict(df_placebo).mean()\nmarginal_rd = risk_active - risk_placebo\n# For SE, use influence-function or bootstrap; see RobinCar \u002F marginaleffects in R\n```\n\n**The reference-category trap is the single most common silent bug.** `smf.logit('y ~ C(ARM)')` uses alphabetical ordering, so `ARM='Active'` becomes 1 and `ARM='Placebo'` becomes 0 -- but with `ARM=['Active','Placebo','Control']`, 'Active' is the reference and 'Placebo' is the comparison. Always pass `Treatment(reference=\"Placebo\")` or equivalent. R `glm(y ~ relevel(ARM, ref='Placebo'))`.\n\n## Marginal vs Conditional Estimand -- The FDA 2023 Pivot\n\n**The single most important methodological shift in clinical biostatistics 2020-2025.** Permutt 2020 established and FDA 2023 codified: the maximum-likelihood coefficient on Z in `glm(Y ~ Z + X, family=binomial)` is the **conditional log-OR** -- the OR comparing Z=1 to Z=0 holding X fixed. Due to OR non-collapsibility, this is a *different parameter* than the **marginal log-OR** (the OR comparing the entire treated population to the entire control population), even under perfect randomisation.\n\n**The FDA 2023 final guidance** (\"Adjusting for Covariates in Randomized Clinical Trials,\" May 2023) endorses covariate-adjusted nonlinear-model analysis *provided the analyst targets a marginal estimand*. Reporting the conditional OR from a multivariable logistic regression as \"the treatment effect\" silently changes the estimand from what was pre-specified.\n\n### G-computation \u002F Standardisation\n\n```python\n# Marginal effects on three scales via g-computation:\ndf_z1 = df.assign(ARM='Active')\ndf_z0 = df.assign(ARM='Placebo')\np_z1 = model.predict(df_z1)\np_z0 = model.predict(df_z0)\n\nmarg_p1 = p_z1.mean()\nmarg_p0 = p_z0.mean()\nmarg_rd = marg_p1 - marg_p0\nmarg_rr = marg_p1 \u002F marg_p0\nmarg_or = (marg_p1 \u002F (1 - marg_p1)) \u002F (marg_p0 \u002F (1 - marg_p0))\n```\n\n**For valid SE:** the delta-method\u002Finfluence-function variance and HC3 sandwich are required. Python `marginaleffects` v0.0.13+ implements this via `marginaleffects.avg_comparisons(model, variables='ARM', vcov='HC3')`. R is more mature: `marginaleffects::avg_comparisons` (Arel-Bundock-Greifer-Heiss 2024 *JSS* 111:9), `RobinCar` (purpose-built for FDA 2023), `riskCommunicator`.\n\n**Tsiatis et al 2008 robustness guarantee:** under randomisation Z ⊥ X, the g-computation marginal estimator is *consistent* for the marginal ATE even if the outcome model is misspecified. Efficiency depends on model quality; consistency does not. This is why FDA 2023 accepts the marginal RD via g-computation without requiring proof of correct logistic mean structure.\n\n**Reporting template (post-FDA-2023):**\n\n> \"Primary estimand: marginal risk difference of -8.5 percentage points (95% CI -12.7 to -4.2, HC3 SE), computed by g-computation\u002Fstandardisation from a logistic regression adjusted for age, sex, and baseline severity. Supportive: conditional OR 0.48 (95% CI 0.34-0.67, Wald) from the same model.\"\n\n## Modified Poisson for Common Outcomes -- Direct RR\n\nWhen prevalence > 10% and the policy quantity is RR (not OR), modified Poisson with sandwich SE is the de facto modern standard (Zou 2004 *AJE* 159:702):\n\n```python\nimport statsmodels.api as sm\nimport numpy as np\n\nX = sm.add_constant(df[['treatment', 'age', 'baseline_score']])\npoisson_model = sm.GLM(df['outcome'], X, family=sm.families.Poisson()).fit(cov_type='HC1')\nrr = np.exp(poisson_model.params)\nrr_ci = np.exp(poisson_model.conf_int())\n```\n\n`cov_type='HC1'` corrects the over-dispersion that Poisson inherently assumes. Without it the variance is wrong because binary data are NOT Poisson. For n \u003C 250, HC3 is preferred (Long-Ervin 2000). **What postdocs argue about:** modified Poisson vs log-binomial -- log-binomial directly models RR but frequently fails to converge when predicted risk approaches 1; modified Poisson always converges but is marginally less efficient when log-binomial works.\n\n## Proportional Odds and Brant Test\n\n**Proportional odds (PO)** assumption: the effect of each predictor is constant across all cut-points of the ordinal outcome. Must be tested or the model parameters are invalid.\n\n```python\nfrom statsmodels.miscmodels.ordinal_model import OrderedModel\nfrom statsmodels.api import MNLogit\nimport pandas as pd\n\ndf['severity'] = pd.Categorical(df['severity'], categories=['mild', 'moderate', 'severe'], ordered=True)\n\npo_model = OrderedModel.from_formula('severity ~ treatment + age', data=df, distr='logit').fit(method='bfgs', disp=0)\nmn_model = MNLogit.from_formula('severity ~ treatment + age', data=df).fit(disp=0)\n\n# LR test for PO vs MN (omnibus)\nlr_stat = 2 * (mn_model.llf - po_model.llf)\nlr_df = mn_model.df_model - po_model.df_model\nfrom scipy.stats import chi2\nlr_p = 1 - chi2.cdf(lr_stat, lr_df)\n\n# Per-coefficient Brant test in R: brant::brant(po_model_object)\n# The Brant test localises which predictor(s) violate PO -- essential before deciding on partial PO\n```\n\n**The omnibus LR test is necessary but not sufficient.** Brant test (Brant 1990 *Biometrics* 46:1171; R `brant::brant`) provides per-coefficient PO tests, identifying *which* predictor violates PO. If only one or two predictors violate PO, fit a **partial proportional odds model** (R `VGAM::vglm(..., cumulative(parallel=FALSE~X1+X2))`) rather than abandoning the model entirely.\n\n**OrderedModel intercept gotcha:** do NOT add an intercept term. Threshold parameters (cut-points between ordinal levels) replace the intercept. An explicit constant causes non-identifiability and optimiser failure.\n\n## Separation and Firth Penalty\n\n**Detection:**\n\n```python\nfrom firthmodels import FirthLogisticRegression, detect_separation\nimport numpy as np\n\nsep_result = detect_separation(X, y)\nif sep_result.separation:\n    print(sep_result.summary())\n# Manual signs: coefficient > 10, SE > 100, convergence warnings\n```\n\n**Firth penalty (Firth 1993 *Biometrika* 80:27):**\n\n```python\nfirth = FirthLogisticRegression()\nfirth.fit(X, y)\nor_firth = np.exp(firth.coef_)\n\n# IMPORTANT: Wald p-values from Firth are LIBERAL (anti-conservative).\n# Prefer the penalised likelihood-ratio test (PLRT).\n# Some Python `firthlogist` releases expose a PLRT attribute (e.g. `pvalues_lrt_`)\n# but its presence and name vary by release -- check `dir(firth)` against the\n# installed version, otherwise compute the PLRT manually from the penalised\n# log-likelihoods of nested models.\n```\n\n**Heinze-Schemper 2002 *Stat Med* 21:2409** showed Wald inference from Firth is **liberal** (anti-conservative); the penalised likelihood-ratio test (PLRT) is the recommended inference. PLRT attributes (e.g. `pvalues_lrt_`) appear in some Python Firth packages but the exact attribute name varies by release -- introspect the installed package; compute the PLRT manually if no attribute is exposed:\n\n```python\ndef penalised_lrt(firth_full, firth_reduced):\n    # Compute 2 * (penalised log-lik full - penalised log-lik reduced) ~ chi-square_df\n    pass  # implementation depends on package version; see Heinze-Schemper 2002\n```\n\nFirth's method was originally designed for finite-sample bias reduction, not separation per se -- it adds the Jeffreys prior penalty to the likelihood, keeping coefficients finite under separation as a side effect. Also recommended for rare events (\u003C5% prevalence) where ML bias is non-negligible.\n\n## Hauck-Donner Effect Detection\n\n**The Hauck-Donner effect (1977 *JASA* 72:851; revived by Yee 2022 *JASA* 117:1763):** the Wald test statistic is non-monotonic in the parameter estimate near the boundary. A large log-OR can produce a small Wald chi-square -- so the Wald test fails to reject when LR\u002Fprofile-likelihood would. Common in small samples with strong predictors.\n\n```python\n# In R, detect with VGAM::hdeff() and replace Wald with profile likelihood:\n# MASS::confint.glm(model) returns profile-likelihood CIs as default\n# Python equivalent: bootstrap or manual profile likelihood\n```\n\n**When to suspect Hauck-Donner:** large coefficient magnitude with non-significant Wald p; large SE with finite estimate; switching from Wald to LR test changes significance. The fix is always: switch to profile likelihood or LR inference.\n\n## Reconciliation: When Methods Disagree\n\n| Pattern | Likely cause | Action |\n|---------|--------------|--------|\n| Conditional OR from logistic vs marginal RD from g-computation give different conclusions | Non-collapsibility (OR is non-collapsible; RD is collapsible) | Report marginal RD as primary per FDA 2023; conditional OR as supportive with explicit parameter label; cite Permutt 2020 |\n| ML logistic diverges (large coefficient, huge SE); Firth penalised converges | Complete or quasi-complete separation in covariate-outcome relationship | Firth penalty with penalised LR test (NOT Wald p-values); cite Heinze-Schemper 2002 |\n| Modified Poisson and log-binomial give different RR estimates | Log-binomial convergence fragility when predicted risk approaches 1 | Modified Poisson with sandwich SE preferred for robust convergence; cite Zou 2004 |\n| Proportional-odds (cumulative logit) and multinomial give different inferences | PO assumption violated for one or more predictors (Brant test rejects) | Localise via Brant test; if 1-2 predictors violate, partial-PO model in VGAM; if widely, multinomial |\n| Adjusted vs unadjusted treatment effect differ substantially | Confounding (in observational) OR non-collapsibility (in RCT) | In RCT, non-collapsibility expected (Permutt 2020); in observational, investigate confounding via DAG |\n| Large OR with non-significant Wald p-value | Hauck-Donner effect: Wald non-monotone near boundary (Yee 2022) | Use profile-likelihood CI (R `MASS::confint.glm`); detect via `VGAM::hdeff()` |\n| Stratified analysis significant; unstratified not | Achieved SE smaller in stratified analysis | Include stratification factors in primary model (Kahan-Morris 2012); ignoring biases the SE upward and loses power (over-conservative) |\n| Significant treatment effect on conditional model vanishes when mediator included | Adjusting for post-treatment variable on causal pathway | Never adjust for mediators in primary; use causal DAG to distinguish confounder vs mediator |\n\n## Per-Method Failure Modes\n\n### Reference-category silent reversal\n\n- **Trigger:** Treatment variable coded as character with `Active` and `Placebo`; reference not explicitly set.\n- **Mechanism:** statsmodels defaults to alphabetical ordering; 'Active' becomes the reference.\n- **Symptom:** OR for \"ARM[T.Placebo]\" appears in output; direction is the opposite of intended.\n- **Fix:** Always pass `C(ARM, Treatment(reference=\"Placebo\"))` or numeric encoding with explicit comment.\n\n### Adjusting for a mediator\n\n- **Trigger:** Including a post-randomisation variable that lies on the causal pathway.\n- **Mechanism:** Adjustment blocks the causal effect, attenuating treatment effect estimate toward null.\n- **Symptom:** Significant unadjusted effect becomes non-significant after adjustment for \"mechanism\" variable (e.g., inflammation marker).\n- **Fix:** Use causal DAG to distinguish confounder from mediator; never adjust for post-treatment variables in the primary analysis. See ICH E9(R1).\n\n### Hauck-Donner non-monotonicity\n\n- **Trigger:** Small samples, strong predictor, cell counts approaching zero.\n- **Mechanism:** Wald test statistic is non-monotone in the parameter near the boundary.\n- **Symptom:** Large OR magnitude with non-significant Wald p; switching to LR test changes significance.\n- **Fix:** Use profile likelihood (R `MASS::confint.glm`) or LR inference; detect with `VGAM::hdeff()`.\n\n### Complete or quasi-complete separation\n\n- **Trigger:** A predictor perfectly predicts outcome in a subset of the data.\n- **Mechanism:** Likelihood is monotone in that coefficient; ML estimate diverges to infinity.\n- **Symptom:** Coefficient >10, SE >100, convergence warning; convergence message says \"fitted probabilities numerically 0 or 1.\"\n- **Fix:** Firth penalty (`firthmodels`); inference via penalised LR test, not Wald.\n\n### Proportional odds violation undetected\n\n- **Trigger:** Ordinal outcome fit with cumulative-logit (PO) model without testing assumption.\n- **Mechanism:** PO assumes a constant effect across cut-points; violation invalidates model parameters.\n- **Symptom:** Brant test rejects PO for one or more predictors; per-cut-point effects in a saturated model diverge.\n- **Fix:** Brant test first; if PO fails on one predictor, partial PO model; if widely fails, multinomial logistic.\n\n### Stratified randomisation not in analysis\n\n- **Trigger:** Stratification by site\u002Fregion\u002Fseverity at randomisation; analysis ignores strata.\n- **Mechanism:** Achieved SE smaller than calculated SE because randomisation removed between-stratum variability.\n- **Symptom:** Over-conservative inference -- SE biased upward, CIs too wide, Type-I error below nominal, and power loss (Kahan-Morris 2012).\n- **Fix:** Include stratification factors as covariates in the logistic; this is non-optional per ICH E9, FDA 2023, EMA 2015.\n\n## Model Diagnostics\n\n| Diagnostic | Method | Threshold | Caveat |\n|-----------|--------|-----------|--------|\n| Discrimination | ROC-AUC (`sklearn.metrics.roc_auc_score`) | >0.7 acceptable, >0.8 good | Trial-level, not patient-individual; depends on outcome prevalence |\n| Calibration -- primary | Calibration plot (observed vs predicted in deciles) | Curve along the diagonal | Visual; preferred over H-L |\n| Calibration -- secondary | Hosmer-Lemeshow chi-square | p > 0.05 | Low power n\u003C200; oversensitive n>2000 |\n| Pseudo R-squared | model.prsquared (McFadden) | >0.2 excellent | NOT comparable to OLS R-squared |\n| Events per variable | n_events \u002F n_covariates | >=10 EPV (Peduzzi 1996) | Below this: bias, overfitting; consider Firth |\n\n### Hosmer-Lemeshow\n\n```python\nfrom scipy.stats import chi2\nimport pandas as pd\n\ndef hosmer_lemeshow(y_true, y_pred, n_groups=10):\n    df_hl = pd.DataFrame({'y': y_true, 'prob': y_pred})\n    df_hl['group'] = pd.qcut(df_hl['prob'], n_groups, duplicates='drop')\n    grouped = df_hl.groupby('group').agg(obs=('y', 'sum'), n=('y', 'count'), pred=('prob', 'mean'))\n    grouped['expected'] = grouped['n'] * grouped['pred']\n    hl_stat = (((grouped['obs'] - grouped['expected']) ** 2) \u002F\n               (grouped['n'] * grouped['pred'] * (1 - grouped['pred']))).sum()\n    actual_groups = len(grouped)\n    return hl_stat, 1 - chi2.cdf(hl_stat, actual_groups - 2)\n```\n\n**H-L is supplementary, not primary:** Hosmer-Lemeshow has low power n\u003C200 (rarely rejects even for poor calibration) and oversensitive n>2000 (rejects for trivial miscalibration). The decile choice is also arbitrary -- `pd.qcut(..., duplicates='drop')` can reduce the actual number of groups when probabilities tie, changing df. Use calibration plots (smoothed observed vs predicted) as primary; Hosmer-Lemeshow as supplementary p-value.\n\n## Quantitative Thresholds\n\n| Threshold | Source | Rationale |\n|-----------|--------|-----------|\n| 10 events per variable (EPV) | Peduzzi et al 1996 *J Clin Epidemiol* 49:1373 | Below this, coefficient bias and CI mis-coverage |\n| Prevalence > 10% -> prefer marginal RR via modified Poisson | Zou 2004 *AJE* 159:702 | OR overstates RR; modified Poisson directly estimates RR |\n| Marginal estimand for primary regulatory analysis | FDA 2023 Final Guidance | Conditional OR is a different parameter than marginal (Permutt 2020) |\n| Brant test for PO assumption | Brant 1990 *Biometrics* 46:1171 | Omnibus LR test misses per-coefficient violations |\n| Firth penalty with penalised LR test, not Wald | Heinze-Schemper 2002 *Stat Med* 21:2409 | Wald is liberal under Firth penalty |\n| HC3 sandwich SE for n \u003C=250 | Long-Ervin 2000 *Am Stat* 54:217 | HC1 (Stata default) anti-conservative in small samples |\n| Stratification factors in analysis when used in randomisation | Kahan-Morris 2012 *Stat Med* 31:328 | Ignoring biases SE upward -- CIs too wide, power loss (over-conservative) |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| OR direction opposite of expected | Alphabetical reference; 'Active' sorts before 'Placebo' | `C(ARM, Treatment(reference=\"Placebo\"))` always |\n| Conditional and marginal OR differ substantially | Non-collapsibility, not confounding | Cite Permutt 2020; report both with explicit labels |\n| Treatment effect vanishes after adjustment | Adjusted for a mediator (post-treatment variable) | Causal DAG check; never adjust for post-treatment in primary |\n| Huge coefficient, huge SE, non-significant Wald | Separation OR Hauck-Donner | Detect separation: `firthmodels.detect_separation`; switch to Firth + PLRT |\n| H-L p > 0.5 with obvious miscalibration | Low power at n\u003C200 | Use calibration plot as primary; H-L supplementary |\n| H-L p \u003C 0.001 with great-looking plot | Oversensitive at n>2000 | Use calibration plot; cite Steyerberg 2019 for cautions |\n| `OrderedModel` fails to converge with intercept | Threshold parameters replace intercept | Drop the explicit constant |\n| `firth.pvalues_` looks too low | Wald p from Firth is liberal | Inspect the installed Firth package for a PLRT attribute (e.g. `pvalues_lrt_`); compute PLRT manually if none is exposed |\n| GLM(family=Binomial) and Logit give same point but different output | `sm.Logit` provides `pred_table()`, `prsquared`; `sm.GLM` does not | Use Logit unless changing link functions |\n| Robust SE not reported for modified Poisson | Missing `cov_type='HC1'` or 'HC3' | Always specify sandwich SE for modified Poisson |\n\n## Anticipated Reviewer Pushback\n\n| Pushback | Response |\n|----------|----------|\n| \"Why is the marginal RD different from the conditional OR's implied RD?\" | Non-collapsibility of OR; cite Permutt 2020 and FDA 2023. Marginal RD via g-computation is the primary per FDA 2023. |\n| \"Adjustment for stratification factors?\" | Pre-specified strata included in the model. Cite Kahan-Morris 2012 and ICH E9. |\n| \"How were covariates chosen?\" | Pre-specified in the SAP based on prior literature\u002Fclinical knowledge. No data-driven selection (which would inflate Type-I). |\n| \"Why not use stepwise selection?\" | Stepwise leaks signal from the outcome and inflates Type-I. Pre-specification is the regulatory norm; cite FDA 2023. |\n| \"PH check for the longitudinal binary?\" | Binary doesn't have PH; if longitudinal, used GEE with sandwich SE or GLMM; see ICH E9 estimand for treatment policy. |\n| \"Why Firth not standard logistic?\" | Separation detected (or rare events \u003C5%); standard ML diverges; Firth penalty + PLRT recommended (Heinze-Schemper 2002). |\n| \"Brant test result?\" | PO holds for predictors X1, X2, X3; PO fails for X4 -> partial PO model fit per VGAM. |\n| \"Calibration?\" | Calibration plot in supplement; H-L p reported as supplementary, not primary. |\n\n## References\n\n- Arel-Bundock V, Greifer N, Heiss A. 2024. How to interpret statistical models using marginaleffects in R and Python. *J Stat Softw* 111:9.\n- Brant R. 1990. Assessing proportionality in the proportional odds model for ordinal logistic regression. *Biometrics* 46:1171-1178.\n- FDA. 2023. Adjusting for Covariates in Randomized Clinical Trials for Drugs and Biological Products. Final Guidance, May 2023.\n- Firth D. 1993. Bias reduction of maximum likelihood estimates. *Biometrika* 80:27-38.\n- Hauck WW, Donner A. 1977. Wald's test as applied to hypotheses in logit analysis. *JASA* 72:851-853.\n- Heinze G, Schemper M. 2002. A solution to the problem of separation in logistic regression. *Stat Med* 21:2409-2419.\n- Kahan BC, Morris TP. 2012. Improper analysis of trials randomised using stratified blocks or minimisation. *Stat Med* 31:328-340.\n- Lin DY, Wei LJ. 1989. The robust inference for the Cox proportional hazards model. *JASA* 84:1074-1078.\n- Long JS, Ervin LH. 2000. Using heteroscedasticity consistent standard errors in the linear regression model. *Am Stat* 54:217-224.\n- Moore KL, van der Laan MJ. 2009. Covariate adjustment in randomized trials with binary outcomes: TMLE. *Stat Med* 28:39-64.\n- Peduzzi P, Concato J, Kemper E, Holford TR, Feinstein AR. 1996. A simulation study of the number of events per variable in logistic regression analysis. *J Clin Epidemiol* 49:1373-1379.\n- Permutt T. 2020. Do covariates change the estimand? *Stat Biopharm Res* 12:45-53.\n- Senn S. 2013. Seven myths of randomisation in clinical trials. *Stat Med* 32:1439-1450.\n- Steyerberg EW. 2019. *Clinical Prediction Models* (2nd ed). Springer.\n- Tsiatis AA, Davidian M, Zhang M, Lu X. 2008. Covariate adjustment for two-sample treatment comparisons in randomized clinical trials. *Stat Med* 27:4658-4677.\n- Wang B, Susukida R, Mojtabai R, Amin-Esmaeili M, Rosenblum M. 2023. Model-robust inference for clinical trials that improve precision by stratified randomization and covariate adjustment. *JASA* 118:1152-1163.\n- Yee TW. 2022. On the Hauck-Donner effect in Wald tests. *JASA* 117:1763-1774.\n- Zou G. 2004. A modified Poisson regression approach to prospective studies with binary data. *AJE* 159:702-706.\n\n## Related Skills\n\n- clinical-biostatistics\u002Fcdisc-data-handling - Prepare analysis datasets from CDISC SDTM\u002FADaM domains\n- clinical-biostatistics\u002Feffect-measures - Modern CI methods; marginal vs conditional in depth\n- clinical-biostatistics\u002Fcategorical-tests - Chi-square and Fisher alternatives for unadjusted tests\n- clinical-biostatistics\u002Fsubgroup-analysis - Interaction terms and HTE detection\n- clinical-biostatistics\u002Fsurvival-analysis - Cox regression for time-to-event analogues\n- clinical-biostatistics\u002Fmultiplicity-graphical - Bretz-Maurer graphs for multiple endpoints from one logistic model\n- clinical-biostatistics\u002Ftrial-reporting - CONSORT 2025 and ICH E9(R1) reporting of logistic analyses\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","python","2026-09-20","clinical-biostatistics\u002Flogistic-regression\u002FSKILL.md","statsmodels","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fgeospatial\u002Fbio-clinical-biostatistics-logistic-regression","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-clinical-biostatistics-logistic-regression",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-clinical-biostatistics-logistic-regression",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-clinical-biostatistics-logistic-regression","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fgeospatial\u002Fbio-clinical-biostatistics-logistic-regression\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Flogistic_regression_clinical.py","SCRIPT","脚本",4510,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fgeospatial\u002Fbio-clinical-biostatistics-logistic-regression\u002Fexamples\u002Flogistic_regression_clinical.py",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",6550,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fgeospatial\u002Fbio-clinical-biostatistics-logistic-regression\u002Fusage-guide.md",[63,70,77,84,91,98],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]