INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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. | 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. | 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 | 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 ---------- | 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. ) | 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 | 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. | 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: | 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 the predicted surviva... | 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 | 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. | 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. | 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. | 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 ]. | 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. | 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 | 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 | 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 ]. | 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
... |
Subtract the { 0 } of two { 1 } objects. | 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. | 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. | 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. | 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. | 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_observed == None timeline: list optional return t... | 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 | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 <= ... |
Predict the median lifetimes for the individuals. If the survival curve of an individual does not cross 0. 5 then the result is infinity. | def predict_median(self, X, ancillary_X=None):
"""
Predict the median lifetimes for the individuals. If the survival curve of an
individual does not cross 0.5, then the result is infinity.
Parameters
----------
X: numpy array or DataFrame
a (n,d) covariate nu... |
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... |
Produces a visual representation of the coefficients including their standard errors and magnitudes. | def plot(self, columns=None, parameter=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
e... |
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 the predicted surviva... | 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... |
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 | 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
... |
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 subject was observed for timeline: iterable 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 ( righ... | def fit(
self,
durations,
event_observed=None,
timeline=None,
entry=None,
label="NA_estimate",
alpha=None,
ci_labels=None,
weights=None,
): # pylint: disable=too-many-arguments
"""
Parameters
-----------
duratio... |
Parameters ----------- bandwidth: float the bandwith used in the Epanechnikov kernel. | def smoothed_hazard_(self, bandwidth):
"""
Parameters
-----------
bandwidth: float
the bandwith used in the Epanechnikov kernel.
Returns
-------
DataFrame:
a DataFrame of the smoothed hazard
"""
timeline = self.timeline
... |
Parameters ---------- bandwidth: float the bandwidth to use in the Epanechnikov kernel. > 0 hazard_: numpy array a computed ( n ) numpy array of estimated hazard rates. If none uses smoothed_hazard_ | def smoothed_hazard_confidence_intervals_(self, bandwidth, hazard_=None):
"""
Parameters
----------
bandwidth: float
the bandwidth to use in the Epanechnikov kernel. > 0
hazard_: numpy array
a computed (n,) numpy array of estimated hazard rates. If non... |
Convert the np. ndarray values into a complete balanced tree. | def _treeify(values):
"""Convert the np.ndarray `values` into a complete balanced tree.
Assumes `values` is sorted ascending. Returns a list `t` of the same length in which t[i] >
t[2i+1] and t[i] < t[2i+2] for all i."""
if len(values) == 1: # this case causes problems later
... |
Insert an occurrence of value into the btree. | def insert(self, value):
"""Insert an occurrence of `value` into the btree."""
i = 0
n = len(self._tree)
while i < n:
cur = self._tree[i]
self._counts[i] += 1
if value < cur:
i = 2 * i + 1
elif value > cur:
i... |
Returns the rank and count of the value in the btree. | def rank(self, value):
"""Returns the rank and count of the value in the btree."""
i = 0
n = len(self._tree)
rank = 0
count = 0
while i < n:
cur = self._tree[i]
if value < cur:
i = 2 * i + 1
continue
elif... |
Produces a quantile - quantile plot of the empirical CDF against the fitted parametric CDF. Large deviances away from the line y = x can invalidate a model ( though we expect some natural deviance in the tails ). | def qq_plot(model, **plot_kwargs):
"""
Produces a quantile-quantile plot of the empirical CDF against
the fitted parametric CDF. Large deviances away from the line y=x
can invalidate a model (though we expect some natural deviance in the tails).
Parameters
-----------
model: obj
A f... |
Remove spines of axis. | def remove_spines(ax, sides):
"""
Remove spines of axis.
Parameters:
ax: axes to operate on
sides: list of sides: top, left, bottom, right
Examples:
removespines(ax, ['top'])
removespines(ax, ['top', 'bottom', 'right', 'left'])
"""
for side in sides:
ax.spines[side]... |
Move the entire spine relative to the figure. | def move_spines(ax, sides, dists):
"""
Move the entire spine relative to the figure.
Parameters:
ax: axes to operate on
sides: list of sides to move. Sides: top, left, bottom, right
dists: list of float distances to move. Should match sides in length.
Example:
move_spines(ax, sid... |
Remove ticks from axis. | def remove_ticks(ax, x=False, y=False):
"""
Remove ticks from axis.
Parameters:
ax: axes to work on
x: if True, remove xticks. Default False.
y: if True, remove yticks. Default False.
Examples:
removeticks(ax, x=True)
removeticks(ax, x=True, y=True)
"""
if x:
... |
Add counts showing how many individuals were at risk at each time point in survival/ hazard plots. | def add_at_risk_counts(*fitters, **kwargs):
"""
Add counts showing how many individuals were at risk at each time point in
survival/hazard plots.
Parameters
----------
fitters:
One or several fitters, for example KaplanMeierFitter,
NelsonAalenFitter, etc...
Returns
-------... |
Returns a lifetime plot see examples: https:// lifelines. readthedocs. io/ en/ latest/ Survival%20Analysis%20intro. html#Censoring | def plot_lifetimes(
durations,
event_observed=None,
entry=None,
left_truncated=False,
sort_by_duration=True,
event_observed_color="#A60628",
event_censored_color="#348ABD",
**kwargs
):
"""
Returns a lifetime plot, see examples: https://lifelines.readthedocs.io/en/latest/Survival%... |
Specifies a plot of the log ( - log ( SV )) versus log ( time ) where SV is the estimated survival function. | def plot_loglogs(cls, loc=None, iloc=None, show_censors=False, censor_styles=None, **kwargs):
"""
Specifies a plot of the log(-log(SV)) versus log(time) where SV is the estimated survival function.
"""
def loglog(s):
return np.log(-np.log(s))
if (loc is not None) and (iloc is not None):
... |
Plots a pretty figure of { 0 }. { 1 } | def _plot_estimate(
cls,
estimate=None,
confidence_intervals=None,
loc=None,
iloc=None,
show_censors=False,
censor_styles=None,
ci_legend=False,
ci_force_lines=False,
ci_alpha=0.25,
ci_show=True,
at_risk_counts=False,
**kwargs
):
"""
Plots a pretty figure of ... |
translate a word document type of file and save the result as document and keep the exactly same file format.: param filename: word doc file: param destination = zh - CN:: param mix = True: if True will have original language and target language into the same doc. paragraphs by paragraphs. | def translate_doc(filename, destination='zh-CN', mix=True):
"""
translate a word document type of file and save the result as document and keep the exactly same file format.
:param filename: word doc file
:param destination='zh-CN':
:param mix=True: if True, will have original languag... |
Translate text from source language to destination language | def translate(self, text, dest='en', src='auto'):
"""Translate text from source language to destination language
:param text: The source text(s) to be translated. Batch translation is supported via sequence input.
:type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, i... |
Detect language of the input text | def detect(self, text):
"""Detect language of the input text
:param text: The source text(s) whose language you want to identify.
Batch detection is supported via sequence input.
:type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, gener... |
update tkk | def _update(self):
"""update tkk
"""
# we don't need to update the base TKK value when it is still valid
now = math.floor(int(time.time() * 1000) / 3600000.0)
if self.tkk and int(self.tkk.split('.')[0]) == now:
return
r = self.session.get(self.host)
... |
Wheel filenames contain the python version and the python ABI version for the wheel. https:// www. python. org/ dev/ peps/ pep - 0427/ #file - name - convention Since we re distributing a rust binary this doesn t matter for us... | def make_wheel_filename_generic(wheel):
""" Wheel filenames contain the python version and the python ABI version
for the wheel. https://www.python.org/dev/peps/pep-0427/#file-name-convention
Since we're distributing a rust binary this doesn't matter for us ... """
name, version, python, abi, platform =... |
Only most frequent k words to be included in the embeddings. | def most_frequent(self, k, inplace=False):
"""Only most frequent k words to be included in the embeddings."""
vocabulary = self.vocabulary.most_frequent(k)
vectors = np.asarray([self[w] for w in vocabulary])
if inplace:
self.vocabulary = vocabulary
self.vectors = vectors
return self
... |
Normalize embeddings matrix row - wise. | def normalize_words(self, ord=2, inplace=False):
"""Normalize embeddings matrix row-wise.
Args:
ord: normalization order. Possible values {1, 2, 'inf', '-inf'}
"""
if ord == 2:
ord = None # numpy uses this flag to indicate l2.
vectors = self.vectors.T / np.linalg.norm(self.vectors, ord,... |
Return the nearest k words to the given word. | def nearest_neighbors(self, word, top_k=10):
"""Return the nearest k words to the given `word`.
Args:
word (string): single word.
top_k (integer): decides how many neighbors to report.
Returns:
A list of words sorted by the distances. The closest is the first.
Note:
L2 metric ... |
Calculate eucledean pairwise distances between word and words. | def distances(self, word, words):
"""Calculate eucledean pairwise distances between `word` and `words`.
Args:
word (string): single word.
words (list): list of strings.
Returns:
numpy array of the distances.
Note:
L2 metric is used to calculate distances.
"""
point = ... |
Load the input - hidden weight matrix from the original C word2vec - tool format. | def from_word2vec(fname, fvocab=None, binary=False):
"""
Load the input-hidden weight matrix from the original C word2vec-tool format.
Note that the information stored in the file is incomplete (the binary tree is missing),
so while you can query for word similarity etc., you cannot continue training
... |
Load an embedding dump generated by save | def load(fname):
"""Load an embedding dump generated by `save`"""
content = _open(fname).read()
if PY2:
state = pickle.loads(content)
else:
state = pickle.loads(content, encoding='latin1')
voc, vec = state
if len(voc) == 2:
words, counts = voc
word_count = dict(zip(words... |
Save a pickled version of the embedding into fname. | def save(self, fname):
"""Save a pickled version of the embedding into `fname`."""
vec = self.vectors
voc = self.vocabulary.getstate()
state = (voc, vec)
with open(fname, 'wb') as f:
pickle.dump(state, f, protocol=pickle.HIGHEST_PROTOCOL) |
Extract the contents of the zip file filename into the directory root. | def unzip(filename, root, verbose=True):
"""
Extract the contents of the zip file ``filename`` into the
directory ``root``.
"""
for message in _unzip_iter(filename, root, verbose):
if isinstance(message, ErrorMessage):
raise Exception(message) |
Create a new data. xml index file by combining the xml description files for various packages and collections. root should be the path to a directory containing the package xml and zip files ; and the collection xml files. The root directory is expected to have the following subdirectories:: | def build_index(root, base_url):
"""
Create a new data.xml index file, by combining the xml description
files for various packages and collections. ``root`` should be the
path to a directory containing the package xml and zip files; and
the collection xml files. The ``root`` directory is expected to
have ... |
Helper for build_index (): Given an XML ElementTree modify it ( and its descendents ) text and tail attributes to generate an indented tree where each nested element is indented by 2 spaces with respect to its parent. | def _indent_xml(xml, prefix=''):
"""
Helper for ``build_index()``: Given an XML ``ElementTree``, modify it
(and its descendents) ``text`` and ``tail`` attributes to generate
an indented tree, where each nested element is indented by 2
spaces with respect to its parent.
"""
if len(xml) > 0:
xml.text = ... |
Helper for build_index (): Perform some checks to make sure that the given package is consistent. | def _check_package(pkg_xml, zipfilename, zf):
"""
Helper for ``build_index()``: Perform some checks to make sure that
the given package is consistent.
"""
# The filename must patch the id given in the XML file.
uid = os.path.splitext(os.path.split(zipfilename)[1])[0]
if pkg_xml.get('id') != uid:
raise... |
Helper for build_index (): Calculate the subversion revision number for a given file ( by using subprocess to run svn ). | def _svn_revision(filename):
"""
Helper for ``build_index()``: Calculate the subversion revision
number for a given file (by using ``subprocess`` to run ``svn``).
"""
p = subprocess.Popen(['svn', 'status', '-v', filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(stdout, st... |
Helper for build_index (): Yield a list of ElementTree. Element objects each holding the xml for a single package collection. | def _find_collections(root):
"""
Helper for ``build_index()``: Yield a list of ElementTree.Element
objects, each holding the xml for a single package collection.
"""
packages = []
for dirname, subdirs, files in os.walk(root):
for filename in files:
if filename.endswith('.xml'):
xmlfile = o... |
Helper for build_index (): Yield a list of tuples ( pkg_xml zf subdir ) where: - pkg_xml is an ElementTree. Element holding the xml for a package - zf is a zipfile. ZipFile for the package s contents. - subdir is the subdirectory ( relative to root ) where the package was found ( e. g. corpora or grammars ). | def _find_packages(root):
"""
Helper for ``build_index()``: Yield a list of tuples
``(pkg_xml, zf, subdir)``, where:
- ``pkg_xml`` is an ``ElementTree.Element`` holding the xml for a
package
- ``zf`` is a ``zipfile.ZipFile`` for the package's contents.
- ``subdir`` is the subdirectory (relative to... |
Return a constant describing the status of the given package or collection. Status can be one of INSTALLED NOT_INSTALLED STALE or PARTIAL. | def status(self, info_or_id, download_dir=None):
"""
Return a constant describing the status of the given package
or collection. Status can be one of ``INSTALLED``,
``NOT_INSTALLED``, ``STALE``, or ``PARTIAL``.
"""
if download_dir is None: download_dir = self._download_dir
info = self._info... |
Re - download any packages whose status is STALE. | def update(self, quiet=False, prefix='[polyglot_data] '):
"""
Re-download any packages whose status is STALE.
"""
self.clear_status_cache()
for pkg in self.packages():
if self.status(pkg) == self.STALE:
self.download(pkg, quiet=quiet, prefix=prefix) |
A helper function that ensures that self. _index is up - to - date. If the index is older than self. INDEX_TIMEOUT then download it again. | def _update_index(self, url=None):
"""A helper function that ensures that self._index is
up-to-date. If the index is older than self.INDEX_TIMEOUT,
then download it again."""
# Check if the index is aleady up-to-date. If so, do nothing.
if not (self._index is None or url is not None or
tim... |
Return the Package or Collection record for the given item. | def info(self, id):
"""Return the ``Package`` or ``Collection`` record for the
given item."""
#self._update_index() # This is commented because it leads to
# excessive network load
if id in self._packages: return self._packages[id]
if id in self._collections: return self... |
Return the collection that represents a specific language or task. | def get_collection(self, lang=None, task=None):
""" Return the collection that represents a specific language or task.
Args:
lang (string): Language code.
task (string): Task name.
"""
if lang: id = "{}{}".format(Downloader.LANG_PREFIX, lang)
elif task: id = "{}{}".format(Downloader.TAS... |
Return True if polyglot supports the language. | def supported_language(lang):
"""Return True if polyglot supports the language.
Args:
lang (string): Language code.
"""
try:
self.get_collection(lang=lang)
return True
except LanguageNotSupported as e:
return False |
Languages that are covered by a specific task. | def supported_languages(self, task=None):
"""Languages that are covered by a specific task.
Args:
task (string): Task name.
"""
if task:
collection = self.get_collection(task=task)
return [isoLangs[x.id.split('.')[1]]["name"]
for x in collectio... |
Languages that are covered by a specific task. | def supported_tasks(self, lang=None):
"""Languages that are covered by a specific task.
Args:
lang (string): Language code name.
"""
if lang:
collection = self.get_collection(lang=lang)
return [x.id.split('.')[0] for x in collection.packages]
else:
return [x.name.split()[0] ... |
Return the XML info record for the given item | def xmlinfo(self, id):
"""Return the XML info record for the given item"""
self._update_index()
for package in self._index.findall('packages/package'):
if package.get('id') == id:
return package
for collection in self._index.findall('collections/collection'):
if collection.get('id') ... |
Set a new URL for the data server. If we re unable to contact the given url then the original url is kept. | def _set_url(self, url):
"""
Set a new URL for the data server. If we're unable to contact
the given url, then the original url is kept.
"""
original_url = self._url
try:
self._update_index(url)
except:
self._url = original_url
raise |
Transliterate a string from English to the target language. | def _decoder(self):
"""Transliterate a string from English to the target language."""
if self.target_lang == 'en':
return Transliterator._dummy_coder
else:
weights = load_transliteration_table(self.target_lang)
decoder_weights = weights["decoder"]
return Transliterator._transliterate... |
Transliterate a string from the input language to English. | def _encoder(self):
"""Transliterate a string from the input language to English."""
if self.source_lang == 'en':
return Transliterator._dummy_coder
else:
weights = load_transliteration_table(self.source_lang)
encoder_weights = weights["encoder"]
return Transliterator._transliterate_... |
Transliterate the word from its source language to the target one. | def transliterate(self, word):
"""Transliterate the word from its source language to the target one.
The method works by encoding the word into English then decoding the new
Enlgish word to the target language.
"""
encoded_word = self.encoder(word)
decoded_word = self.decoder(encoded_word)
... |
Return a list of tokens using this blob s tokenizer object ( defaults to: class: WordTokenizer <textblob. tokenizers. WordTokenizer > ). | def tokens(self):
"""Return a list of tokens, using this blob's tokenizer object
(defaults to :class:`WordTokenizer <textblob.tokenizers.WordTokenizer>`).
"""
seq = self.word_tokenizer.transform(Sequence(self.raw))
return WordList(seq.tokens(), parent=self, language=self.language.code) |
Return the polarity score as a float within the range [ - 1. 0 1. 0 ] | def polarity(self):
"""Return the polarity score as a float within the range [-1.0, 1.0]
"""
scores = [w.polarity for w in self.words if w.polarity != 0]
if not scores:
return 0.0
return sum(scores) / float(len(scores)) |
Transliterate the string to the target language. | def transliterate(self, target_language="en"):
"""Transliterate the string to the target language."""
return WordList([w.transliterate(target_language) for w in self.words],
language=target_language, parent=self) |
Returns a list of entities for this blob. | def entities(self):
"""Returns a list of entities for this blob."""
start = 0
end = 0
prev_tag = u'O'
chunks = []
for i, (w, tag) in enumerate(self.ne_chunker.annotate(self.words)):
if tag != prev_tag:
if prev_tag == u'O':
start = i
else:
chunks.append(C... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.