#!/usr/bin/env python # coding: utf-8 # ## Custom regression models # # Like for univariate models, it is possible to create your own custom parametric survival models. Why might you want to do this? # # - Create new / extend AFT models using known probability distributions # - Create a piecewise model using domain knowledge about subjects # - Iterate and fit a more accurate parametric model # # *lifelines* has a very simple API to create custom parametric regression models. The author only needs to define the cumulative hazard function. For example, the cumulative hazard for the Exponential regression model looks like: # # $$ # H(t, x) = \frac{t}{\lambda(x)}\\ \lambda(x) = \exp{(\vec{\beta} \cdot \vec{x}^{\,T})} # $$ # # # # Below are some example custom models. # In[1]: from lifelines.fitters import ParametricRegressionFitter from autograd import numpy as np from lifelines.datasets import load_rossi class ExponentialAFTFitter(ParametricRegressionFitter): # this is necessary, and should always be a non-empty list of strings. _fitted_parameter_names = ['lambda_'] def _cumulative_hazard(self, params, T, Xs): # params is a dictionary that maps unknown parameters to a numpy vector. # Xs is a dictionary that maps unknown parameters to a numpy 2d array lambda_ = np.exp(np.dot(Xs['lambda_'], params['lambda_'])) return T / lambda_ rossi = load_rossi() rossi['intercept'] = 1.0 # the below variables maps dataframe columns to parameters regressors = { 'lambda_': rossi.columns } eaf = ExponentialAFTFitter().fit(rossi, 'week', 'arrest', regressors=regressors) eaf.print_summary() # In[2]: get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'retina'") from lifelines.fitters import ParametricRegressionFitter from autograd import numpy as np class PolynomialCumulativeHazard(ParametricRegressionFitter): _fitted_parameter_names = ['lambda1_', 'lambda2_', 'lambda3_'] def _cumulative_hazard(self, params, T, Xs): lambda1_ = np.exp(np.dot(Xs['lambda1_'], params['lambda1_'])) lambda2_ = np.exp(np.dot(Xs['lambda2_'], params['lambda2_'])) lambda3_ = np.exp(np.dot(Xs['lambda3_'], params['lambda3_'])) return (T/lambda1_) + (T/lambda2_)**2 + (T/lambda3_)**3 def _add_penalty(self, params, neg_ll): # authors can create their own non-traditional penalty functions too. # This penalty is an "information-pooling" penalty, see more about it here: # https://dataorigami.net/blogs/napkin-folding/churn params_stacked = np.stack(params.values()) coef_penalty = 0 if self.penalizer > 0: for i in range(params_stacked.shape[1] - 1): # assuming the intercept col is the last column... coef_penalty = coef_penalty + (params_stacked[:, i]).var() return neg_ll + self.penalizer * coef_penalty rossi = load_rossi() rossi['intercept'] = 1.0 # the below variables maps dataframe columns to parameters regressors = { 'lambda1_': rossi.columns, 'lambda2_': rossi.columns, 'lambda3_': rossi.columns } pf = PolynomialCumulativeHazard(penalizer=.5).fit(rossi, 'week', 'arrest', regressors=regressors) pf.print_summary() ax = plt.subplot() pf.plot(columns=['fin'], ax=ax) pf = PolynomialCumulativeHazard(penalizer=5.).fit(rossi, 'week', 'arrest', regressors=regressors) pf.plot(columns=['fin'], ax=ax, c="r") # ### Cure models # # Suppose in our population we have a subpopulation that will never experience the event of interest. Or, for some subjects the event will occur so far in the future that it's essentially at time infinity. In this case, the survival function for an individual should not asymptically approach zero, but _some positive value_. Models that describe this are sometimes called cure models (i.e. the subject is "cured" of death and hence no longer susceptible) or time-lagged conversion models. # # It would be nice to be able to use common survival models _and_ have some "cure" component. Let's suppose that for individuals that will experience the event of interest, their survival distrubtion is a Weibull, denoted $S_W(t)$. For a random selected individual in the population, thier survival curve, $S(t)$, is: # # $$ # \begin{align*} # S(t) = P(T > t) &= P(\text{cured}) P(T > t\;|\;\text{cured}) + P(\text{not cured}) P(T > t\;|\;\text{not cured}) \\ # &= p + (1-p) S_W(t) # \end{align*} # $$ # # Even though it's in an unconvential form, we can still determine the cumulative hazard (which is the negative logarithm of the survival function): # # $$ H(t) = -\log{\left(p + (1-p) S_W(t)\right)} $$ # In[26]: from autograd.scipy.special import expit class CureModel(ParametricRegressionFitter): _fitted_parameter_names = ["lambda_", "beta_", "rho_"] def _cumulative_hazard(self, params, T, Xs): c = expit(np.dot(Xs["beta_"], params["beta_"])) lambda_ = np.exp(np.dot(Xs["lambda_"], params["lambda_"])) rho_ = np.exp(np.dot(Xs["rho_"], params["rho_"])) sf = np.exp(-(T / lambda_) ** rho_) return -np.log((1 - c) + c * sf) swf = CureModel(penalizer=.1) rossi = load_rossi() rossi["intercept"] = 1.0 covariates = {"lambda_": rossi.columns, "rho_": ["intercept", "prio"], "beta_": rossi.columns} swf.fit(rossi, "week", event_col="arrest", regressors=covariates, timeline=np.arange(250)) swf.print_summary(2) # In[27]: swf.predict_survival_function(rossi.loc[::75]).plot(figsize=(12,6)) # In[30]: # what's the effect on the survival curve if I vary "age" fig, ax = plt.subplots(figsize=(12, 6)) swf.plot_covariate_groups(['age'], values=np.arange(20, 50, 5), cmap='coolwarm', ax=ax)