INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Override to substitute { ATTRIBUTE } by attributes of our _item.
def get_value(self, key, args, kwargs): """Override to substitute {ATTRIBUTE} by attributes of our _item.""" if hasattr(self._item, key): return getattr(self._item, key) return super().get_value(key, args, kwargs)
Override: meth: string. Formatter. format_field to have our default format_spec for: class: datetime. Datetime objects and to let None yield an empty string rather than None.
def format_field(self, value, format_spec): """Override :meth:`string.Formatter.format_field` to have our default format_spec for :class:`datetime.Datetime` objects, and to let None yield an empty string rather than ``None``.""" if isinstance(value, datetime) and not format_spec: ...
Override: meth: string. Formatter. vformat for character substitution in paths for Windows see issue #84.
def vformat(self, format_string, args, kwargs): """Override :meth:`string.Formatter.vformat` for character substitution in paths for Windows, see issue #84.""" ret = super().vformat(format_string, args, kwargs) if platform.system() == 'Windows': ret = ret.replace(':', '\ua789').repla...
Yield an anonymous otherwise equally - configured copy of an Instaloader instance ; Then copy its error log.
def anonymous_copy(self): """Yield an anonymous, otherwise equally-configured copy of an Instaloader instance; Then copy its error log.""" new_loader = Instaloader(self.context.sleep, self.context.quiet, self.context.user_agent, self.dirname_pattern, self.filename_patter...
Downloads and saves picture with given url under given directory with given timestamp. Returns true if file was actually downloaded i. e. updated.
def download_pic(self, filename: str, url: str, mtime: datetime, filename_suffix: Optional[str] = None, _attempt: int = 1) -> bool: """Downloads and saves picture with given url under given directory with given timestamp. Returns true, if file was actually downloaded, i.e. updated."...
Saves metadata JSON file of a structure.
def save_metadata_json(self, filename: str, structure: JsonExportable) -> None: """Saves metadata JSON file of a structure.""" if self.compress_json: filename += '.json.xz' else: filename += '.json' save_structure_to_file(structure, filename) if isinstance...
Updates picture caption/ Post metadata info
def save_caption(self, filename: str, mtime: datetime, caption: str) -> None: """Updates picture caption / Post metadata info""" def _elliptify(caption): pcaption = caption.replace('\n', ' ').strip() return '[' + ((pcaption[:29] + u"\u2026") if len(pcaption) > 31 else pcaption) +...
Save post location name and Google Maps link.
def save_location(self, filename: str, location: PostLocation, mtime: datetime) -> None: """Save post location name and Google Maps link.""" filename += '_location.txt' location_string = (location.name + "\n" + "https://maps.google.com/maps?q={0},{1}&ll={0},{1}\n".form...
Downloads and saves profile pic.
def download_profilepic(self, profile: Profile, _attempt: int = 1) -> None: """Downloads and saves profile pic.""" def _epoch_to_string(epoch: datetime) -> str: return epoch.strftime('%Y-%m-%d_%H-%M-%S_UTC') profile_pic_response = self.context.get_raw(profile.profile_pic_url) ...
Saves internally stored: class: requests. Session object.
def save_session_to_file(self, filename: Optional[str] = None) -> None: """Saves internally stored :class:`requests.Session` object. :param filename: Filename, or None to use default filename. """ if filename is None: filename = get_default_session_filename(self.context.user...
Internally stores: class: requests. Session object loaded from file.
def load_session_from_file(self, username: str, filename: Optional[str] = None) -> None: """Internally stores :class:`requests.Session` object loaded from file. If filename is None, the file with the default session path is loaded. :raises FileNotFoundError: If the file does not exist. ...
Log in to instagram with given username and password and internally store session object.
def login(self, user: str, passwd: str) -> None: """Log in to instagram with given username and password and internally store session object. :raises InvalidArgumentException: If the provided username does not exist. :raises BadCredentialsException: If the provided password is wrong. :r...
Format filename of a: class: Post or: class: StoryItem according to filename - pattern parameter.
def format_filename(self, item: Union[Post, StoryItem], target: Optional[str] = None): """Format filename of a :class:`Post` or :class:`StoryItem` according to ``filename-pattern`` parameter. .. versionadded:: 4.1""" return _PostPathFormatter(item).format(self.filename_pattern, target=target)
Download everything associated with one instagram post node i. e. picture caption and video.
def download_post(self, post: Post, target: str) -> bool: """ Download everything associated with one instagram post node, i.e. picture, caption and video. :param post: Post to download. :param target: Target name, i.e. profile name, #hashtag, :feed; for filename. :return: True ...
Get available stories from followees or all stories of users whose ID are given. Does not mark stories as seen. To use this one needs to be logged in
def get_stories(self, userids: Optional[List[int]] = None) -> Iterator[Story]: """Get available stories from followees or all stories of users whose ID are given. Does not mark stories as seen. To use this, one needs to be logged in :param userids: List of user IDs to be processed in te...
Download available stories from user followees or all stories of users whose ID are given. Does not mark stories as seen. To use this one needs to be logged in
def download_stories(self, userids: Optional[List[Union[int, Profile]]] = None, fast_update: bool = False, filename_target: Optional[str] = ':stories', storyitem_filter: Optional[Callable[[StoryItem], bool]] = None) -> N...
Download one user story.
def download_storyitem(self, item: StoryItem, target: str) -> bool: """Download one user story. :param item: Story item, as in story['items'] for story in :meth:`get_stories` :param target: Replacement for {target} in dirname_pattern and filename_pattern :return: True if something was d...
Get all highlights from a user. To use this one needs to be logged in.
def get_highlights(self, user: Union[int, Profile]) -> Iterator[Highlight]: """Get all highlights from a user. To use this, one needs to be logged in. .. versionadded:: 4.1 :param user: ID or Profile of the user whose highlights should get fetched. """ userid = user if...
Download available highlights from a user whose ID is given. To use this one needs to be logged in.
def download_highlights(self, user: Union[int, Profile], fast_update: bool = False, filename_target: Optional[str] = None, storyitem_filter: Optional[Callable[[StoryItem], bool]] = None) -> None: """ ...
Get Posts of the user s feed.
def get_feed_posts(self) -> Iterator[Post]: """Get Posts of the user's feed. :return: Iterator over Posts of the user's feed. """ data = self.context.graphql_query("d6f4427fbe92d846298cf93df0b937d3", {})["data"] while True: feed = data["user"]["edge_web_feed_timeli...
Download pictures from the user s feed.
def download_feed_posts(self, max_count: int = None, fast_update: bool = False, post_filter: Optional[Callable[[Post], bool]] = None) -> None: """ Download pictures from the user's feed. Example to download up to the 20 pics the user last liked:: loader ...
Download user s saved pictures.
def download_saved_posts(self, max_count: int = None, fast_update: bool = False, post_filter: Optional[Callable[[Post], bool]] = None) -> None: """Download user's saved pictures. :param max_count: Maximum count of pictures to download :param fast_update: If true, ab...
Get Posts which are listed by Instagram for a given Location.
def get_location_posts(self, location: str) -> Iterator[Post]: """Get Posts which are listed by Instagram for a given Location. :return: Iterator over Posts of a location's posts .. versionadded:: 4.2 """ has_next_page = True end_cursor = None while has_next_pa...
Download pictures of one location.
def download_location(self, location: str, max_count: Optional[int] = None, post_filter: Optional[Callable[[Post], bool]] = None, fast_update: bool = False) -> None: """Download pictures of one location. To download the last ...
Get Posts which are worthy of exploring suggested by Instagram.
def get_explore_posts(self) -> Iterator[Post]: """Get Posts which are worthy of exploring suggested by Instagram. :return: Iterator over Posts of the user's suggested posts. """ data = self.context.get_json('explore/', {}) yield from (Post(self.context, node) ...
Get Posts associated with a #hashtag.
def get_hashtag_posts(self, hashtag: str) -> Iterator[Post]: """Get Posts associated with a #hashtag.""" has_next_page = True end_cursor = None while has_next_page: if end_cursor: params = {'__a': 1, 'max_id': end_cursor} else: para...
Download pictures of one hashtag.
def download_hashtag(self, hashtag: str, max_count: Optional[int] = None, post_filter: Optional[Callable[[Post], bool]] = None, fast_update: bool = False) -> None: """Download pictures of one hashtag. To download the last 30 pic...
Download all posts where a profile is tagged.
def download_tagged(self, profile: Profile, fast_update: bool = False, target: Optional[str] = None, post_filter: Optional[Callable[[Post], bool]] = None) -> None: """Download all posts where a profile is tagged. .. versionadded:: 4.1""" if target...
Store ID of profile locally.
def save_profile_id(self, profile: Profile): """ Store ID of profile locally. .. versionadded:: 4.0.6 """ os.makedirs(self.dirname_pattern.format(profile=profile.username, target=profile.username), exist_ok=True) with open(...
Consult locally stored ID of profile with given name check whether ID matches and whether name has changed and return current name of the profile and store ID of profile.
def check_profile_id(self, profile_name: str) -> Profile: """ Consult locally stored ID of profile with given name, check whether ID matches and whether name has changed and return current name of the profile, and store ID of profile. :param profile_name: Profile name :return: I...
High - level method to download set of profiles.
def download_profiles(self, profiles: Set[Profile], profile_pic: bool = True, posts: bool = True, tagged: bool = False, highlights: bool = False, stories: bool = False, fast_update: bool = False, post_filter: Optiona...
Download one profile
def download_profile(self, profile_name: Union[str, Profile], profile_pic: bool = True, profile_pic_only: bool = False, fast_update: bool = False, download_stories: bool = False, download_stories_only: bool = False, down...
Checks to see if the current post has been committed.
def check_if_committed(self, filename: str) -> bool: """Checks to see if the current post has been committed. A post is considered committed if its json metadata file exists and is not malformed. .. versionadded:: 4.2 """ if os.path.isfile(filename + '.json.xz'): fi...
Logs in and internally stores session asking user for password interactively.
def interactive_login(self, username: str) -> None: """Logs in and internally stores session, asking user for password interactively. :raises LoginRequiredException: when in quiet mode. :raises InvalidArgumentException: If the provided username does not exist. :raises ConnectionExceptio...
Takes an -- post - filter =... or -- storyitem - filter =... filter specification and makes a filter_func Callable out of it.
def filterstr_to_filterfunc(filter_str: str, item_type: type): """Takes an --post-filter=... or --storyitem-filter=... filter specification and makes a filter_func Callable out of it.""" # The filter_str is parsed, then all names occurring in its AST are replaced by loads to post.<name>. A # function ...
Download set of profiles hashtags etc. and handle logging in and session files if desired.
def _main(instaloader: Instaloader, targetlist: List[str], username: Optional[str] = None, password: Optional[str] = None, sessionfile: Optional[str] = None, download_profile_pic: bool = True, download_posts=True, download_stories: bool = False, download_highlights: bool = False,...
beta * ( 1 - np. exp ( - alpha * ( t - beta )))
def exp_comp_(t, alpha=1, beta=1): """beta*(1 - np.exp(-alpha*(t-beta)))""" return beta * (1 - np.exp(-alpha * np.maximum(0, t - 10 * beta)))
beta * np. log ( alpha * ( t - beta ) + 1 )
def log_(t, alpha=1, beta=1): """beta*np.log(alpha*(t-beta)+1)""" return beta * np.log(alpha * np.maximum(0, t - 10 * beta) + 1)
Right censor the deaths uniformly lifetimes: ( n ) array of positive random variables max_: the max time a censorship can occur min_: the min time a censorship can occur
def right_censor_lifetimes(lifetimes, max_, min_=0): """ Right censor the deaths, uniformly lifetimes: (n,) array of positive random variables max_: the max time a censorship can occur min_: the min time a censorship can occur Returns The actual observations including uniform right ...
n: the number of instances integer d: the dimension of the covarites integer binary: a float between 0 and d the represents the binary covariates p: in binary the probability of 1
def generate_covariates(n, d, n_binary=0, p=0.5): """ n: the number of instances, integer d: the dimension of the covarites, integer binary: a float between 0 and d the represents the binary covariates p: in binary, the probability of 1 returns (n, d+1) """ # pylint: disable=chained-com...
Proportional hazards model.
def constant_coefficients(d, timelines, constant=True, independent=0): """ Proportional hazards model. 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 ...
Time vary coefficients
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 ]
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 postive number censors all events above...
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
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.
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
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.
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:
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.
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.
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.
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
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 ].
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.
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_interest: integer -- indicator for event of interest....
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 between 0 an...
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.
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. )
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 return...
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...
Find the times when one or more survival functions reach the qth percentile.
def qth_survival_times(q, survival_functions, cdf=False): """ Find the times when one or more survival functions reach the qth percentile. Parameters ---------- q: float or array a float between 0 and 1 that represents the time when the survival function hits the qth percentile. survival_...
Returns the time when a single survival function reaches the qth percentile.
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.
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 observed ]. If None ( default ) ...
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.
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.
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.
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.
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.
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:
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.
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.
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.
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/ latest/ S...
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:
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 the death was observed False if the event was lost ( right - censor...
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
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
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 - censored ). Defaults all True if event_observed == None tim...
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
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 }
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.
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.
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.
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
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.
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: ...
Produces a visual representation of the coefficients including their standard errors and magnitudes.
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: ...
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...
Fit the Cox proportional hazard model to a dataset.
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.
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!
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. ...
Assumes sorted on ascending on T Calculates the first and second order vector differentials with respect to beta.
def _get_efron_values_batch(self, X, T, E, weights, beta): # pylint: disable=too-many-locals """ Assumes sorted on ascending on T Calculates the first and second order vector differentials, with respect to beta. A good explanation for how Efron handles ties. Consider three of five subj...