survml 1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
survml/__init__.py ADDED
@@ -0,0 +1,74 @@
1
+ """survml — integrated survival analysis and machine learning in Python.
2
+
3
+ The package implements the integrated algorithms of Csalódi and Abonyi and
4
+ recent survival methods that have no Python implementation elsewhere, on top
5
+ of a small set of classical estimators:
6
+
7
+ * classical building blocks with weights: Kaplan–Meier, Nelson–Aalen,
8
+ Aalen–Johansen, weighted log-rank tests (:mod:`survml.core`);
9
+ * cluster-weighted mixtures of local Weibull (and other) survival models with
10
+ Gaussian and categorical gates, fitted by EM, read as Takagi–Sugeno fuzzy
11
+ rules (:mod:`survml.mixture`, :mod:`survml.distributions`);
12
+ * frequent itemset-based association rules and cumulative incidence functions
13
+ of competing risks (:mod:`survml.itemsets`);
14
+ * time-dependent confidences of frequent sequences and sequential rules, with
15
+ bootstrap bands and a censoring-aware estimator (:mod:`survml.sequences`,
16
+ :mod:`survml.patterns`);
17
+ * root causes of long durations by Cox regression (:mod:`survml.changeover`);
18
+ * Fine–Gray competing-risks regression (:mod:`survml.competing`),
19
+ pseudo-observation regression (:mod:`survml.pseudo`), restricted mean
20
+ survival and time lost (:mod:`survml.restricted`), mixture cure models
21
+ (:mod:`survml.cure`), survival stacking (:mod:`survml.stacking`),
22
+ conformal lower prediction bounds with fixed and adaptive cut-offs
23
+ (:mod:`survml.conformal`);
24
+ * metrics (:mod:`survml.metrics`), public data sets (:mod:`survml.datasets`),
25
+ simulators with known truth (:mod:`survml.simulate`) and plots (:mod:`survml.viz`).
26
+ """
27
+
28
+ from . import (
29
+ changeover,
30
+ competing,
31
+ conformal,
32
+ core,
33
+ cure,
34
+ datasets,
35
+ distributions,
36
+ itemsets,
37
+ metrics,
38
+ mixture,
39
+ patterns,
40
+ pseudo,
41
+ restricted,
42
+ sequences,
43
+ simulate,
44
+ stacking,
45
+ viz,
46
+ )
47
+ from ._version import __version__
48
+ from .changeover import DurationRootCause
49
+ from .competing import FineGray
50
+ from .conformal import CensoringModel, ConformalSurvival
51
+ from .core import AalenJohansen, KaplanMeier, NelsonAalen, bootstrap_band, logrank_test, pairwise_logrank
52
+ from .cure import MixtureCure
53
+ from .itemsets import PeriodItemsetSurvival, discrete_cif
54
+ from .metrics import brier_score, concordance_index, d_calibration, integrated_brier_score, uno_concordance
55
+ from .mixture import ClusterWeightedSurvival, select_n_components
56
+ from .patterns import build_traces, frequent_itemsets, frequent_sequences, sequential_rules
57
+ from .pseudo import PseudoRegression, pseudo_observations
58
+ from .restricted import rmst, rmst_test, rmtl
59
+ from .sequences import FrequentSequenceSurvival, SequentialRuleSurvival
60
+ from .stacking import SurvivalStacking
61
+
62
+ __all__ = [
63
+ "__version__",
64
+ "KaplanMeier", "NelsonAalen", "AalenJohansen", "logrank_test", "pairwise_logrank", "bootstrap_band",
65
+ "ClusterWeightedSurvival", "select_n_components",
66
+ "PeriodItemsetSurvival", "discrete_cif",
67
+ "FrequentSequenceSurvival", "SequentialRuleSurvival",
68
+ "frequent_itemsets", "frequent_sequences", "sequential_rules", "build_traces",
69
+ "DurationRootCause", "FineGray", "PseudoRegression", "pseudo_observations",
70
+ "rmst", "rmst_test", "rmtl", "MixtureCure", "SurvivalStacking", "ConformalSurvival", "CensoringModel",
71
+ "concordance_index", "uno_concordance", "brier_score", "integrated_brier_score", "d_calibration",
72
+ "changeover", "competing", "conformal", "core", "cure", "datasets", "distributions", "itemsets", "metrics",
73
+ "mixture", "patterns", "pseudo", "restricted", "sequences", "simulate", "stacking", "viz",
74
+ ]
survml/_utils.py ADDED
@@ -0,0 +1,96 @@
1
+ """Small helpers shared by the modules (input checks, step functions, random generators)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+
9
+ def as_rng(random_state=None) -> np.random.Generator:
10
+ """A NumPy generator from a seed, a generator or ``None``."""
11
+ if isinstance(random_state, np.random.Generator):
12
+ return random_state
13
+ return np.random.default_rng(random_state)
14
+
15
+
16
+ def check_surv(time, event=None, weights=None):
17
+ """Validate a right-censored sample.
18
+
19
+ Returns ``time`` (float, non-negative), ``event`` (int; 0 = censored,
20
+ 1, 2, ... = cause of the event) and ``weights`` (float, non-negative).
21
+ ``event=None`` means that every time is an event time.
22
+ """
23
+ t = np.asarray(time, dtype=float).ravel()
24
+ if t.size == 0:
25
+ raise ValueError("empty sample")
26
+ if np.any(~np.isfinite(t)) or np.any(t < 0):
27
+ raise ValueError("times must be finite and non-negative")
28
+ if event is None:
29
+ e = np.ones(t.size, dtype=int)
30
+ else:
31
+ e_raw = np.asarray(event).ravel()
32
+ if e_raw.dtype == bool:
33
+ e = e_raw.astype(int)
34
+ else:
35
+ e = np.asarray(e_raw, dtype=float)
36
+ if np.any(e != np.round(e)) or np.any(e < 0):
37
+ raise ValueError("event codes must be 0 (censored) or positive integers (causes)")
38
+ e = e.astype(int)
39
+ if e.size != t.size:
40
+ raise ValueError("time and event have different lengths")
41
+ if weights is None:
42
+ w = np.ones(t.size)
43
+ else:
44
+ w = np.asarray(weights, dtype=float).ravel()
45
+ if w.size != t.size or np.any(w < 0) or np.any(~np.isfinite(w)):
46
+ raise ValueError("weights must be finite, non-negative and as long as time")
47
+ return t, e, w
48
+
49
+
50
+ def step_eval(x, y, t, left: float = 1.0) -> np.ndarray:
51
+ """Evaluate a right-continuous step function given by jump points ``x`` and values ``y``.
52
+
53
+ ``y[k]`` holds on ``[x[k], x[k+1])``; before ``x[0]`` the value is ``left``.
54
+ """
55
+ x = np.asarray(x, dtype=float)
56
+ y = np.asarray(y, dtype=float)
57
+ t = np.asarray(t, dtype=float)
58
+ if y.size == 0:
59
+ return np.full(t.shape, float(left))
60
+ idx = np.searchsorted(x, t, side="right") - 1
61
+ return np.where(idx >= 0, y[np.clip(idx, 0, None)], left)
62
+
63
+
64
+ def as_frame(X, prefix: str = "x") -> pd.DataFrame | None:
65
+ """``None``, an array or a DataFrame → DataFrame (columns named ``prefix0, prefix1, ...``)."""
66
+ if X is None:
67
+ return None
68
+ if isinstance(X, pd.DataFrame):
69
+ return X
70
+ if isinstance(X, pd.Series):
71
+ return X.to_frame()
72
+ a = np.asarray(X)
73
+ if a.ndim == 1:
74
+ a = a[:, None]
75
+ return pd.DataFrame(a, columns=[f"{prefix}{k}" for k in range(a.shape[1])])
76
+
77
+
78
+ def holm(pvalues) -> np.ndarray:
79
+ """Holm's step-down adjustment of p-values (family-wise error rate)."""
80
+ p = np.asarray(pvalues, dtype=float)
81
+ m = p.size
82
+ order = np.argsort(p)
83
+ adj = np.empty(m)
84
+ run = 0.0
85
+ for rank, k in enumerate(order):
86
+ run = max(run, min(1.0, (m - rank) * p[k]))
87
+ adj[k] = run
88
+ return adj
89
+
90
+
91
+ def logsumexp(a, axis=None):
92
+ a = np.asarray(a, dtype=float)
93
+ m = np.max(a, axis=axis, keepdims=True)
94
+ m = np.where(np.isfinite(m), m, 0.0)
95
+ out = np.log(np.sum(np.exp(a - m), axis=axis, keepdims=True)) + m
96
+ return np.squeeze(out, axis=axis) if axis is not None else out.item()
survml/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.0"
survml/changeover.py ADDED
@@ -0,0 +1,179 @@
1
+ r"""Root causes of long durations by Cox regression (setup and changeover times).
2
+
3
+ Ruppert, Csalódi and Abonyi (2021, Computers & Industrial Engineering 153:
4
+ 107026) treat the duration of a machine setup as a survival time: the event is
5
+ the end of the changeover, and a longer "survival" is a loss. A Cox model
6
+ with categorical factors (product, operator, shift, machine) gives the factors
7
+ that significantly prolong the changeovers — the root causes that the
8
+ single-minute exchange of die (SMED) philosophy wants to remove. The same
9
+ analysis fits any duration of a process step: service, repair, waiting,
10
+ processing, length of stay.
11
+
12
+ :class:`DurationRootCause` wraps the Cox model of :mod:`lifelines` and adds
13
+
14
+ * one-hot coding of the factors with a chosen reference level,
15
+ * likelihood-ratio tests of whole factors and Holm-adjusted Wald tests of the levels,
16
+ * the proportional-hazards check (Schoenfeld residuals, Grambsch and Therneau,
17
+ 1994) with automatic stratification of the factors that violate it,
18
+ * expected (median) durations of every level and the excess time over the
19
+ best level — the potential gain of removing a root cause.
20
+
21
+ A hazard ratio below one means a *slower* completion, i.e. a longer duration.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from typing import Sequence
27
+
28
+ import numpy as np
29
+ import pandas as pd
30
+ from scipy import stats
31
+
32
+ from ._utils import holm
33
+
34
+ __all__ = ["DurationRootCause"]
35
+
36
+
37
+ class DurationRootCause:
38
+ """Cox-regression analysis of the factors behind long durations.
39
+
40
+ Parameters
41
+ ----------
42
+ factors : sequence of str
43
+ Categorical columns (products, operators, ...).
44
+ numeric : sequence of str, optional
45
+ Numeric columns.
46
+ reference : dict, optional
47
+ Reference level per factor (default: the most frequent level).
48
+ alpha : float
49
+ Significance level of the proportional-hazards check.
50
+ stratify_violations : bool
51
+ Refit with factors that violate the PH assumption as strata.
52
+ penalizer : float
53
+ Ridge penalty of the Cox fit (helps with rare levels).
54
+ min_count : int
55
+ Levels with fewer observations are merged into ``"other"``.
56
+ """
57
+
58
+ def __init__(self, factors: Sequence[str], numeric: Sequence[str] = (), reference: dict | None = None,
59
+ alpha: float = 0.05, stratify_violations: bool = True, penalizer: float = 0.0, min_count: int = 5):
60
+ self.factors = list(factors)
61
+ self.numeric = list(numeric)
62
+ self.reference = reference or {}
63
+ self.alpha = alpha
64
+ self.stratify_violations = stratify_violations
65
+ self.penalizer = penalizer
66
+ self.min_count = min_count
67
+
68
+ def _design(self, df, factors):
69
+ parts = [df[self.numeric].astype(float)] if self.numeric else []
70
+ for f in factors:
71
+ x = df[f].astype(str).where(df[f].astype(str).isin(self.levels_[f]), "other")
72
+ ref = self.reference_[f]
73
+ levels = [lv for lv in self.levels_[f] if lv != ref]
74
+ parts.append(pd.DataFrame({f"{f}[{lv}]": (x == lv).astype(float) for lv in levels}, index=df.index))
75
+ return pd.concat(parts, axis=1) if parts else pd.DataFrame(index=df.index)
76
+
77
+ def fit(self, df: pd.DataFrame, duration: str, event: str | None = None):
78
+ from lifelines import CoxPHFitter
79
+
80
+ d = df.copy()
81
+ if event is None:
82
+ event = "_event"
83
+ d[event] = 1
84
+ self.levels_, self.reference_ = {}, {}
85
+ for f in self.factors:
86
+ vc = d[f].astype(str).value_counts()
87
+ keep = list(vc[vc >= self.min_count].index)
88
+ if (vc < self.min_count).any():
89
+ keep.append("other")
90
+ self.levels_[f] = keep
91
+ self.reference_[f] = str(self.reference.get(f, vc.index[0]))
92
+ X = self._design(d, self.factors)
93
+ data = pd.concat([X, d[[duration, event]]], axis=1)
94
+ cph = CoxPHFitter(penalizer=self.penalizer).fit(data, duration, event)
95
+ self.strata_ = []
96
+ self.ph_test_ = None
97
+ if self.stratify_violations and len(X.columns):
98
+ try:
99
+ from lifelines.statistics import proportional_hazard_test
100
+
101
+ ph = proportional_hazard_test(cph, data, time_transform="rank").summary
102
+ self.ph_test_ = ph
103
+ bad = ph.index[ph["p"] < self.alpha]
104
+ viol = sorted({c.split("[")[0] for c in bad if c.split("[")[0] in self.factors})
105
+ if viol:
106
+ self.strata_ = viol
107
+ rest = [f for f in self.factors if f not in viol]
108
+ X = self._design(d, rest)
109
+ data = pd.concat([X, d[viol].astype(str), d[[duration, event]]], axis=1)
110
+ cph = CoxPHFitter(penalizer=self.penalizer).fit(data, duration, event, strata=viol)
111
+ except Exception: # noqa: BLE001 - the check is advisory
112
+ pass
113
+ self.model_ = cph
114
+ s = cph.summary.copy()
115
+ s["p_holm"] = holm(s["p"].to_numpy())
116
+ s["interpretation"] = np.where(s["exp(coef)"] < 1, "longer duration", "shorter duration")
117
+ self.summary_ = s
118
+ # likelihood-ratio test of every factor (drop the factor and refit)
119
+ rows = []
120
+ tested = [f for f in self.factors if f not in self.strata_]
121
+ for f in tested:
122
+ others = [g for g in tested if g != f]
123
+ X0 = self._design(d, others)
124
+ cols = [d[self.strata_].astype(str)] if self.strata_ else []
125
+ data0 = pd.concat([X0] + cols + [d[[duration, event]]], axis=1)
126
+ if X0.shape[1] == 0 and not self.strata_:
127
+ ll0 = _null_loglik(d[duration].to_numpy(), d[event].to_numpy())
128
+ else:
129
+ ll0 = CoxPHFitter(penalizer=self.penalizer).fit(data0, duration, event,
130
+ strata=self.strata_ or None).log_likelihood_
131
+ lr = 2 * (cph.log_likelihood_ - ll0)
132
+ k = len(self.levels_[f]) - 1
133
+ rows.append({"factor": f, "LR": lr, "df": k, "p": float(stats.chi2.sf(lr, k))})
134
+ self.factor_tests_ = pd.DataFrame(rows).set_index("factor") if rows else pd.DataFrame()
135
+ self._data = d
136
+ self._duration, self._event = duration, event
137
+ return self
138
+
139
+ def level_durations(self, factor: str, quantile: float = 0.5) -> pd.DataFrame:
140
+ """Model-based median (or other quantile) duration of every level of ``factor``.
141
+
142
+ The other covariates are held at the sample means (numeric) and at the
143
+ reference levels (factors); ``excess`` is the difference from the
144
+ fastest level.
145
+ """
146
+ rows = []
147
+ base = {c: 0.0 for c in self.model_.params_.index}
148
+ for n in self.numeric:
149
+ base[n] = float(self._data[n].mean())
150
+ for lv in self.levels_[factor]:
151
+ x = dict(base)
152
+ col = f"{factor}[{lv}]"
153
+ if col in x:
154
+ x[col] = 1.0
155
+ X = pd.DataFrame([x])
156
+ if self.strata_:
157
+ for s in self.strata_:
158
+ X[s] = self._data[s].astype(str).mode().iloc[0]
159
+ sf = self.model_.predict_survival_function(X)
160
+ tt = sf.index.to_numpy()
161
+ v = sf.iloc[:, 0].to_numpy()
162
+ hit = np.nonzero(v <= 1 - quantile)[0]
163
+ rows.append({"level": lv, "n": int((self._data[factor].astype(str) == lv).sum()),
164
+ "duration": float(tt[hit[0]]) if hit.size else np.inf})
165
+ out = pd.DataFrame(rows).set_index("level")
166
+ out["excess"] = out["duration"] - out["duration"].min()
167
+ return out.sort_values("duration", ascending=False)
168
+
169
+
170
+ def _null_loglik(t, e):
171
+ """Cox partial log-likelihood with no covariates (Efron ties, as in lifelines)."""
172
+ order = np.argsort(t)
173
+ t, e = t[order], e[order]
174
+ ll = 0.0
175
+ for u in np.unique(t[e > 0]):
176
+ d = np.sum((t == u) & (e > 0))
177
+ r = np.sum(t >= u)
178
+ ll -= float(np.sum(np.log(r - np.arange(d))))
179
+ return ll
survml/competing.py ADDED
@@ -0,0 +1,177 @@
1
+ r"""Competing-risks regression: the Fine–Gray proportional subdistribution hazards model.
2
+
3
+ When a subject can fail from several causes, the probability of failing from
4
+ cause :math:`c` by time :math:`t` is the cumulative incidence
5
+ :math:`F_c(t\mid\mathbf x)`. Fine and Gray (1999, JASA 94: 496–509) model its
6
+ subdistribution hazard
7
+
8
+ .. math:: \lambda_c(t\mid\mathbf x)=\lambda_{c,0}(t)\exp(\mathbf x^\top\boldsymbol\beta),\qquad
9
+ F_c(t\mid\mathbf x)=1-\exp\bigl[-\Lambda_{c,0}(t)e^{\mathbf x^\top\boldsymbol\beta}\bigr],
10
+
11
+ so that :math:`\exp(\beta_k)` is a subdistribution hazard ratio that acts directly
12
+ on the cumulative incidence. Subjects who failed from a competing cause stay in
13
+ the risk set with the inverse-probability-of-censoring weight
14
+ :math:`w_i(u)=\hat G(u-)/\hat G(\min(u,T_i)-)`, where :math:`\hat G` is the
15
+ Kaplan–Meier curve of the censoring times. The estimator maximizes the weighted
16
+ partial likelihood (Breslow ties) by Newton–Raphson; the baseline cumulative
17
+ subdistribution hazard is the weighted Breslow estimator.
18
+
19
+ Neither :mod:`lifelines` nor :mod:`sksurv` fits this model; survml's version
20
+ is checked against simulation from the Fine–Gray design and against the
21
+ Aalen–Johansen estimator (which it reproduces without covariates).
22
+
23
+ The robust (sandwich) variance uses the score residuals of the weighted
24
+ partial likelihood and treats :math:`\hat G` as known, which ignores a usually
25
+ small term of the exact variance of Fine and Gray.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import numpy as np
31
+ import pandas as pd
32
+ from scipy import stats
33
+
34
+ from ._utils import as_frame, check_surv, step_eval
35
+ from .core import KaplanMeier
36
+
37
+ __all__ = ["FineGray"]
38
+
39
+
40
+ class FineGray:
41
+ """Fine–Gray proportional subdistribution hazards regression.
42
+
43
+ Parameters
44
+ ----------
45
+ cause : int
46
+ Cause of interest (event code).
47
+ penalizer : float
48
+ Ridge penalty :math:`\\tfrac12\\,\\mathrm{penalizer}\\,\\|\\beta\\|^2` (stabilizes
49
+ separated data; 0 = maximum likelihood).
50
+ max_iter, tol : int, float
51
+ Newton–Raphson stopping rule.
52
+ conf_level : float
53
+
54
+ Attributes
55
+ ----------
56
+ coef_ : ndarray
57
+ se_, robust_se_ : ndarray
58
+ Model-based and sandwich standard errors.
59
+ summary_ : DataFrame
60
+ Coefficients, subdistribution hazard ratios, robust SE, z, p and CI.
61
+ baseline_ : DataFrame
62
+ Event times and :math:`\\hat\\Lambda_{c,0}`.
63
+ """
64
+
65
+ def __init__(self, cause: int = 1, penalizer: float = 0.0, max_iter: int = 50, tol: float = 1e-9,
66
+ conf_level: float = 0.95):
67
+ self.cause = cause
68
+ self.penalizer = penalizer
69
+ self.max_iter = max_iter
70
+ self.tol = tol
71
+ self.conf_level = conf_level
72
+
73
+ def _weights_matrix(self, t, e, ut):
74
+ """Risk-set weights w_i(u) for every event time u (K × n)."""
75
+ cens = KaplanMeier().fit(t, (e == 0).astype(int))
76
+ # G(u-) : value just before u
77
+ G_minus = lambda u: step_eval(cens.timeline_, cens.survival_, np.nextafter(u, -np.inf)) # noqa: E731
78
+ Gu = G_minus(ut)
79
+ Gt = G_minus(t)
80
+ W = np.zeros((ut.size, t.size))
81
+ at_risk = t[None, :] >= ut[:, None]
82
+ comp = (e[None, :] > 0) & (e[None, :] != self.cause) & (t[None, :] < ut[:, None])
83
+ with np.errstate(divide="ignore", invalid="ignore"):
84
+ ratio = np.where(Gt[None, :] > 0, Gu[:, None] / Gt[None, :], 0.0)
85
+ W[at_risk] = 1.0
86
+ W[comp] = np.minimum(ratio[comp], 1.0)
87
+ return W
88
+
89
+ def fit(self, X, time, event):
90
+ """Fit the model. ``X``: covariates (array or DataFrame); ``event``: 0 censored, 1.. causes."""
91
+ Xf = as_frame(X, "x")
92
+ self.feature_names_ = [str(c) for c in Xf.columns]
93
+ Z = Xf.to_numpy(dtype=float)
94
+ t, e, _ = check_surv(time, event)
95
+ self._mean = Z.mean(0)
96
+ Zc = Z - self._mean
97
+ ev = e == self.cause
98
+ ut = np.unique(t[ev])
99
+ W = self._weights_matrix(t, e, ut)
100
+ D = np.vstack([np.bincount(np.searchsorted(ut, t[ev]), minlength=ut.size)]).ravel().astype(float)
101
+ Dz = np.zeros((ut.size, Zc.shape[1]))
102
+ np.add.at(Dz, np.searchsorted(ut, t[ev]), Zc[ev])
103
+ p = Zc.shape[1]
104
+ beta = np.zeros(p)
105
+ ll_old = -np.inf
106
+ for it in range(self.max_iter):
107
+ eta = Zc @ beta
108
+ r = np.exp(eta - eta.max())
109
+ WR = W * r[None, :]
110
+ S0 = WR.sum(1)
111
+ S1 = WR @ Zc
112
+ S2 = np.einsum("kn,ni,nj->kij", WR, Zc, Zc, optimize=True)
113
+ ll = float(np.sum(Dz @ beta) - np.sum(D * (np.log(S0) + eta.max()))) - 0.5 * self.penalizer * beta @ beta
114
+ xbar = S1 / S0[:, None]
115
+ U = (Dz - D[:, None] * xbar).sum(0) - self.penalizer * beta
116
+ I = np.einsum("k,kij->ij", D / S0, S2) - np.einsum("k,ki,kj->ij", D, xbar, xbar) \
117
+ + self.penalizer * np.eye(p)
118
+ step = np.linalg.solve(I, U)
119
+ # step halving
120
+ h = 1.0
121
+ while h > 1e-6:
122
+ nb = beta + h * step
123
+ eta2 = Zc @ nb
124
+ r2 = np.exp(eta2 - eta2.max())
125
+ ll2 = float(np.sum(Dz @ nb) - np.sum(D * (np.log((W * r2[None, :]).sum(1)) + eta2.max()))) \
126
+ - 0.5 * self.penalizer * nb @ nb
127
+ if ll2 >= ll - 1e-12:
128
+ break
129
+ h /= 2
130
+ beta = nb
131
+ if abs(ll2 - ll_old) < self.tol * (1 + abs(ll2)) and np.max(np.abs(h * step)) < 1e-7:
132
+ break
133
+ ll_old = ll2
134
+ self.n_iter_ = it + 1
135
+ eta = Zc @ beta
136
+ r = np.exp(eta)
137
+ WR = W * r[None, :]
138
+ S0 = WR.sum(1)
139
+ S1 = WR @ Zc
140
+ S2 = np.einsum("kn,ni,nj->kij", WR, Zc, Zc, optimize=True)
141
+ xbar = S1 / S0[:, None]
142
+ I = np.einsum("k,kij->ij", D / S0, S2) - np.einsum("k,ki,kj->ij", D, xbar, xbar) + self.penalizer * np.eye(p)
143
+ Iinv = np.linalg.inv(I)
144
+ # score residuals
145
+ resid = np.zeros_like(Zc)
146
+ pos = np.searchsorted(ut, t[ev])
147
+ resid[ev] += Zc[ev] - xbar[pos]
148
+ dlam = D / S0 # K
149
+ resid -= r[:, None] * (np.einsum("kn,k,ni->ni", W, dlam, Zc) - np.einsum("kn,k,ki->ni", W, dlam, xbar))
150
+ B = resid.T @ resid
151
+ self.coef_ = beta
152
+ self.loglik_ = ll2
153
+ self.information_ = I
154
+ self.covariance_ = Iinv
155
+ self.robust_covariance_ = Iinv @ B @ Iinv
156
+ self.se_ = np.sqrt(np.diag(Iinv))
157
+ self.robust_se_ = np.sqrt(np.diag(self.robust_covariance_))
158
+ self.baseline_ = pd.DataFrame({"time": ut, "cumhaz": np.cumsum(D / S0)})
159
+ z = stats.norm.ppf(0.5 + self.conf_level / 2)
160
+ zs = beta / self.robust_se_
161
+ self.summary_ = pd.DataFrame({
162
+ "coef": beta, "shr": np.exp(beta), "se(robust)": self.robust_se_, "se(model)": self.se_, "z": zs,
163
+ "p": 2 * stats.norm.sf(np.abs(zs)), "shr lower": np.exp(beta - z * self.robust_se_),
164
+ "shr upper": np.exp(beta + z * self.robust_se_)}, index=self.feature_names_)
165
+ return self
166
+
167
+ def predict_cif(self, X, times) -> np.ndarray:
168
+ r""":math:`\hat F_c(t\mid\mathbf x)`, shape (n, len(times))."""
169
+ Z = as_frame(X, "x")[self.feature_names_].to_numpy(dtype=float) - self._mean
170
+ L0 = step_eval(self.baseline_["time"].to_numpy(), self.baseline_["cumhaz"].to_numpy(),
171
+ np.atleast_1d(times), left=0.0)
172
+ return 1.0 - np.exp(-np.outer(np.exp(Z @ self.coef_), L0))
173
+
174
+ def predict_risk(self, X) -> np.ndarray:
175
+ """Linear predictor (higher = larger cumulative incidence)."""
176
+ Z = as_frame(X, "x")[self.feature_names_].to_numpy(dtype=float) - self._mean
177
+ return Z @ self.coef_