Files
models/models/cacu/development_firth.py
T

84 lines
3.5 KiB
Python

"""Firth, FLIC and FLAC from edgar/camodels, commit 2392d54fd4a3942b56dae803906586bc65600728."""
import warnings
import numpy as np
from scipy.optimize import brentq
from scipy.special import expit
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.exceptions import ConvergenceWarning
SOLVER = dict(max_iter=200, gtol=1e-6, xtol=1e-6)
class ConvergenceError(RuntimeError):
"""Raised when the remaining Newton step fails the convergence check."""
def solve_logistic(X, y, sample_weight=None, penalty_weight=0.5):
"""Fit logistic regression and return the fitted solver and leverages.
Check the remaining Newton step directly because numerical precision can
affect the solver's convergence flag.
"""
y = np.asarray(y)
if y.ndim != 1 or not (np.isin(y, [0, 1]).all() and (y == 0).any() and (y == 1).any()):
raise ValueError("The outcome must contain only 0 and 1, with both classes present.")
y = y.astype(int, copy=False)
from firthmodels import FirthLogisticRegression
with warnings.catch_warnings():
warnings.simplefilter("ignore", ConvergenceWarning)
model = FirthLogisticRegression(penalty_weight=penalty_weight, **SOLVER).fit(
X, y, sample_weight=sample_weight
)
design = np.column_stack([np.ones(len(y)), X])
weights = np.ones(len(y)) if sample_weight is None else sample_weight
p = expit(model.intercept_ + X @ model.coef_)
w = weights * p * (1 - p)
info = design.T @ (w[:, None] * design)
h = w * np.einsum("ij,ji->i", design, np.linalg.solve(info, design.T))
score = design.T @ (weights * (y - p) + penalty_weight * h * (1 - 2 * p))
step = np.abs(np.linalg.solve(info, score)).max()
if not np.isfinite(step) or step >= 1e-4:
raise ConvergenceError(f"The fit did not converge (remaining Newton step {step:.2g}).")
return model, h
class FirthFamily(ClassifierMixin, BaseEstimator):
"""Estimate binary outcome probabilities using Firth, FLIC, or FLAC."""
def __init__(self, method="firth"):
self.method = method
def fit(self, X, y):
"""Fit the selected method to a binary outcome."""
if self.method not in ("firth", "flic", "flac"):
raise ValueError(f"Unknown method {self.method!r}. Expected 'firth', 'flic', or 'flac'.")
X = np.asarray(X, float)
firth, h = solve_logistic(X, y)
y = np.asarray(y, int)
self.classes_ = np.array([0, 1])
self.coef_, self.intercept_ = firth.coef_.copy(), float(firth.intercept_)
if self.method == "flic":
eta = X @ self.coef_
self.intercept_ = brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50, xtol=1e-12)
elif self.method == "flac":
# Pseudo-observations use both outcomes, each with half the leverage.
g = np.repeat([0, 1, 1], len(y))
self.X_aug_ = np.column_stack([np.tile(X, (3, 1)), g])
self.y_aug_ = np.concatenate([y, y, 1 - y])
self.w_aug_ = np.concatenate([np.ones(len(y)), h / 2, h / 2])
ml, _ = solve_logistic(self.X_aug_, self.y_aug_, self.w_aug_, penalty_weight=0)
# Predict on original observations, where the indicator is zero.
self.coef_, self.intercept_ = ml.coef_[:-1].copy(), float(ml.intercept_)
return self
def predict_proba(self, X):
"""Return probabilities for classes 0 and 1 in that order."""
p = expit(self.intercept_ + np.asarray(X, float) @ self.coef_)
return np.column_stack([1 - p, p])