INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Starts the task thread.
def start(self): """ Starts the task thread. """ self._lock.acquire() try: if not self.is_alive(): self._thread = threading.Thread(target=self._target, name="raven.AsyncWorker") self._thread.setDaemon(True) self._thread....
Primary function which handles recursively transforming values via their serializers
def transform(self, value, **kwargs): """ Primary function which handles recursively transforming values via their serializers """ if value is None: return None objid = id(value) if objid in self.context: return '<...>' self.contex...
Takes the same arguments as the super function in :py:class:`Client` and extracts the keyword argument callback which will be called on asynchronous sending of the request :return: a 32-length string identifying this event
def capture(self, *args, **kwargs): """ Takes the same arguments as the super function in :py:class:`Client` and extracts the keyword argument callback which will be called on asynchronous sending of the request :return: a 32-length string identifying this event """ ...
Serializes the message and passes the payload onto ``send_encoded``.
def send(self, auth_header=None, callback=None, **data): """ Serializes the message and passes the payload onto ``send_encoded``. """ message = self.encode(data) return self.send_encoded(message, auth_header=auth_header, callback=callback)
Initialise a Tornado AsyncClient and send the request to the sentry server. If the callback is a callable, it will be called with the response.
def _send_remote(self, url, data, headers=None, callback=None): """ Initialise a Tornado AsyncClient and send the request to the sentry server. If the callback is a callable, it will be called with the response. """ if headers is None: headers = {} re...
Extracts the data required for 'sentry.interfaces.Http' from the current request being handled by the request handler :param return: A dictionary.
def get_sentry_data_from_request(self): """ Extracts the data required for 'sentry.interfaces.Http' from the current request being handled by the request handler :param return: A dictionary. """ return { 'request': { 'url': self.request.full_u...
Override implementation to report all exceptions to sentry. log_exception() is added in Tornado v3.1.
def log_exception(self, typ, value, tb): """Override implementation to report all exceptions to sentry. log_exception() is added in Tornado v3.1. """ rv = super(SentryMixin, self).log_exception(typ, value, tb) # Do not capture tornado.web.HTTPErrors outside the 500 range. ...
Override implementation to report all exceptions to sentry, even after self.flush() or self.finish() is called, for pre-v3.1 Tornado.
def send_error(self, status_code=500, **kwargs): """Override implementation to report all exceptions to sentry, even after self.flush() or self.finish() is called, for pre-v3.1 Tornado. """ if hasattr(super(SentryMixin, self), 'log_exception'): return super(SentryMixin, self)...
Given ``value``, recurse (using the parent serializer) to handle coercing of newly defined values.
def recurse(self, value, max_depth=6, _depth=0, **kwargs): """ Given ``value``, recurse (using the parent serializer) to handle coercing of newly defined values. """ string_max_length = kwargs.get('string_max_length', None) _depth += 1 if _depth >= max_depth: ...
Returns a public DSN which is consumable by raven-js >>> # Return scheme-less DSN >>> print client.get_public_dsn() >>> # Specify a scheme to use (http or https) >>> print client.get_public_dsn('https')
def get_public_dsn(self, scheme=None): """ Returns a public DSN which is consumable by raven-js >>> # Return scheme-less DSN >>> print client.get_public_dsn() >>> # Specify a scheme to use (http or https) >>> print client.get_public_dsn('https') """ if s...
Captures, processes and serializes an event into a dict object The result of ``build_msg`` should be a standardized dict, with all default values available.
def build_msg(self, event_type, data=None, date=None, time_spent=None, extra=None, stack=None, public_key=None, tags=None, fingerprint=None, **kwargs): """ Captures, processes and serializes an event into a dict object The result of ``build_msg`` should be a ...
Captures and processes an event and pipes it off to SentryClient.send. To use structured data (interfaces) with capture: >>> capture('raven.events.Message', message='foo', data={ >>> 'request': { >>> 'url': '...', >>> 'data': {}, >>> 'query_s...
def capture(self, event_type, data=None, date=None, time_spent=None, extra=None, stack=None, tags=None, sample_rate=None, **kwargs): """ Captures and processes an event and pipes it off to SentryClient.send. To use structured data (interfaces) with capture: ...
Log a reasonable representation of an event that should have been sent to Sentry
def _log_failed_submission(self, data): """ Log a reasonable representation of an event that should have been sent to Sentry """ message = data.pop('message', '<no message value>') output = [message] if 'exception' in data and 'stacktrace' in data['exception']['va...
Given an already serialized message, signs the message and passes the payload off to ``send_remote``.
def send_encoded(self, message, auth_header=None, **kwargs): """ Given an already serialized message, signs the message and passes the payload off to ``send_remote``. """ client_string = 'raven-python/%s' % (raven.VERSION,) if not auth_header: timestamp = tim...
Creates an event from an exception. >>> try: >>> exc_info = sys.exc_info() >>> client.captureException(exc_info) >>> finally: >>> del exc_info If exc_info is not provided, or is set to True, then this method will perform the ``exc_info = sys.exc_info...
def captureException(self, exc_info=None, **kwargs): """ Creates an event from an exception. >>> try: >>> exc_info = sys.exc_info() >>> client.captureException(exc_info) >>> finally: >>> del exc_info If exc_info is not provided, or is set to ...
Wrap a function or code block in try/except and automatically call ``.captureException`` if it raises an exception, then the exception is reraised. By default, it will capture ``Exception`` >>> @client.capture_exceptions >>> def foo(): >>> raise Exception() ...
def capture_exceptions(self, function_or_exceptions=None, **kwargs): """ Wrap a function or code block in try/except and automatically call ``.captureException`` if it raises an exception, then the exception is reraised. By default, it will capture ``Exception`` >>> @cl...
Creates an event for a SQL query. >>> client.captureQuery('SELECT * FROM foo')
def captureQuery(self, query, params=(), engine=None, **kwargs): """ Creates an event for a SQL query. >>> client.captureQuery('SELECT * FROM foo') """ return self.capture( 'raven.events.Query', query=query, params=params, engine=engine, **kwargs)
Records a breadcrumb with the current context. They will be sent with the next event.
def captureBreadcrumb(self, *args, **kwargs): """ Records a breadcrumb with the current context. They will be sent with the next event. """ # Note: framework integration should not call this method but # instead use the raven.breadcrumbs.record_breadcrumb function ...
It is possible to inject new schemes at runtime
def register_scheme(self, scheme, cls): """ It is possible to inject new schemes at runtime """ if scheme in self._schemes: raise DuplicateScheme() urlparse.register_scheme(scheme) # TODO (vng): verify the interface of the new class self._schemes[sche...
Requires Flask-Login (https://pypi.python.org/pypi/Flask-Login/) to be installed and setup.
def get_user_info(self, request): """ Requires Flask-Login (https://pypi.python.org/pypi/Flask-Login/) to be installed and setup. """ user_info = {} try: ip_address = request.access_route[0] except IndexError: ip_address = request.remote_a...
Determine how to retrieve actual data by using request.mimetype.
def get_http_info(self, request): """ Determine how to retrieve actual data by using request.mimetype. """ if self.is_json_type(request.mimetype): retriever = self.get_json_data else: retriever = self.get_form_data return self.get_http_info_with_re...
Exact method for getting http_info but with form data work around.
def get_http_info_with_retriever(self, request, retriever=None): """ Exact method for getting http_info but with form data work around. """ if retriever is None: retriever = self.get_form_data urlparts = urlparse.urlsplit(request.url) try: data =...
Configures logging to pipe to Sentry. - ``exclude`` is a list of loggers that shouldn't go to Sentry. For a typical Python install: >>> from raven.handlers.logging import SentryHandler >>> client = Sentry(...) >>> setup_logging(SentryHandler(client)) Within Django: >>> from raven.contri...
def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS): """ Configures logging to pipe to Sentry. - ``exclude`` is a list of loggers that shouldn't go to Sentry. For a typical Python install: >>> from raven.handlers.logging import SentryHandler >>> client = Sentry(...) >>> setup_logg...
Spawn an async request to a remote webserver.
def send(self, url, data, headers): """ Spawn an async request to a remote webserver. """ eventlet.spawn(self._send_payload, (url, data, headers))
Exact method for getting http_info but with form data work around.
def get_http_info_with_retriever(self, request, retriever): """ Exact method for getting http_info but with form data work around. """ urlparts = urlparse.urlsplit(request.url) try: data = retriever(request) except Exception: data = {} re...
Given something that closely resembles a dictionary, we attempt to coerce it into a propery dictionary.
def to_dict(dictish): """ Given something that closely resembles a dictionary, we attempt to coerce it into a propery dictionary. """ if hasattr(dictish, 'iterkeys'): m = dictish.iterkeys elif hasattr(dictish, 'keys'): m = dictish.keys else: raise ValueError(dictish) ...
Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable.
def iter_traceback_frames(tb): """ Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable. """ # Some versions of celery have hacked traceback objects that might # miss tb_frame. while tb and hasattr(tb, 'tb_frame'): ...
Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable.
def iter_stack_frames(frames=None): """ Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable. """ if not frames: frames = inspect.stack()[1:] for frame, lineno in ((f[0], f[2]) for f in r...
Removes various excess metadata from middle frames which go beyond ``frame_allowance``. Returns ``frames``.
def slim_frame_data(frames, frame_allowance=25): """ Removes various excess metadata from middle frames which go beyond ``frame_allowance``. Returns ``frames``. """ frames_len = 0 app_frames = [] system_frames = [] for frame in frames: frames_len += 1 if frame.get('i...
Given a list of frames, returns a list of stack information dictionary objects that are JSON-ready. We have to be careful here as certain implementations of the _Frame class do not contain the necessary data to lookup all of the information we want.
def get_stack_info(frames, transformer=transform, capture_locals=True, frame_allowance=25): """ Given a list of frames, returns a list of stack information dictionary objects that are JSON-ready. We have to be careful here as certain implementations of the _Frame class do not con...
Returns request data extracted from web.ctx.
def get_data_from_request(): """Returns request data extracted from web.ctx.""" return { 'request': { 'url': '%s://%s%s' % (web.ctx['protocol'], web.ctx['host'], web.ctx['path']), 'query_string': web.ctx.query, 'method': web.ctx.method, 'data': web.data(),...
Utility method for django's deprecated resolver.regex
def get_regex(resolver_or_pattern): """Utility method for django's deprecated resolver.regex""" try: regex = resolver_or_pattern.regex except AttributeError: regex = resolver_or_pattern.pattern.regex return regex
>>> fetch_package_version('sentry')
def fetch_package_version(dist_name): """ >>> fetch_package_version('sentry') """ try: # Importing pkg_resources can be slow, so only import it # if we need it. import pkg_resources except ImportError: # pkg_resource is not available on Google App Engine raise...
Convert a settings object (or dictionary) to parameters which may be passed to a new ``Client()`` instance.
def convert_options(settings, defaults=None): """ Convert a settings object (or dictionary) to parameters which may be passed to a new ``Client()`` instance. """ if defaults is None: defaults = {} if isinstance(settings, dict): def getopt(key, default=None): return s...
Access request.body, otherwise it might not be accessible later after request has been read/streamed
def process_request(self, request): """ Access request.body, otherwise it might not be accessible later after request has been read/streamed """ content_type = request.META.get('CONTENT_TYPE', '') for non_cacheable_type in self.non_cacheable_types: if non_cach...
Wrap a function or code block in try/except and automatically call ``.captureException`` if it raises an exception, then the exception is reraised. By default, it will capture ``Exception`` >>> @client.capture_exceptions >>> def foo(): >>> raise Exception() ...
def capture_exceptions(self, f=None, exceptions=None): # TODO: Ash fix kwargs in base """ Wrap a function or code block in try/except and automatically call ``.captureException`` if it raises an exception, then the exception is reraised. By default, it will capture ``Exception`...
Runs a thing once and once only.
def once(func): """Runs a thing once and once only.""" lock = threading.Lock() def new_func(*args, **kwargs): if new_func.called: return with lock: if new_func.called: return rv = func(*args, **kwargs) new_func.called = True ...
A reimplementation of Django's get_host, without the SuspiciousOperation check.
def get_host(request): """ A reimplementation of Django's get_host, without the SuspiciousOperation check. """ # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ( 'HTTP_X_FORWARDED_HOST' in request.META): host = request.META['HTTP...
Called when an exception has been raised in the code run by ZeroRPC
def server_inspect_exception(self, req_event, rep_event, task_ctx, exc_info): """ Called when an exception has been raised in the code run by ZeroRPC """ # Hide the zerorpc internal frames for readability, for a REQ/REP or # REQ/STREAM server the frames to hide are: # - c...
Install specified middleware
def install_middleware(middleware_name, lookup_names=None): """ Install specified middleware """ if lookup_names is None: lookup_names = (middleware_name,) # default settings.MIDDLEWARE is None middleware_attr = 'MIDDLEWARE' if getattr(settings, ...
Train survival model on given data and return its score on test data
def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params): """Train survival model on given data and return its score on test data""" X_train, y_train = _safe_split(est, x, y, train_index) train_params = fit_params.copy() # Training est.set_params(**para...
Fit estimator. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censorin...
def fit(self, X, y): """Fit estimator. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and t...
Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to neighbors of alpha in the list of alphas constructed during training.
def _interpolate_coefficients(self, alpha): """Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to neighbors of alpha in the list of alphas constructed during training.""" exact = False coef_idx = None for i, val in enumerate(self....
The linear predictor of the model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Test data of which to calculate log-likelihood from alpha : float, optional Constant that multiplies the penalty terms. If the same alpha was used during tra...
def predict(self, X, alpha=None): """The linear predictor of the model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Test data of which to calculate log-likelihood from alpha : float, optional Constant that multiplies the penalty...
Predict cumulative hazard function. Only available if :meth:`fit` has been called with `fit_baseline_model = True`. The cumulative hazard function for an individual with feature vector :math:`x_\\alpha` is defined as .. math:: H(t \\mid x_\\alpha) = \\exp(x_\\alpha^\\top ...
def predict_cumulative_hazard_function(self, X, alpha=None): """Predict cumulative hazard function. Only available if :meth:`fit` has been called with `fit_baseline_model = True`. The cumulative hazard function for an individual with feature vector :math:`x_\\alpha` is defined as ...
Predict survival function. Only available if :meth:`fit` has been called with `fit_baseline_model = True`. The survival function for an individual with feature vector :math:`x_\\alpha` is defined as .. math:: S(t \\mid x_\\alpha) = S_0(t)^{\\exp(x_\\alpha^\\top \\beta)} ,...
def predict_survival_function(self, X, alpha=None): """Predict survival function. Only available if :meth:`fit` has been called with `fit_baseline_model = True`. The survival function for an individual with feature vector :math:`x_\\alpha` is defined as .. math:: ...
For each base estimator collect models trained on each fold
def _create_base_ensemble(self, out, n_estimators, n_folds): """For each base estimator collect models trained on each fold""" ensemble_scores = numpy.empty((n_estimators, n_folds)) base_ensemble = numpy.empty_like(ensemble_scores, dtype=numpy.object) for model, fold, score, est in out: ...
For each selected base estimator, average models trained on each fold
def _create_cv_ensemble(self, base_ensemble, idx_models_included, model_names=None): """For each selected base estimator, average models trained on each fold""" fitted_models = numpy.empty(len(idx_models_included), dtype=numpy.object) for i, idx in enumerate(idx_models_included): mod...
Takes special care of estimators using custom kernel function Parameters ---------- X : array, shape = (n_samples, n_features) Samples to pre-compute kernel matrix from. Returns ------- base_estimators : list Same as `self.base_estimators`, expec...
def _get_base_estimators(self, X): """Takes special care of estimators using custom kernel function Parameters ---------- X : array, shape = (n_samples, n_features) Samples to pre-compute kernel matrix from. Returns ------- base_estimators : list ...
Restore custom kernel functions of estimators for predictions
def _restore_base_estimators(self, kernel_cache, out, X, cv): """Restore custom kernel functions of estimators for predictions""" train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)} for idx, fold, _, est in out: if idx in kernel_cache: if no...
Create a cross-validated model by training a model for each fold with the same model parameters
def _fit_and_score_ensemble(self, X, y, cv, **fit_params): """Create a cross-validated model by training a model for each fold with the same model parameters""" fit_params_steps = self._split_fit_params(fit_params) folds = list(cv.split(X, y)) # Take care of custom kernel functions ...
Fit ensemble of models Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------- self
def fit(self, X, y=None, **fit_params): """Fit ensemble of models Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------...
Write ARFF file Parameters ---------- data : :class:`pandas.DataFrame` DataFrame containing data filename : string or file-like object Path to ARFF file or file-like object. In the latter case, the handle is closed by calling this function. relation_name : string, optional...
def writearff(data, filename, relation_name=None, index=True): """Write ARFF file Parameters ---------- data : :class:`pandas.DataFrame` DataFrame containing data filename : string or file-like object Path to ARFF file or file-like object. In the latter case, the handle is ...
Write header containing attribute names and types
def _write_header(data, fp, relation_name, index): """Write header containing attribute names and types""" fp.write("@relation {0}\n\n".format(relation_name)) if index: data = data.reset_index() attribute_names = _sanitize_column_names(data) for column, series in data.iteritems(): ...
Replace illegal characters with underscore
def _sanitize_column_names(data): """Replace illegal characters with underscore""" new_names = {} for name in data.columns: new_names[name] = _ILLEGAL_CHARACTER_PAT.sub("_", name) return new_names
If string has a space, wrap it in double quotes and remove/escape illegal characters
def _check_str_value(x): """If string has a space, wrap it in double quotes and remove/escape illegal characters""" if isinstance(x, str): # remove commas, and single quotation marks since loadarff cannot deal with it x = x.replace(",", ".").replace(chr(0x2018), "'").replace(chr(0x2019), "'") ...
Write categories of a categorical/nominal attribute
def _write_attribute_categorical(series, fp): """Write categories of a categorical/nominal attribute""" if is_categorical_dtype(series.dtype): categories = series.cat.categories string_values = _check_str_array(categories) else: categories = series.dropna().unique() string_va...
Write the data section
def _write_data(data, fp): """Write the data section""" fp.write("@data\n") def to_str(x): if pandas.isnull(x): return '?' else: return str(x) data = data.applymap(to_str) n_rows = data.shape[0] for i in range(n_rows): str_values = list(data.iloc...
Fit base estimators. Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------- self
def fit(self, X, y=None, **fit_params): """Fit base estimators. Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------- ...
Perform prediction. Only available of the meta estimator has a predict method. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data with samples to predict. Returns ------- prediction : array, shape = (n_samples, n_dim) ...
def predict(self, X): """Perform prediction. Only available of the meta estimator has a predict method. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data with samples to predict. Returns ------- prediction : array, s...
Perform prediction. Only available of the meta estimator has a predict_proba method. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data with samples to predict. Returns ------- prediction : ndarray, shape = (n_samples, n_dim)...
def predict_proba(self, X): """Perform prediction. Only available of the meta estimator has a predict_proba method. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data with samples to predict. Returns ------- predictio...
Perform prediction. Only available of the meta estimator has a predict_log_proba method. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data with samples to predict. Returns ------- prediction : ndarray, shape = (n_samples, n_...
def predict_log_proba(self, X): """Perform prediction. Only available of the meta estimator has a predict_log_proba method. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data with samples to predict. Returns ------- p...
Perform Z-Normalization on each numeric column of the given table. Parameters ---------- table : pandas.DataFrame or numpy.ndarray Data to standardize. with_std : bool, optional, default: True If ``False`` data is only centered and not converted to unit variance. Returns -----...
def standardize(table, with_std=True): """ Perform Z-Normalization on each numeric column of the given table. Parameters ---------- table : pandas.DataFrame or numpy.ndarray Data to standardize. with_std : bool, optional, default: True If ``False`` data is only centered and not...
Encode categorical columns with `M` categories into `M-1` columns according to the one-hot scheme. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. columns : list-like, optional, default: None Column names in the DataFrame to be encoded. ...
def encode_categorical(table, columns=None, **kwargs): """ Encode categorical columns with `M` categories into `M-1` columns according to the one-hot scheme. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. columns : list-like, optional, defa...
Encode categorical columns to numeric by converting each category to an integer value. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. Returns ------- encoded : pandas.DataFrame Table with categorical columns encoded as numeric. ...
def categorical_to_numeric(table): """Encode categorical columns to numeric by converting each category to an integer value. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. Returns ------- encoded : pandas.DataFrame Table with ca...
Build a survival support vector machine model from training data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator a...
def fit(self, X, y, sample_weight=None): """Build a survival support vector machine model from training data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array...
Check that array correctly represents an outcome for survival analysis. Parameters ---------- y_or_event : structured array with two fields, or boolean array If a structured array, it must contain the binary event indicator as first field, and time of event or time of censoring as s...
def check_y_survival(y_or_event, *args, allow_all_censored=False): """Check that array correctly represents an outcome for survival analysis. Parameters ---------- y_or_event : structured array with two fields, or boolean array If a structured array, it must contain the binary event indicator ...
Check that all arrays have consistent first dimensions. Parameters ---------- X : array-like Data matrix containing feature vectors. y : structured array with two fields A structured array containing the binary event indicator as first field, and time of event or time of censor...
def check_arrays_survival(X, y, **kwargs): """Check that all arrays have consistent first dimensions. Parameters ---------- X : array-like Data matrix containing feature vectors. y : structured array with two fields A structured array containing the binary event indicator a...
Alternative to :func:`pandas.concat` that preserves categorical variables. Parameters ---------- objs : a sequence or mapping of Series, DataFrame, or Panel objects If a dict is passed, the sorted keys will be used as the `keys` argument, unless it is passed, in which case the values will b...
def safe_concat(objs, *args, **kwargs): """Alternative to :func:`pandas.concat` that preserves categorical variables. Parameters ---------- objs : a sequence or mapping of Series, DataFrame, or Panel objects If a dict is passed, the sorted keys will be used as the `keys` argument, unles...
Create structured array. Parameters ---------- event : array-like Event indicator. A boolean array or array with values 0/1. time : array-like Observed time. name_event : str|None Name of event, optional, default: 'event' name_time : s...
def from_arrays(event, time, name_event=None, name_time=None): """Create structured array. Parameters ---------- event : array-like Event indicator. A boolean array or array with values 0/1. time : array-like Observed time. name_event : str|None ...
Create structured array from data frame. Parameters ---------- event : object Identifier of column containing event indicator. time : object Identifier of column containing time. data : pandas.DataFrame Dataset. Returns ------...
def from_dataframe(event, time, data): """Create structured array from data frame. Parameters ---------- event : object Identifier of column containing event indicator. time : object Identifier of column containing time. data : pandas.DataFrame ...
Negative gradient of partial likelihood Parameters --------- y : tuple, len = 2 First element is boolean event indicator and second element survival/censoring time. y_pred : np.ndarray, shape=(n,): The predictions.
def negative_gradient(self, y, y_pred, sample_weight=None, **kwargs): """Negative gradient of partial likelihood Parameters --------- y : tuple, len = 2 First element is boolean event indicator and second element survival/censoring time. y_pred : np.ndarray, shape=(n...
Least squares does not need to update terminal regions. But it has to update the predictions.
def update_terminal_regions(self, tree, X, y, residual, y_pred, sample_weight, sample_mask, learning_rate=1.0, k=0): """Least squares does not need to update terminal regions. But it has to update the predictions. """ # upd...
Least squares does not need to update terminal regions
def _update_terminal_region(self, tree, terminal_regions, leaf, X, y, residual, pred, sample_weight): """Least squares does not need to update terminal regions"""
Negative gradient of partial likelihood Parameters --------- y : tuple, len = 2 First element is boolean event indicator and second element survival/censoring time. y_pred : np.ndarray, shape=(n,): The predictions.
def negative_gradient(self, y, y_pred, sample_weight=None, **kwargs): """Negative gradient of partial likelihood Parameters --------- y : tuple, len = 2 First element is boolean event indicator and second element survival/censoring time. y_pred : np.ndarray, shape=(n...
Modify the extensions to build from the .c and .cpp files. This is useful for releases, this way cython is not required to run python setup.py install.
def build_from_c_and_cpp_files(extensions): """Modify the extensions to build from the .c and .cpp files. This is useful for releases, this way cython is not required to run python setup.py install. """ for extension in extensions: sources = [] for sfile in extension.sources: ...
Tweaks for building extensions between release and development mode.
def maybe_cythonize_extensions(top_path, config): """Tweaks for building extensions between release and development mode.""" is_release = os.path.exists(os.path.join(top_path, 'PKG-INFO')) if is_release: build_from_c_and_cpp_files(config.ext_modules) else: message = ('Please install cyt...
Return dict mapping relevance level to sample index
def _count_values(self): """Return dict mapping relevance level to sample index""" indices = {yi: [i] for i, yi in enumerate(self.y) if self.status[i]} return indices
Split into intercept/bias and feature-specific coefficients
def _split_coefficents(self, w): """Split into intercept/bias and feature-specific coefficients""" if self._fit_intercept: bias = w[0] wf = w[1:] else: bias = 0.0 wf = w return bias, wf
Samples are ordered by relevance
def _create_optimizer(self, X, y, status): """Samples are ordered by relevance""" if self.optimizer is None: self.optimizer = 'avltree' times, ranks = y if self.optimizer == 'simple': optimizer = SimpleOptimizer(X, status, self.alpha, self.rank_ratio, timeit=sel...
Build a survival support vector machine model from training data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator a...
def fit(self, X, y): """Build a survival support vector machine model from training data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the bina...
Like numpy.argsort, but resolves ties uniformly at random
def _argsort_and_resolve_ties(time, random_state): """Like numpy.argsort, but resolves ties uniformly at random""" n_samples = len(time) order = numpy.argsort(time, kind="mergesort") i = 0 while i < n_samples - 1: inext = i + 1 while inext < n_samples and...
Rank samples according to survival times Lower ranks indicate shorter survival, higher ranks longer survival. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : ndarray, shape = (n_samples,) ...
def predict(self, X): """Rank samples according to survival times Lower ranks indicate shorter survival, higher ranks longer survival. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y...
Rank samples according to survival times Lower ranks indicate shorter survival, higher ranks longer survival. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : ndarray, shape = (n_samples,) ...
def predict(self, X): """Rank samples according to survival times Lower ranks indicate shorter survival, higher ranks longer survival. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y...
Build an accelerated failure time model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time o...
def fit(self, X, y): """Build an accelerated failure time model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator ...
Compute baseline cumulative hazard function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, sh...
def fit(self, linear_predictor, event, time): """Compute baseline cumulative hazard function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. event : array-like, shape = (n_samples,) Contain...
Predict cumulative hazard function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. Returns ------- cum_hazard : ndarray, shape = (n_samples,) Predicted cumulative hazard functions.
def get_cumulative_hazard_function(self, linear_predictor): """Predict cumulative hazard function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. Returns ------- cum_hazard : ndarray, s...
Predict survival function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. Returns ------- survival : ndarray, shape = (n_samples,) Predicted survival functions.
def get_survival_function(self, linear_predictor): """Predict survival function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. Returns ------- survival : ndarray, shape = (n_samples,) ...
Compute negative partial log-likelihood Parameters ---------- w : array, shape = (n_features,) Estimate of coefficients Returns ------- loss : float Average negative partial log-likelihood
def nlog_likelihood(self, w): """Compute negative partial log-likelihood Parameters ---------- w : array, shape = (n_features,) Estimate of coefficients Returns ------- loss : float Average negative partial log-likelihood """ ...
Compute gradient and Hessian matrix with respect to `w`.
def update(self, w, offset=0): """Compute gradient and Hessian matrix with respect to `w`.""" time = self.time x = self.x exp_xw = numpy.exp(offset + numpy.dot(x, w)) n_samples, n_features = x.shape gradient = numpy.zeros((1, n_features), dtype=float) hessian = n...
Minimize negative partial log-likelihood for provided data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first...
def fit(self, X, y): """Minimize negative partial log-likelihood for provided data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary even...
Predict risk scores. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. Returns ------- risk_score : array, shape = (n_samples,) Predicted risk scores.
def predict(self, X): """Predict risk scores. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. Returns ------- risk_score : array, shape = (n_samples,) Predicted risk scores. """ check_is_...
Count right censored and uncensored samples at each unique time point. Parameters ---------- event : array Boolean event indicator. time : array Survival time or time of censoring. order : array or None Indices to order time in ascending order. If None, order will ...
def _compute_counts(event, time, order=None): """Count right censored and uncensored samples at each unique time point. Parameters ---------- event : array Boolean event indicator. time : array Survival time or time of censoring. order : array or None Indices to order ...
Compute counts for left truncated and right censored survival data. Parameters ---------- event : array Boolean event indicator. time_start : array Time when a subject entered the study. time_exit : array Time when a subject left the study due to an event or censor...
def _compute_counts_truncated(event, time_enter, time_exit): """Compute counts for left truncated and right censored survival data. Parameters ---------- event : array Boolean event indicator. time_start : array Time when a subject entered the study. time_exit : array ...
Kaplan-Meier estimator of survival function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time_exit : array-like, shape = (n_samples,) Contains event/censoring times. time_enter : array-like, shape = (n_samples,), optional ...
def kaplan_meier_estimator(event, time_exit, time_enter=None, time_min=None): """Kaplan-Meier estimator of survival function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time_exit : array-like, shape = (n_samples,) Contains event...
Nelson-Aalen estimator of cumulative hazard function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, shape = (n_samples,) Contains event/censoring times. Returns ------- time : array, shape = (n_times,) ...
def nelson_aalen_estimator(event, time): """Nelson-Aalen estimator of cumulative hazard function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, shape = (n_samples,) Contains event/censoring times. Returns ...
Compute inverse probability of censoring weights Parameters ---------- event : array, shape = (n_samples,) Boolean event indicator. time : array, shape = (n_samples,) Time when a subject experienced an event or was censored. Returns ------- weights : array, shape = (n_samp...
def ipc_weights(event, time): """Compute inverse probability of censoring weights Parameters ---------- event : array, shape = (n_samples,) Boolean event indicator. time : array, shape = (n_samples,) Time when a subject experienced an event or was censored. Returns -------...
Estimate survival distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Retur...
def fit(self, y): """Estimate survival distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as ...
Return probability of an event after given time point. :math:`\\hat{S}(t) = P(T > t)` Parameters ---------- time : array, shape = (n_samples,) Time to estimate probability at. Returns ------- prob : array, shape = (n_samples,) Probabilit...
def predict_proba(self, time): """Return probability of an event after given time point. :math:`\\hat{S}(t) = P(T > t)` Parameters ---------- time : array, shape = (n_samples,) Time to estimate probability at. Returns ------- prob : array, s...
Estimate censoring distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Retu...
def fit(self, y): """Estimate censoring distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as ...