Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add variance formula for Kaplan Meier estimator #678

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lifelines/fitters/kaplan_meier_fitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ def fit(
setattr(self, secondary_estimate_name, pd.DataFrame(1 - np.exp(log_estimate), columns=[self._label]))

self.__estimate = getattr(self, primary_estimate_name)
self.variance_ = self._greenwood_variance(cumulative_sq_[:,None])
self.confidence_interval_ = self._bounds(cumulative_sq_[:, None], alpha, ci_labels)
self.median_ = median_survival_times(self.__estimate, left_censorship=left_censorship)
self._cumulative_sq_ = cumulative_sq_
Expand Down Expand Up @@ -288,6 +289,15 @@ def _bounds(self, cumulative_sq_, alpha, ci_labels):
df[ci_labels[0]] = np.exp(-np.exp(np.log(-v) + z * np.sqrt(cumulative_sq_) / v))
df[ci_labels[1]] = np.exp(-np.exp(np.log(-v) - z * np.sqrt(cumulative_sq_) / v))
return df

def _greenwood_variance(self, cumulative_sq_):
# This method calculates variance using the Greenwood formula.
# See https://www.math.wustl.edu/%7Esawyer/handouts/greenwood.pdf
df = pd.DataFrame(index=self.timeline)
v = self.__estimate.values

df["var"] = v**2 * cumulative_sq_
return df

def _additive_f(self, population, deaths):
np.seterr(invalid="ignore", divide="ignore")
Expand Down