INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Time vary coefficients
d: the dimension of the dataset
timelines: the observational times
constant: True for constant coefficients
independent: the number of coffients to set to 0 (covariate is ind of survival), or
a list of covariates to make indepent.
randgen: how scalar coefficients (betas... | def time_varying_coefficients(d, timelines, constant=False, independent=0, randgen=random.exponential):
"""
Time vary coefficients
d: the dimension of the dataset
timelines: the observational times
constant: True for constant coefficients
independent: the number of coffients to set to 0 (covari... |
n: the number of instances
d: the number of covariates
lifelines: the observational times
constant: make the coeffients constant (not time dependent)
n_binary: the number of binary covariates
model: from ["aalen", "cox"]
Returns:s
hazard rates: (t,n) dataframe,
coefficient... | def generate_hazard_rates(n, d, timelines, constant=False, independent=0, n_binary=0, model="aalen"):
"""
n: the number of instances
d: the number of covariates
lifelines: the observational times
constant: make the coeffients constant (not time dependent)
n_binary: the number of binary... |
Based on the hazard rates, compute random variables from the survival function
hazard_rates: (n,t) array of hazard rates
timelines: (t,) the observation times
size: the number to return, per hardard rate
censor: If True, adds uniform censoring between timelines.max() and 0
If a po... | def generate_random_lifetimes(hazard_rates, timelines, size=1, censor=None):
"""
Based on the hazard rates, compute random variables from the survival function
hazard_rates: (n,t) array of hazard rates
timelines: (t,) the observation times
size: the number to return, per hardard rate
cen... |
Given hazard rates, reconstruct the survival curves
Parameters
----------
hazard_rates: (n,t) array
timelines: (t,) the observational times
Returns
-------
t: survial curves, (n,t) array | def construct_survival_curves(hazard_rates, timelines):
"""
Given hazard rates, reconstruct the survival curves
Parameters
----------
hazard_rates: (n,t) array
timelines: (t,) the observational times
Returns
-------
t: survial curves, (n,t) array
"""
cumulative_hazards = cu... |
Parameters
----------
Fit the Aalen Additive model to a dataset.
Parameters
----------
df: DataFrame
a Pandas DataFrame with necessary columns `duration_col` and
`event_col` (see below), covariates columns, and special columns (weights).
`dura... | def fit(self, df, duration_col, event_col=None, weights_col=None, show_progress=False):
"""
Parameters
----------
Fit the Aalen Additive model to a dataset.
Parameters
----------
df: DataFrame
a Pandas DataFrame with necessary columns `duration_col` a... |
Returns the hazard rates for the individuals
Parameters
----------
X: a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the training data. | def predict_cumulative_hazard(self, X):
"""
Returns the hazard rates for the individuals
Parameters
----------
X: a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order ... |
Compute the expected lifetime, E[T], using covariates X.
Parameters
----------
X: a (n,d) covariate numpy array or DataFrame
If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the training data.
Return... | def predict_expectation(self, X):
"""
Compute the expected lifetime, E[T], using covariates X.
Parameters
----------
X: a (n,d) covariate numpy array or DataFrame
If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
... |
A wrapper around plotting. Matplotlib plot arguments can be passed in, plus:
Parameters
-----------
columns: string or list-like, optional
If not empty, plot a subset of columns from the ``cumulative_hazards_``. Default all.
loc:
iloc: slice, optional
specif... | def plot(self, columns=None, loc=None, iloc=None, **kwargs):
""""
A wrapper around plotting. Matplotlib plot arguments can be passed in, plus:
Parameters
-----------
columns: string or list-like, optional
If not empty, plot a subset of columns from the ``cumulative_haz... |
Using the epanechnikov kernel to smooth the hazard function, with sigma/bandwidth | def smoothed_hazards_(self, bandwidth=1):
"""
Using the epanechnikov kernel to smooth the hazard function, with sigma/bandwidth
"""
timeline = self._index.values
return pd.DataFrame(
np.dot(epanechnikov_kernel(timeline[:, None], timeline, bandwidth), self.hazards_.va... |
The concordance score (also known as the c-index) of the fit. The c-index is a generalization of the ROC AUC
to survival data, including censorships.
For this purpose, the ``score_`` is a measure of the predictive accuracy of the fitted model
onto the training dataset. It's analogous to the R^... | def score_(self):
"""
The concordance score (also known as the c-index) of the fit. The c-index is a generalization of the ROC AUC
to survival data, including censorships.
For this purpose, the ``score_`` is a measure of the predictive accuracy of the fitted model
onto the trai... |
Summary statistics describing the fit.
Returns
-------
df : DataFrame | def summary(self):
"""Summary statistics describing the fit.
Returns
-------
df : DataFrame
"""
df = pd.DataFrame(index=self.cumulative_hazards_.columns)
betas, se = self._compute_slopes()
df["slope(coef)"] = betas
df["se(slope(coef))"] = se
... |
Print summary statistics describing the fit, the coefficients, and the error bounds.
Parameters
-----------
decimals: int, optional (default=2)
specify the number of decimal places to show
kwargs:
print additional meta data in the output (useful to provide model ... | def print_summary(self, decimals=2, **kwargs):
"""
Print summary statistics describing the fit, the coefficients, and the error bounds.
Parameters
-----------
decimals: int, optional (default=2)
specify the number of decimal places to show
kwargs:
... |
Returns the median lifetimes for the individuals, by default. If the survival curve of an
individual does not cross 0.5, then the result is infinity.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
Parameters
----------
X: numpy array or DataFrame
... | def predict_percentile(self, X, ancillary_X=None, p=0.5):
"""
Returns the median lifetimes for the individuals, by default. If the survival curve of an
individual does not cross 0.5, then the result is infinity.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
... |
Predict the expectation of lifetimes, :math:`E[T | x]`.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the train... | def predict_expectation(self, X, ancillary_X=None):
"""
Predict the expectation of lifetimes, :math:`E[T | x]`.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a... |
Return the cumulative hazard rate of subjects in X at time points.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order a... | def predict_cumulative_hazard(self, X, times=None, ancillary_X=None):
"""
Return the cumulative hazard rate of subjects in X at time points.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
... |
Parameters
----------
durations: an array or pd.Series of length n -- duration of subject was observed for
event_observed: an array, or pd.Series, of length n. Integer indicator of distinct events. Must be
only positive integers, where 0 indicates censoring.
event_of_i... | def fit(
self,
durations,
event_observed,
event_of_interest,
timeline=None,
entry=None,
label="AJ_estimate",
alpha=None,
ci_labels=None,
weights=None,
): # pylint: disable=too-many-arguments,too-many-locals
"""
Paramete... |
Determine extent to jitter tied event times. Automatically called by fit if tied event times are detected | def _jitter(self, durations, event, jitter_level, seed=None):
"""Determine extent to jitter tied event times. Automatically called by fit if tied event times are detected
"""
np.random.seed(seed)
if jitter_level <= 0:
raise ValueError("The jitter level is less than zero, ple... |
Bounds are based on pg 411 of "Modelling Survival Data in Medical Research" David Collett 3rd Edition, which
is derived from Greenwood's variance estimator. Confidence intervals are obtained using the delta method
transformation of SE(log(-log(F_j))). This ensures that the confidence intervals all lie b... | def _bounds(self, lagged_survival, alpha, ci_labels):
"""Bounds are based on pg 411 of "Modelling Survival Data in Medical Research" David Collett 3rd Edition, which
is derived from Greenwood's variance estimator. Confidence intervals are obtained using the delta method
transformation of SE(log(... |
Checks for duplicated event times in the data set. This is narrowed to detecting duplicated event times
where the events are of different types | def _check_for_duplicates(durations, events):
"""Checks for duplicated event times in the data set. This is narrowed to detecting duplicated event times
where the events are of different types
"""
# Setting up DataFrame to detect duplicates
df = pd.DataFrame({"t": durations, "e":... |
This computes the sample size for needed power to compare two groups under a Cox
Proportional Hazard model.
Parameters
----------
power : float
power to detect the magnitude of the hazard ratio as small as that specified by postulated_hazard_ratio.
ratio_of_participants: ratio of participa... | def sample_size_necessary_under_cph(power, ratio_of_participants, p_exp, p_con, postulated_hazard_ratio, alpha=0.05):
"""
This computes the sample size for needed power to compare two groups under a Cox
Proportional Hazard model.
Parameters
----------
power : float
power to detect the ... |
This computes the power of the hypothesis test that the two groups, experiment and control,
have different hazards (that is, the relative hazard ratio is different from 1.)
Parameters
----------
n_exp : integer
size of the experiment group.
n_con : integer
size of the control grou... | def power_under_cph(n_exp, n_con, p_exp, p_con, postulated_hazard_ratio, alpha=0.05):
"""
This computes the power of the hypothesis test that the two groups, experiment and control,
have different hazards (that is, the relative hazard ratio is different from 1.)
Parameters
----------
n_exp : i... |
lowess(x, y, f=2./3., iter=3) -> yest
Lowess smoother: Robust locally weighted regression.
The lowess function fits a nonparametric regression curve to a scatterplot.
The arrays x and y contain an equal number of elements; each pair
(x[i], y[i]) defines a data point in the scatterplot. The function retu... | def lowess(x, y, f=2.0 / 3.0, iterations=3):
"""lowess(x, y, f=2./3., iter=3) -> yest
Lowess smoother: Robust locally weighted regression.
The lowess function fits a nonparametric regression curve to a scatterplot.
The arrays x and y contain an equal number of elements; each pair
(x[i], y[i]) define... |
Returns the time when a single survival function reaches the qth percentile.
Parameters
----------
q: float
a float between 0 and 1 that represents the time when the survival function hit's the qth percentile.
survival_function: Series or single-column DataFrame.
cdf: boolean, optional
... | def qth_survival_time(q, survival_function, cdf=False):
"""
Returns the time when a single survival function reaches the qth percentile.
Parameters
----------
q: float
a float between 0 and 1 that represents the time when the survival function hit's the qth percentile.
survival_function: ... |
Joins multiple event series together into DataFrames. A generalization of
`survival_table_from_events` to data with groups. Previously called `group_event_series` pre 0.2.3.
Parameters
----------
groups: a (n,) array
individuals' group ids.
durations: a (n,) array
durations of each ind... | def group_survival_table_from_events(
groups, durations, event_observed, birth_times=None, limit=-1
): # pylint: disable=too-many-locals
"""
Joins multiple event series together into DataFrames. A generalization of
`survival_table_from_events` to data with groups. Previously called `group_event_series`... |
Parameters
----------
death_times: (n,) array
represent the event times
event_observed: (n,) array
1 if observed event, 0 is censored event.
birth_times: a (n,) array, optional
representing when the subject was first observed. A subject's death event is then at [birth times + duration ... | def survival_table_from_events(
death_times,
event_observed,
birth_times=None,
columns=["removed", "observed", "censored", "entrance", "at_risk"],
weights=None,
collapse=False,
intervals=None,
): # pylint: disable=dangerous-default-value,too-many-locals
"""
Parameters
----------... |
This is the inverse of the function ``survival_table_from_events``.
Parameters
----------
survival_table: DataFrame
a pandas DataFrame with index as the durations and columns "observed" and "censored", referring to
the number of individuals that died and were censored at time t.
obse... | def survival_events_from_table(survival_table, observed_deaths_col="observed", censored_col="censored"):
"""
This is the inverse of the function ``survival_table_from_events``.
Parameters
----------
survival_table: DataFrame
a pandas DataFrame with index as the durations and columns "observ... |
This is a very flexible function for transforming arrays of start_times and end_times
to the proper format for lifelines: duration and event observation arrays.
Parameters
----------
start_times: an array, Series or DataFrame
iterable representing start times. These can be strings, or datetime ... | def datetimes_to_durations(
start_times, end_times, fill_date=datetime.today(), freq="D", dayfirst=False, na_values=None
):
"""
This is a very flexible function for transforming arrays of start_times and end_times
to the proper format for lifelines: duration and event observation arrays.
Parameters... |
r"""
Calculates the l1 log-loss of predicted event times to true event times for *non-censored*
individuals only.
.. math:: 1/N \sum_{i} |log(t_i) - log(q_i)|
Parameters
----------
event_times: a (n,) array of observed survival times.
predicted_event_times: a (n,) array of predicted s... | def l1_log_loss(event_times, predicted_event_times, event_observed=None):
r"""
Calculates the l1 log-loss of predicted event times to true event times for *non-censored*
individuals only.
.. math:: 1/N \sum_{i} |log(t_i) - log(q_i)|
Parameters
----------
event_times: a (n,) array of obs... |
r"""
Calculates the l2 log-loss of predicted event times to true event times for *non-censored*
individuals only.
.. math:: 1/N \sum_{i} (log(t_i) - log(q_i))**2
Parameters
----------
event_times: a (n,) array of observed survival times.
predicted_event_times: a (n,) array of predicte... | def l2_log_loss(event_times, predicted_event_times, event_observed=None):
r"""
Calculates the l2 log-loss of predicted event times to true event times for *non-censored*
individuals only.
.. math:: 1/N \sum_{i} (log(t_i) - log(q_i))**2
Parameters
----------
event_times: a (n,) array of ... |
Perform cross validation on a dataset. If multiple models are provided,
all models will train on each of the k subsets.
Parameters
----------
fitters: model
one or several objects which possess a method: ``fit(self, data, duration_col, event_col)``
Note that the last two arguments will be g... | def k_fold_cross_validation(
fitters,
df,
duration_col,
event_col=None,
k=5,
evaluation_measure=concordance_index,
predictor="predict_expectation",
predictor_kwargs={},
fitter_kwargs={},
): # pylint: disable=dangerous-default-value,too-many-arguments,too-many-locals
"""
Perf... |
Normalize X. If mean OR std is None, normalizes
X to have mean 0 and std 1. | def normalize(X, mean=None, std=None):
"""
Normalize X. If mean OR std is None, normalizes
X to have mean 0 and std 1.
"""
if mean is None or std is None:
mean = X.mean(0)
std = X.std(0)
return (X - mean) / std |
Also known as Tikhonov regularization. This solves the minimization problem:
min_{beta} ||(beta X - Y)||^2 + c1||beta||^2 + c2||beta - offset||^2
One can find more information here: http://en.wikipedia.org/wiki/Tikhonov_regularization
Parameters
----------
X: a (n,d) numpy array
Y: a (n,) num... | def ridge_regression(X, Y, c1=0.0, c2=0.0, offset=None, ix=None):
"""
Also known as Tikhonov regularization. This solves the minimization problem:
min_{beta} ||(beta X - Y)||^2 + c1||beta||^2 + c2||beta - offset||^2
One can find more information here: http://en.wikipedia.org/wiki/Tikhonov_regularizati... |
Called to compute the Kaplan Meier and Nelson-Aalen estimates. | def _additive_estimate(events, timeline, _additive_f, _additive_var, reverse):
"""
Called to compute the Kaplan Meier and Nelson-Aalen estimates.
"""
if reverse:
events = events.sort_index(ascending=False)
at_risk = events["entrance"].sum() - events["removed"].cumsum().shift(1).fillna(0... |
Cleans and confirms input to what lifelines expects downstream | def _preprocess_inputs(durations, event_observed, timeline, entry, weights):
"""
Cleans and confirms input to what lifelines expects downstream
"""
n = len(durations)
durations = np.asarray(pass_for_numeric_dtypes_or_raise_array(durations)).reshape((n,))
# set to all observed if event_observed... |
Use the utility `to_numeric` to check that x is convertible to numeric values, and then convert. Any errors
are reported back to the user.
Parameters
----------
x: list, array, Series, DataFrame
Notes
------
This actually allows objects like timedeltas (converted to microseconds), and stri... | def pass_for_numeric_dtypes_or_raise_array(x):
"""
Use the utility `to_numeric` to check that x is convertible to numeric values, and then convert. Any errors
are reported back to the user.
Parameters
----------
x: list, array, Series, DataFrame
Notes
------
This actually allows ob... |
This function takes a "flat" dataset (that is, non-time-varying), and converts it into a time-varying dataset
with static variables.
Useful if your dataset has variables that do not satisfy the proportional hazard assumption, and you need to create a
time-varying dataset to include interaction terms with t... | def to_episodic_format(df, duration_col, event_col, id_col=None, time_gaps=1):
"""
This function takes a "flat" dataset (that is, non-time-varying), and converts it into a time-varying dataset
with static variables.
Useful if your dataset has variables that do not satisfy the proportional hazard assump... |
This function converts a survival analysis DataFrame to a lifelines "long" format. The lifelines "long"
format is used in a common next function, ``add_covariate_to_timeline``.
Parameters
----------
df: DataFrame
a DataFrame in the standard survival analysis form (one for per observation, with ... | def to_long_format(df, duration_col):
"""
This function converts a survival analysis DataFrame to a lifelines "long" format. The lifelines "long"
format is used in a common next function, ``add_covariate_to_timeline``.
Parameters
----------
df: DataFrame
a DataFrame in the standard surv... |
This is a util function to help create a long form table tracking subjects' covariate changes over time. It is meant
to be used iteratively as one adds more and more covariates to track over time. Before using this function, it is recommended
to view the documentation at https://lifelines.readthedocs.io/en/late... | def add_covariate_to_timeline(
long_form_df,
cv,
id_col,
duration_col,
event_col,
start_col="start",
stop_col="stop",
add_enum=False,
overwrite=True,
cumulative_sum=False,
cumulative_sum_prefix="cumsum_",
delay=0,
): # pylint: disable=too-many-arguments
"""
This ... |
This is a helper function to handle binary event datastreams in a specific format and convert
it to a format that add_covariate_to_timeline will accept. For example, suppose you have a
dataset that looks like:
.. code:: python
id promotion movement raise
0 1 1.0 NaN ... | def covariates_from_event_matrix(df, id_col):
"""
This is a helper function to handle binary event datastreams in a specific format and convert
it to a format that add_covariate_to_timeline will accept. For example, suppose you have a
dataset that looks like:
.. code:: python
id promot... |
sometimes the exp. column can be too large | def format_exp_floats(decimals):
"""
sometimes the exp. column can be too large
"""
threshold = 10 ** 5
return (
lambda n: "{:.{prec}e}".format(n, prec=decimals) if n > threshold else "{:4.{prec}f}".format(n, prec=decimals)
) |
Parameters
----------
durations: an array, or pd.Series, of length n
duration subject was observed for
timeline:
return the best estimate at the values in timelines (positively increasing)
event_observed: an array, or pd.Series, of length n
True if the... | def fit(
self,
durations,
event_observed=None,
timeline=None,
entry=None,
label="BFH_estimate",
alpha=None,
ci_labels=None,
): # pylint: disable=too-many-arguments
"""
Parameters
----------
durations: an array, or pd.Se... |
Fit the model to a right-censored dataset
Parameters
----------
durations: an array, list, pd.DataFrame or pd.Series
length n -- duration subject was observed for
event_observed: an array, list, pd.DataFrame, or pd.Series, optional
True if the the death was ... | def fit(
self,
durations,
event_observed=None,
timeline=None,
entry=None,
label="KM_estimate",
left_censorship=False,
alpha=None,
ci_labels=None,
weights=None,
): # pylint: disable=too-many-arguments,too-many-locals
"""
... |
Fit the model to a left-censored dataset
Parameters
----------
durations: an array, list, pd.DataFrame or pd.Series
length n -- duration subject was observed for
event_observed: an array, list, pd.DataFrame, or pd.Series, optional
True if the the death was o... | def fit_left_censoring(
self,
durations,
event_observed=None,
timeline=None,
entry=None,
label="KM_estimate",
alpha=None,
ci_labels=None,
weights=None,
):
"""
Fit the model to a left-censored dataset
Parameters
... |
Parameters
----------
durations: an array, list, pd.DataFrame or pd.Series
length n -- duration subject was observed for
event_observed: an array, list, pd.DataFrame, or pd.Series, optional
True if the the death was observed, False if the event was lost (right-censor... | def _fit(
self,
durations,
event_observed=None,
timeline=None,
entry=None,
label="KM_estimate",
alpha=None,
ci_labels=None,
weights=None,
): # pylint: disable=too-many-arguments,too-many-locals
"""
Parameters
----------... |
Return a Pandas series of the predicted cumulative density at specific times
Parameters
-----------
times: iterable or float
Returns
--------
pd.Series | def cumulative_density_at_times(self, times, label=None):
"""
Return a Pandas series of the predicted cumulative density at specific times
Parameters
-----------
times: iterable or float
Returns
--------
pd.Series
"""
label = coalesce(la... |
Alias of ``plot`` | def plot_survival_function(self, **kwargs):
"""Alias of ``plot``"""
return _plot_estimate(
self,
estimate=self.survival_function_,
confidence_intervals=self.confidence_interval_survival_function_,
**kwargs
) |
Plots a pretty figure of {0}.{1}
Matplotlib plot arguments can be passed in inside the kwargs, plus
Parameters
-----------
show_censors: bool
place markers at censorship events. Default: False
censor_styles: bool
If show_censors, this dictionary will be ... | def plot_cumulative_density(self, **kwargs):
"""
Plots a pretty figure of {0}.{1}
Matplotlib plot arguments can be passed in inside the kwargs, plus
Parameters
-----------
show_censors: bool
place markers at censorship events. Default: False
censor_s... |
Fit the Cox Proportional Hazard model to a time varying dataset. Tied survival times
are handled using Efron's tie-method.
Parameters
-----------
df: DataFrame
a Pandas DataFrame with necessary columns `duration_col` and
`event_col`, plus other covariates. `durati... | def fit(
self,
df,
id_col,
event_col,
start_col="start",
stop_col="stop",
weights_col=None,
show_progress=False,
step_size=None,
robust=False,
strata=None,
initial_point=None,
): # pylint: disable=too-many-arguments
... |
Newton Rhaphson algorithm for fitting CPH model.
Parameters
----------
df: DataFrame
stop_times_events: DataFrame
meta information about the subjects history
show_progress: boolean, optional (default: True)
to show verbose output of convergence
s... | def _newton_rhaphson(
self,
df,
events,
start,
stop,
weights,
show_progress=False,
step_size=None,
precision=10e-6,
max_steps=50,
initial_point=None,
): # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too... |
Calculates the first and second order vector differentials, with respect to beta.
Returns
-------
hessian: (d, d) numpy array,
gradient: (d,) numpy array
log_likelihood: float | def _get_gradients(self, X, events, start, stop, weights, beta): # pylint: disable=too-many-locals
"""
Calculates the first and second order vector differentials, with respect to beta.
Returns
-------
hessian: (d, d) numpy array,
gradient: (d,) numpy array
log_l... |
r"""
This is equivalent to R's linear.predictors.
Returns the log of the partial hazard for the individuals, partial since the
baseline hazard is not included. Equal to :math:`(x - \bar{x})'\beta `
Parameters
----------
X: numpy array or DataFrame
a (n,d) co... | def predict_log_partial_hazard(self, X):
r"""
This is equivalent to R's linear.predictors.
Returns the log of the partial hazard for the individuals, partial since the
baseline hazard is not included. Equal to :math:`(x - \bar{x})'\beta `
Parameters
----------
X... |
Print summary statistics describing the fit, the coefficients, and the error bounds.
Parameters
-----------
decimals: int, optional (default=2)
specify the number of decimal places to show
kwargs:
print additional meta data in the output (useful to provide model ... | def print_summary(self, decimals=2, **kwargs):
"""
Print summary statistics describing the fit, the coefficients, and the error bounds.
Parameters
-----------
decimals: int, optional (default=2)
specify the number of decimal places to show
kwargs:
... |
approximate change in betas as a result of excluding ith row | def _compute_delta_beta(self, df, events, start, stop, weights):
""" approximate change in betas as a result of excluding ith row"""
score_residuals = self._compute_residuals(df, events, start, stop, weights) * weights[:, None]
naive_var = inv(self._hessian_)
delta_betas = -score_resid... |
Produces a visual representation of the coefficients, including their standard errors and magnitudes.
Parameters
----------
columns : list, optional
specify a subset of the columns to plot
errorbar_kwargs:
pass in additional plotting commands to matplotlib errorb... | def plot(self, columns=None, **errorbar_kwargs):
"""
Produces a visual representation of the coefficients, including their standard errors and magnitudes.
Parameters
----------
columns : list, optional
specify a subset of the columns to plot
errorbar_kwargs:
... |
Fit the Cox proportional hazard model to a dataset.
Parameters
----------
df: DataFrame
a Pandas DataFrame with necessary columns `duration_col` and
`event_col` (see below), covariates columns, and special columns (weights, strata).
`duration_col` refers to
... | def fit(
self,
df,
duration_col=None,
event_col=None,
show_progress=False,
initial_point=None,
strata=None,
step_size=None,
weights_col=None,
cluster_col=None,
robust=False,
batch_mode=None,
):
"""
Fit th... |
Newton Rhaphson algorithm for fitting CPH model.
Note
----
The data is assumed to be sorted on T!
Parameters
----------
X: (n,d) Pandas DataFrame of observations.
T: (n) Pandas Series representing observed durations.
E: (n) Pandas Series representing dea... | def _fit_model(
self,
X,
T,
E,
weights=None,
initial_point=None,
step_size=None,
precision=1e-07,
show_progress=True,
max_steps=50,
): # pylint: disable=too-many-statements,too-many-branches
"""
Newton Rhaphson algorith... |
Calculates the first and second order vector differentials, with respect to beta.
Note that X, T, E are assumed to be sorted on T!
A good explanation for Efron. Consider three of five subjects who fail at the time.
As it is not known a priori that who is the first to fail, so one-third of
... | def _get_efron_values_single(self, X, T, E, weights, beta):
"""
Calculates the first and second order vector differentials, with respect to beta.
Note that X, T, E are assumed to be sorted on T!
A good explanation for Efron. Consider three of five subjects who fail at the time.
... |
r"""
Let s_k be the kth schoenfeld residuals. Then E[s_k] = 0.
For tests of proportionality, we want to test if \beta_i(t) is \beta_i (constant) or not.
Let V_k be the contribution to the information matrix at time t_k. A main result from Grambsch and Therneau is that
\beta(t) = E[s_k*... | def _compute_scaled_schoenfeld(self, X, T, E, weights, index=None):
r"""
Let s_k be the kth schoenfeld residuals. Then E[s_k] = 0.
For tests of proportionality, we want to test if \beta_i(t) is \beta_i (constant) or not.
Let V_k be the contribution to the information matrix at time t_k.... |
A positive value of the residual shows an X value that is higher than expected at that death time. | def _compute_schoenfeld_within_strata(self, X, T, E, weights):
"""
A positive value of the residual shows an X value that is higher than expected at that death time.
"""
# TODO: the diff_against is gross
# This uses Efron ties.
n, d = X.shape
if not np.any(E):
... |
approximate change in betas as a result of excluding ith row. Good for finding outliers / specific
subjects that influence the model disproportionately. Good advice: don't drop these outliers, model them. | def _compute_delta_beta(self, X, T, E, weights, index=None):
"""
approximate change in betas as a result of excluding ith row. Good for finding outliers / specific
subjects that influence the model disproportionately. Good advice: don't drop these outliers, model them.
"""
score_... |
Summary statistics describing the fit.
Set alpha property in the object before calling.
Returns
-------
df : DataFrame
Contains columns coef, np.exp(coef), se(coef), z, p, lower, upper | def summary(self):
"""Summary statistics describing the fit.
Set alpha property in the object before calling.
Returns
-------
df : DataFrame
Contains columns coef, np.exp(coef), se(coef), z, p, lower, upper"""
ci = 1 - self.alpha
with np.errstate(inva... |
r"""
This is equivalent to R's linear.predictors.
Returns the log of the partial hazard for the individuals, partial since the
baseline hazard is not included. Equal to :math:`(x - mean(x_{train}))'\beta `
Parameters
----------
X: numpy array or DataFrame
a... | def predict_log_partial_hazard(self, X):
r"""
This is equivalent to R's linear.predictors.
Returns the log of the partial hazard for the individuals, partial since the
baseline hazard is not included. Equal to :math:`(x - mean(x_{train}))'\beta `
Parameters
----------
... |
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the training data.
times: iterable, optional
an itera... | def predict_cumulative_hazard(self, X, times=None):
"""
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as t... |
Predict the survival function for individuals, given their covariates. This assumes that the individual
just entered the study (that is, we do not condition on how long they have already lived for.)
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy a... | def predict_survival_function(self, X, times=None):
"""
Predict the survival function for individuals, given their covariates. This assumes that the individual
just entered the study (that is, we do not condition on how long they have already lived for.)
Parameters
----------
... |
Returns the median lifetimes for the individuals, by default. If the survival curve of an
individual does not cross 0.5, then the result is infinity.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
Parameters
----------
X: numpy array or DataFrame
... | def predict_percentile(self, X, p=0.5):
"""
Returns the median lifetimes for the individuals, by default. If the survival curve of an
individual does not cross 0.5, then the result is infinity.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
Parameters
... |
r"""
Compute the expected lifetime, :math:`E[T]`, using covariates X. This algorithm to compute the expectation is
to use the fact that :math:`E[T] = \int_0^\inf P(T > t) dt = \int_0^\inf S(t) dt`. To compute the integral, we use the trapizoidal rule to approximate the integral.
Caution
... | def predict_expectation(self, X):
r"""
Compute the expected lifetime, :math:`E[T]`, using covariates X. This algorithm to compute the expectation is
to use the fact that :math:`E[T] = \int_0^\inf P(T > t) dt = \int_0^\inf S(t) dt`. To compute the integral, we use the trapizoidal rule to approxim... |
Importantly, this agrees with what the KaplanMeierFitter produces. Ex:
Example
-------
>>> from lifelines.datasets import load_rossi
>>> from lifelines import CoxPHFitter, KaplanMeierFitter
>>> rossi = load_rossi()
>>> kmf = KaplanMeierFitter()
>>> kmf.fit(rossi[... | def _compute_baseline_survival(self):
"""
Importantly, this agrees with what the KaplanMeierFitter produces. Ex:
Example
-------
>>> from lifelines.datasets import load_rossi
>>> from lifelines import CoxPHFitter, KaplanMeierFitter
>>> rossi = load_rossi()
... |
Produces a visual representation comparing the baseline survival curve of the model versus
what happens when a covariate(s) is varied over values in a group. This is useful to compare
subjects' survival as we vary covariate(s), all else being held equal. The baseline survival
curve is equal to t... | def plot_covariate_groups(self, covariates, values, plot_baseline=True, **kwargs):
"""
Produces a visual representation comparing the baseline survival curve of the model versus
what happens when a covariate(s) is varied over values in a group. This is useful to compare
subjects' surviva... |
Use this function to test the proportional hazards assumption. See usage example at
https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%20hazard%20assumption.html
Parameters
-----------
training_df: DataFrame
the original DataFrame used in the call to... | def check_assumptions(
self, training_df, advice=True, show_plots=False, p_value_threshold=0.01, plot_n_bootstraps=10
):
"""
Use this function to test the proportional hazards assumption. See usage example at
https://lifelines.readthedocs.io/en/latest/jupyter_notebooks/Proportional%2... |
The concordance score (also known as the c-index) of the fit. The c-index is a generalization of the ROC AUC
to survival data, including censorships.
For this purpose, the ``score_`` is a measure of the predictive accuracy of the fitted model
onto the training dataset.
References
... | def score_(self):
"""
The concordance score (also known as the c-index) of the fit. The c-index is a generalization of the ROC AUC
to survival data, including censorships.
For this purpose, the ``score_`` is a measure of the predictive accuracy of the fitted model
onto the trai... |
Calculates the concordance index (C-index) between two series
of event times. The first is the real survival times from
the experimental data, and the other is the predicted survival
times from a model of some kind.
The c-index is the average of how often a model says X is greater than Y when, in the o... | def concordance_index(event_times, predicted_scores, event_observed=None):
"""
Calculates the concordance index (C-index) between two series
of event times. The first is the real survival times from
the experimental data, and the other is the predicted survival
times from a model of some kind.
... |
Find the concordance index in n * log(n) time.
Assumes the data has been verified by lifelines.utils.concordance_index first. | def _concordance_summary_statistics(
event_times, predicted_event_times, event_observed
): # pylint: disable=too-many-locals
"""Find the concordance index in n * log(n) time.
Assumes the data has been verified by lifelines.utils.concordance_index first.
"""
# Here's how this works.
#
# It ... |
Handle all pairs that exited at the same time as truth[first_ix].
Returns
-------
(pairs, correct, tied, next_ix)
new_pairs: The number of new comparisons performed
new_correct: The number of comparisons correctly predicted
next_ix: The next index that needs to be handled | def _handle_pairs(truth, pred, first_ix, times_to_compare):
"""
Handle all pairs that exited at the same time as truth[first_ix].
Returns
-------
(pairs, correct, tied, next_ix)
new_pairs: The number of new comparisons performed
new_correct: The number of comparisons correctly predict... |
Fallback, simpler method to compute concordance.
Assumes the data has been verified by lifelines.utils.concordance_index first. | def _naive_concordance_summary_statistics(event_times, predicted_event_times, event_observed):
"""
Fallback, simpler method to compute concordance.
Assumes the data has been verified by lifelines.utils.concordance_index first.
"""
num_pairs = 0.0
num_correct = 0.0
num_tied = 0.0
for a,... |
True if times can be compared. | def _valid_comparison(time_a, time_b, event_a, event_b):
"""True if times can be compared."""
if time_a == time_b:
# Ties are only informative if exactly one event happened
return event_a != event_b
if event_a and event_b:
return True
if event_a and time_a < time_b:
retur... |
Returns the median lifetimes for the individuals, by default. If the survival curve of an
individual does not cross ``p``, then the result is infinity.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
Parameters
----------
X: numpy array or DataFrame
... | def predict_percentile(self, X, ancillary_X=None, p=0.5):
"""
Returns the median lifetimes for the individuals, by default. If the survival curve of an
individual does not cross ``p``, then the result is infinity.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
... |
Returns the median lifetimes for the individuals. If the survival curve of an
individual does not cross 0.5, then the result is infinity.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
Parameters
----------
X: numpy array or DataFrame
a (n... | def predict_median(self, X, ancillary_X=None):
"""
Returns the median lifetimes for the individuals. If the survival curve of an
individual does not cross 0.5, then the result is infinity.
http://stats.stackexchange.com/questions/102986/percentile-loss-functions
Parameters
... |
Predict the expectation of lifetimes, :math:`E[T | x]`.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order as the train... | def predict_expectation(self, X, ancillary_X=None):
"""
Predict the expectation of lifetimes, :math:`E[T | x]`.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a... |
Return the cumulative hazard rate of subjects in X at time points.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
can be in any order. If a numpy array, columns must be in the
same order ... | def predict_cumulative_hazard(self, X, times=None, ancillary_X=None):
"""
Return the cumulative hazard rate of subjects in X at time points.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns
... |
Subtract the {0} of two {1} objects.
Parameters
----------
other: an {1} fitted instance. | def subtract(self, other):
"""
Subtract the {0} of two {1} objects.
Parameters
----------
other: an {1} fitted instance.
"""
self_estimate = getattr(self, self._estimate_name)
other_estimate = getattr(other, other._estimate_name)
new_index = np.co... |
Predict the {0} at certain point in time. Uses a linear interpolation if
points in time are not in the index.
Parameters
----------
times: a scalar or an array of times to predict the value of {0} at.
Returns
-------
predictions: a scalar if time is a scalar, a ... | def predict(self, times):
"""
Predict the {0} at certain point in time. Uses a linear interpolation if
points in time are not in the index.
Parameters
----------
times: a scalar or an array of times to predict the value of {0} at.
Returns
-------
... |
Return a DataFrame, with index equal to survival_function_, that estimates the median
duration remaining until the death event, given survival up until time t. For example, if an
individual exists until age 1, their expected life remaining *given they lived to time 1*
might be 9 years.
... | def _conditional_time_to_event_(self):
"""
Return a DataFrame, with index equal to survival_function_, that estimates the median
duration remaining until the death event, given survival up until time t. For example, if an
individual exists until age 1, their expected life remaining *give... |
This computes the confidence intervals of a transform of the parameters. Ex: take
the fitted parameters, a function/transform and the variance matrix and give me
back confidence intervals of the transform.
Parameters
-----------
transform: function
must a function of... | def _compute_confidence_bounds_of_transform(self, transform, alpha, ci_labels):
"""
This computes the confidence intervals of a transform of the parameters. Ex: take
the fitted parameters, a function/transform and the variance matrix and give me
back confidence intervals of the transform... |
Summary statistics describing the fit.
Returns
-------
df : pd.DataFrame
Contains columns coef, exp(coef), se(coef), z, p, lower, upper
See Also
--------
``print_summary`` | def summary(self):
"""
Summary statistics describing the fit.
Returns
-------
df : pd.DataFrame
Contains columns coef, exp(coef), se(coef), z, p, lower, upper
See Also
--------
``print_summary``
"""
ci = 1 - self.alpha
... |
Print summary statistics describing the fit, the coefficients, and the error bounds.
Parameters
-----------
decimals: int, optional (default=2)
specify the number of decimal places to show
kwargs:
print additional metadata in the output (useful to provide model n... | def print_summary(self, decimals=2, **kwargs):
"""
Print summary statistics describing the fit, the coefficients, and the error bounds.
Parameters
-----------
decimals: int, optional (default=2)
specify the number of decimal places to show
kwargs:
... |
Parameters
----------
durations: an array, or pd.Series
length n, duration subject was observed for
event_observed: numpy array or pd.Series, optional
length n, True if the the death was observed, False if the event was lost (right-censored). Defaults all True if event_observ... | def fit(
self,
durations,
event_observed=None,
timeline=None,
label=None,
alpha=None,
ci_labels=None,
show_progress=False,
entry=None,
weights=None,
left_censorship=False,
): # pylint: disable=too-many-arguments
"""
... |
Fit the model to a left-censored dataset
Parameters
----------
durations: an array, or pd.Series
length n, duration subject was observed for
event_observed: numpy array or pd.Series, optional
length n, True if the the death was observed, False if the event was lost (... | def fit_left_censoring(
self,
durations,
event_observed=None,
timeline=None,
label=None,
alpha=None,
ci_labels=None,
show_progress=False,
entry=None,
weights=None,
): # pylint: disable=too-many-arguments
"""
Fit the mod... |
Fit the model to an interval censored dataset.
Parameters
----------
lower_bound: an array, or pd.Series
length n, the start of the period the subject experienced the event in.
upper_bound: an array, or pd.Series
length n, the end of the period the subject experience... | def fit_interval_censoring(
self,
lower_bound,
upper_bound,
event_observed=None,
timeline=None,
label=None,
alpha=None,
ci_labels=None,
show_progress=False,
entry=None,
weights=None,
): # pylint: disable=too-many-arguments
... |
Return a Pandas series of the predicted survival value at specific times.
Parameters
-----------
times: iterable or float
values to return the survival function at.
label: string, optional
Rename the series returned. Useful for plotting.
Returns
----... | def survival_function_at_times(self, times, label=None):
"""
Return a Pandas series of the predicted survival value at specific times.
Parameters
-----------
times: iterable or float
values to return the survival function at.
label: string, optional
R... |
Return a Pandas series of the predicted cumulative density function (1-survival function) at specific times.
Parameters
-----------
times: iterable or float
values to return the survival function at.
label: string, optional
Rename the series returned. Useful for plot... | def cumulative_density_at_times(self, times, label=None):
"""
Return a Pandas series of the predicted cumulative density function (1-survival function) at specific times.
Parameters
-----------
times: iterable or float
values to return the survival function at.
... |
Return a Pandas series of the predicted cumulative hazard value at specific times.
Parameters
-----------
times: iterable or float
values to return the cumulative hazard at.
label: string, optional
Rename the series returned. Useful for plotting.
Returns
... | def cumulative_hazard_at_times(self, times, label=None):
"""
Return a Pandas series of the predicted cumulative hazard value at specific times.
Parameters
-----------
times: iterable or float
values to return the cumulative hazard at.
label: string, optional
... |
Return a Pandas series of the predicted hazard at specific times.
Parameters
-----------
times: iterable or float
values to return the hazard at.
label: string, optional
Rename the series returned. Useful for plotting.
Returns
--------
pd.Ser... | def hazard_at_times(self, times, label=None):
"""
Return a Pandas series of the predicted hazard at specific times.
Parameters
-----------
times: iterable or float
values to return the hazard at.
label: string, optional
Rename the series returned. Use... |
The confidence interval of the hazard. | def confidence_interval_hazard_(self):
"""
The confidence interval of the hazard.
"""
return self._compute_confidence_bounds_of_transform(self._hazard, self.alpha, self._ci_labels) |
The confidence interval of the survival function. | def confidence_interval_survival_function_(self):
"""
The confidence interval of the survival function.
"""
return self._compute_confidence_bounds_of_transform(self._survival_function, self.alpha, self._ci_labels) |
The confidence interval of the survival function. | def confidence_interval_cumulative_density_(self):
"""
The confidence interval of the survival function.
"""
return self._compute_confidence_bounds_of_transform(self._cumulative_density, self.alpha, self._ci_labels) |
Produce a pretty-plot of the estimate. | def plot(self, **kwargs):
"""
Produce a pretty-plot of the estimate.
"""
set_kwargs_drawstyle(kwargs, "default")
return _plot_estimate(
self, estimate=getattr(self, self._estimate_name), confidence_intervals=self.confidence_interval_, **kwargs
) |
Fit the accelerated failure time model to a right-censored dataset.
Parameters
----------
df: DataFrame
a Pandas DataFrame with necessary columns `duration_col` and
`event_col` (see below), covariates columns, and special columns (weights).
`duration_col` ref... | def fit(
self,
df,
duration_col,
event_col=None,
ancillary_df=None,
show_progress=False,
timeline=None,
weights_col=None,
robust=False,
initial_point=None,
entry_col=None,
):
"""
Fit the accelerated failure time ... |
Fit the accelerated failure time model to a left-censored dataset.
Parameters
----------
df: DataFrame
a Pandas DataFrame with necessary columns ``lower_bound_col``, ``upper_bound_col`` (see below),
and any other covariates or weights.
lower_bound_col: string
... | def fit_interval_censoring(
self,
df,
lower_bound_col,
upper_bound_col,
event_col=None,
ancillary_df=None,
show_progress=False,
timeline=None,
weights_col=None,
robust=False,
initial_point=None,
entry_col=None,
):
... |
Fit the accelerated failure time model to a left-censored dataset.
Parameters
----------
df: DataFrame
a Pandas DataFrame with necessary columns `duration_col` and
`event_col` (see below), covariates columns, and special columns (weights).
`duration_col` refe... | def fit_left_censoring(
self,
df,
duration_col=None,
event_col=None,
ancillary_df=None,
show_progress=False,
timeline=None,
weights_col=None,
robust=False,
initial_point=None,
entry_col=None,
):
"""
Fit the accel... |
See https://github.com/CamDavidsonPilon/lifelines/issues/664 | def _create_initial_point(self, Ts, E, entries, weights, Xs):
"""
See https://github.com/CamDavidsonPilon/lifelines/issues/664
"""
import lifelines # kinda hacky but lol
def transform_ith_param(model, i):
param = model._fitted_parameters_[i]
if param <= ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.