INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Sample near the document by replacing some of its features with values sampled from distribution found by KDE.
def sample_near(self, doc, n_samples=1): """ Sample near the document by replacing some of its features with values sampled from distribution found by KDE. """ doc = np.asarray(doc) num_features = len(self.kdes_) sizes = self.rng_.randint(low=1, high=num_features ...
All feature names for a feature: usually just the feature itself, but can be several features for unhashed features with collisions.
def _all_feature_names(name): # type: (Union[str, bytes, List[Dict]]) -> List[str] """ All feature names for a feature: usually just the feature itself, but can be several features for unhashed features with collisions. """ if isinstance(name, bytes): return [name.decode('utf8')] elif is...
Return feature names filtered by a regular expression ``feature_re``, and indices of filtered elements.
def filtered(self, feature_filter, x=None): # type: (Callable, Any) -> Tuple[FeatureNames, List[int]] """ Return feature names filtered by a regular expression ``feature_re``, and indices of filtered elements. """ indices = [] filtered_feature_names = [] indexed_...
Add a new feature name, return it's index.
def add_feature(self, feature): # type: (Any) -> int """ Add a new feature name, return it's index. """ # A copy of self.feature_names is always made, because it might be # "owned" by someone else. # It's possible to make the copy only at the first call to # self....
Format explanation as text. Parameters ---------- expl : eli5.base.Explanation Explanation returned by ``eli5.explain_weights`` or ``eli5.explain_prediction`` functions. highlight_spaces : bool or None, optional Whether to highlight spaces in feature names. This is useful if ...
def format_as_text(expl, # type: Explanation show=fields.ALL, highlight_spaces=None, # type: Optional[bool] show_feature_values=False, # type: bool ): # type: (...) -> str """ Format explanation as text. Parameters ---------...
Format feature name for hashed features.
def _format_unhashed_feature(name, hl_spaces, sep=' | '): # type: (List, bool, str) -> str """ Format feature name for hashed features. """ return sep.join( format_signed(n, _format_single_feature, hl_spaces=hl_spaces) for n in name)
Return a ``(pos, neg)`` tuple. ``pos`` and ``neg`` are lists of ``(name, value)`` tuples for features with positive and negative coefficients. Parameters: * ``feature_names`` - a vector of feature names; * ``coef`` - coefficient vector; coef.shape must be equal to feature_names.shape; * ...
def _get_top_features(feature_names, coef, top, x): """ Return a ``(pos, neg)`` tuple. ``pos`` and ``neg`` are lists of ``(name, value)`` tuples for features with positive and negative coefficients. Parameters: * ``feature_names`` - a vector of feature names; * ``coef`` - coefficient vecto...
Return character weights for a text document with highlighted features. If preserve_density is True, then color for longer fragments will be less intensive than for shorter fragments, so that "sum" of intensities will correspond to feature weight. If preserve_density is None, then it's value is taken fr...
def get_char_weights(doc_weighted_spans, preserve_density=None): # type: (DocWeightedSpans, Optional[bool]) -> np.ndarray """ Return character weights for a text document with highlighted features. If preserve_density is True, then color for longer fragments will be less intensive than for shorter fragm...
Return weighted spans prepared for rendering. Calculate a separate weight range for each different weighted span (for each different index): each target has the same number of weighted spans.
def prepare_weighted_spans(targets, # type: List[TargetExplanation] preserve_density=None, # type: Optional[bool] ): # type: (...) -> List[Optional[List[PreparedWeightedSpans]]] """ Return weighted spans prepared for rendering. Calculate a separate wei...
Return an analyzer and the preprocessed doc. Analyzer will yield pairs of spans and feature, where spans are pairs of indices into the preprocessed doc. The idea here is to do minimal preprocessing so that we can still recover the same features as sklearn vectorizers, but with spans, that will allow us ...
def build_span_analyzer(document, vec): """ Return an analyzer and the preprocessed doc. Analyzer will yield pairs of spans and feature, where spans are pairs of indices into the preprocessed doc. The idea here is to do minimal preprocessing so that we can still recover the same features as sklearn ...
Return an explanation of an XGBoost estimator (via scikit-learn wrapper XGBClassifier or XGBRegressor, or via xgboost.Booster) as feature importances. See :func:`eli5.explain_weights` for description of ``top``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``target_name...
def explain_weights_xgboost(xgb, vec=None, top=20, target_names=None, # ignored targets=None, # ignored feature_names=None, feature_re=None, # type: ...
Return an explanation of XGBoost prediction (via scikit-learn wrapper XGBClassifier or XGBRegressor, or via xgboost.Booster) as feature weights. See :func:`eli5.explain_prediction` for description of ``top``, ``top_targets``, ``target_names``, ``targets``, ``feature_names``, ``feature_re`` and ``featur...
def explain_prediction_xgboost( xgb, doc, vec=None, top=None, top_targets=None, target_names=None, targets=None, feature_names=None, feature_re=None, # type: Pattern[str] feature_filter=None, vectorized=False, # type: bool is_regr...
For each target, return score and numpy array with feature weights on this prediction, following an idea from http://blog.datadive.net/interpreting-random-forests/
def _prediction_feature_weights(booster, dmatrix, n_targets, feature_names, xgb_feature_names): """ For each target, return score and numpy array with feature weights on this prediction, following an idea from http://blog.datadive.net/interpreting-random-forests/ """ ...
Return a leaf nodeid -> node dictionary with "parent" and "leaf" (average child "leaf" value) added to all nodes.
def _indexed_leafs(parent): """ Return a leaf nodeid -> node dictionary with "parent" and "leaf" (average child "leaf" value) added to all nodes. """ if not parent.get('children'): return {parent['nodeid']: parent} indexed = {} for child in parent['children']: child['parent'] = p...
Value of the parent node: a weighted sum of child values.
def _parent_value(children): # type: (...) -> int """ Value of the parent node: a weighted sum of child values. """ covers = np.array([child['cover'] for child in children]) covers /= np.sum(covers) leafs = np.array([child['leaf'] for child in children]) return np.sum(leafs * covers)
Parse text tree dump (one item of a list returned by Booster.get_dump()) into json format that will be used by next XGBoost release.
def _parse_tree_dump(text_dump): # type: (str) -> Optional[Dict[str, Any]] """ Parse text tree dump (one item of a list returned by Booster.get_dump()) into json format that will be used by next XGBoost release. """ result = None stack = [] # type: List[Dict] for line in text_dump.split('\n...
Return a copy of values where missing values (equal to missing_value) are replaced to nan according. If sparse_missing is True, entries missing in a sparse matrix will also be set to nan. Sparse matrices will be converted to dense format.
def _missing_values_set_to_nan(values, missing_value, sparse_missing): """ Return a copy of values where missing values (equal to missing_value) are replaced to nan according. If sparse_missing is True, entries missing in a sparse matrix will also be set to nan. Sparse matrices will be converted to dens...
Return no more than ``k`` indices of smallest values.
def argsort_k_smallest(x, k): """ Return no more than ``k`` indices of smallest values. """ if k == 0: return np.array([], dtype=np.intp) if k is None or k >= len(x): return np.argsort(x) indices = np.argpartition(x, k)[:k] values = x[indices] return indices[np.argsort(values)]
The same as x[indices], but return an empty array if indices are empty, instead of returning all x elements, and handles sparse "vectors".
def mask(x, indices): """ The same as x[indices], but return an empty array if indices are empty, instead of returning all x elements, and handles sparse "vectors". """ indices_shape = ( [len(indices)] if isinstance(indices, list) else indices.shape) if not indices_shape[0]: ...
x is a 2D sparse matrix with it's first shape equal to 1.
def is_sparse_vector(x): """ x is a 2D sparse matrix with it's first shape equal to 1. """ return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1
Convert indices to a boolean (integer) mask. >>> list(indices_to_bool_mask(np.array([2, 3]), 4)) [False, False, True, True] >>> list(indices_to_bool_mask([2, 3], 4)) [False, False, True, True] >>> indices_to_bool_mask(np.array([5]), 2) Traceback (most recent call last): ... IndexError...
def indices_to_bool_mask(indices, size): """ Convert indices to a boolean (integer) mask. >>> list(indices_to_bool_mask(np.array([2, 3]), 4)) [False, False, True, True] >>> list(indices_to_bool_mask([2, 3], 4)) [False, False, True, True] >>> indices_to_bool_mask(np.array([5]), 2) Tracebac...
Return a list of (target_id, display_name) tuples. By default original names are passed as-is, only indices are added: >>> get_target_display_names(['x', 'y']) [(0, 'x'), (1, 'y')] ``targets`` can be written using both names from ``target_names` and from ``original_names``: >>> get_target_disp...
def get_target_display_names(original_names=None, target_names=None, targets=None, top_targets=None, score=None): """ Return a list of (target_id, display_name) tuples. By default original names are passed as-is, only indices are added: >>> get_target_display_names(['x', 'y...
Return (target_name, scale, label_id) tuple for a binary classifier. >>> get_binary_target_scale_label_id(+5.0, get_target_display_names([False, True])) (True, 1, 1) >>> get_binary_target_scale_label_id(-5.0, get_target_display_names([False, True])) (False, -1, 0) >>> get_binary_target_scale_label_...
def get_binary_target_scale_label_id(score, display_names, proba=None): """ Return (target_name, scale, label_id) tuple for a binary classifier. >>> get_binary_target_scale_label_id(+5.0, get_target_display_names([False, True])) (True, 1, 1) >>> get_binary_target_scale_label_id(-5.0, get_target_dis...
>>> _get_value_indices(['foo', 'bar', 'baz'], ['foo', 'bar', 'baz'], ... ['bar', 'foo']) [1, 0] >>> _get_value_indices(['foo', 'bar', 'baz'], ['FOO', 'bar', 'baz'], ... ['bar', 'FOO']) [1, 0] >>> _get_value_indices(['foo', 'bar', 'BAZ'], ['foo', 'BAZ', 'baz'...
def _get_value_indices(names1, names2, lookups): """ >>> _get_value_indices(['foo', 'bar', 'baz'], ['foo', 'bar', 'baz'], ... ['bar', 'foo']) [1, 0] >>> _get_value_indices(['foo', 'bar', 'baz'], ['FOO', 'bar', 'baz'], ... ['bar', 'FOO']) [1, 0] >>> _...
Render Graphviz data to SVG
def dot2svg(dot): # type: (str) -> str """ Render Graphviz data to SVG """ svg = graphviz.Source(dot).pipe(format='svg').decode('utf8') # type: str # strip doctype and xml declaration svg = svg[svg.index('<svg'):] return svg
Return an explanation of an estimator
def explain_weights_sklearn(estimator, vec=None, top=_TOP, target_names=None, targets=None, feature_names=None, coef_scale=None, feature_re=None, feature_filter=None): """ Return an explanation of an esti...
Return an explanation of a linear classifier weights. See :func:`eli5.explain_weights` for description of ``top``, ``target_names``, ``targets``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``vec`` is a vectorizer instance used to transform raw features to the input of the...
def explain_linear_classifier_weights(clf, vec=None, top=_TOP, target_names=None, targets=None, feature_names=None, ...
Return an explanation of a tree-based ensemble estimator. See :func:`eli5.explain_weights` for description of ``top``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``target_names`` and ``targets`` parameters are ignored. ``vec`` is a vectorizer instance used to transform ...
def explain_rf_feature_importance(estimator, vec=None, top=_TOP, target_names=None, # ignored targets=None, # ignored feature_names=None, ...
Return an explanation of a decision tree. See :func:`eli5.explain_weights` for description of ``top``, ``target_names``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``targets`` parameter is ignored. ``vec`` is a vectorizer instance used to transform raw features to th...
def explain_decision_tree(estimator, vec=None, top=_TOP, target_names=None, targets=None, # ignored feature_names=None, feature_re=None, ...
Return an explanation of a linear regressor weights. See :func:`eli5.explain_weights` for description of ``top``, ``target_names``, ``targets``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``vec`` is a vectorizer instance used to transform raw features to the input of the ...
def explain_linear_regressor_weights(reg, vec=None, top=_TOP, target_names=None, targets=None, feature_names=None, ...
Return an explanation of PermutationImportance. See :func:`eli5.explain_weights` for description of ``top``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``target_names`` and ``targets`` parameters are ignored. ``vec`` is a vectorizer instance used to transform raw fea...
def explain_permutation_importance(estimator, vec=None, top=_TOP, target_names=None, # ignored targets=None, # ignored feature_names=None, ...
Return a dict ``{column_id: [possible term ids]}`` with collision information.
def _get_collisions(indices): # type: (...) -> Dict[int, List[int]] """ Return a dict ``{column_id: [possible term ids]}`` with collision information. """ collisions = defaultdict(list) # type: Dict[int, List[int]] for term_id, hash_id in enumerate(indices): collisions[hash_id].appe...
For each term from ``terms`` return its column index and sign, as assigned by FeatureHasher ``hasher``.
def _get_indices_and_signs(hasher, terms): """ For each term from ``terms`` return its column index and sign, as assigned by FeatureHasher ``hasher``. """ X = _transform_terms(hasher, terms) indices = X.nonzero()[1] signs = X.sum(axis=1).A.ravel() return indices, signs
Return feature_names and coef_scale (if with_coef_scale is True), calling .get_feature_names for invhashing vectorizers.
def handle_hashing_vec(vec, feature_names, coef_scale, with_coef_scale=True): """ Return feature_names and coef_scale (if with_coef_scale is True), calling .get_feature_names for invhashing vectorizers. """ needs_coef_scale = with_coef_scale and coef_scale is None if is_invhashing(vec): if f...
Create an :class:`~.InvertableHashingVectorizer` from hashing vectorizer vec and fit it on docs. If vec is a FeatureUnion, do it for all hashing vectorizers in the union. Return an :class:`~.InvertableHashingVectorizer`, or a FeatureUnion, or an unchanged vectorizer.
def invert_hashing_and_fit( vec, # type: Union[FeatureUnion, HashingVectorizer] docs ): # type: (...) -> Union[FeatureUnion, InvertableHashingVectorizer] """ Create an :class:`~.InvertableHashingVectorizer` from hashing vectorizer vec and fit it on docs. If vec is a FeatureUnion, do it ...
Fit InvertableHashingVectorizer on doc inside a FeatureUnion.
def _fit_invhashing_union(vec_union, docs): # type: (FeatureUnion, Any) -> FeatureUnion """ Fit InvertableHashingVectorizer on doc inside a FeatureUnion. """ return FeatureUnion( [(name, invert_hashing_and_fit(v, docs)) for name, v in vec_union.transformer_list], transformer_wei...
Extract possible terms from documents
def fit(self, X, y=None): """ Extract possible terms from documents """ self.unhasher.fit(self._get_terms_iter(X)) return self
Return feature names. This is a best-effort function which tries to reconstruct feature names based on what it has seen so far. HashingVectorizer uses a signed hash function. If always_signed is True, each term in feature names is prepended with its sign. If it is False, signs a...
def get_feature_names(self, always_signed=True): # type: (bool) -> FeatureNames """ Return feature names. This is a best-effort function which tries to reconstruct feature names based on what it has seen so far. HashingVectorizer uses a signed hash function. If always_si...
Return a numpy array with expected signs of features. Values are * +1 when all known terms which map to the column have positive sign; * -1 when all known terms which map to the column have negative sign; * ``nan`` when there are both positive and negative known terms for this...
def column_signs_(self): """ Return a numpy array with expected signs of features. Values are * +1 when all known terms which map to the column have positive sign; * -1 when all known terms which map to the column have negative sign; * ``nan`` when there are both positiv...
Update all computed attributes. It is only needed if you need to access computed attributes after :meth:`patrial_fit` was called.
def recalculate_attributes(self, force=False): # type: (bool) -> None """ Update all computed attributes. It is only needed if you need to access computed attributes after :meth:`patrial_fit` was called. """ if not self._attributes_dirty and not force: return ...
Return text representation of a decision tree.
def tree2text(tree_obj, indent=4): # type: (TreeInfo, int) -> str """ Return text representation of a decision tree. """ parts = [] def _format_node(node, depth=0): # type: (NodeInfo, int) -> None def p(*args): # type: (*str) -> None parts.append(" " * de...
>>> _format_array([0, 1.0], "{:0.3f}") '[0.000, 1.000]'
def _format_array(x, fmt): # type: (Any, str) -> str """ >>> _format_array([0, 1.0], "{:0.3f}") '[0.000, 1.000]' """ value_repr = ", ".join(fmt.format(v) for v in x) return "[{}]".format(value_repr)
Explain weights and export them to ``pandas.DataFrame``. All keyword arguments are passed to :func:`eli5.explain_weights`. Weights of all features are exported by default.
def explain_weights_df(estimator, **kwargs): # type: (...) -> pd.DataFrame """ Explain weights and export them to ``pandas.DataFrame``. All keyword arguments are passed to :func:`eli5.explain_weights`. Weights of all features are exported by default. """ kwargs = _set_defaults(kwargs) return...
Explain weights and export them to a dict with ``pandas.DataFrame`` values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does). All keyword arguments are passed to :func:`eli5.explain_weights`. Weights of all features are exported by default.
def explain_weights_dfs(estimator, **kwargs): # type: (...) -> Dict[str, pd.DataFrame] """ Explain weights and export them to a dict with ``pandas.DataFrame`` values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does). All keyword arguments are passed to :func:`eli5.explain_weights`. ...
Explain prediction and export explanation to ``pandas.DataFrame`` All keyword arguments are passed to :func:`eli5.explain_prediction`. Weights of all features are exported by default.
def explain_prediction_df(estimator, doc, **kwargs): # type: (...) -> pd.DataFrame """ Explain prediction and export explanation to ``pandas.DataFrame`` All keyword arguments are passed to :func:`eli5.explain_prediction`. Weights of all features are exported by default. """ kwargs = _set_default...
Explain prediction and export explanation to a dict with ``pandas.DataFrame`` values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does). All keyword arguments are passed to :func:`eli5.explain_prediction`. Weights of all features are exported by default.
def explain_prediction_dfs(estimator, doc, **kwargs): # type: (...) -> Dict[str, pd.DataFrame] """ Explain prediction and export explanation to a dict with ``pandas.DataFrame`` values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does). All keyword arguments are passed to :func:`eli5...
Export an explanation to a single ``pandas.DataFrame``. In case several dataframes could be exported by :func:`eli5.formatters.as_dataframe.format_as_dataframes`, a warning is raised. If no dataframe can be exported, ``None`` is returned. This function also accepts some components of the explanation as ...
def format_as_dataframe(explanation): # type: (Explanation) -> Optional[pd.DataFrame] """ Export an explanation to a single ``pandas.DataFrame``. In case several dataframes could be exported by :func:`eli5.formatters.as_dataframe.format_as_dataframes`, a warning is raised. If no dataframe can be exp...
Export an explanation to a dictionary with ``pandas.DataFrame`` values and string keys that correspond to explanation attributes. Use this method if several dataframes can be exported from a single explanation (e.g. for CRF explanation with has both feature weights and transition matrix). Note that ...
def format_as_dataframes(explanation): # type: (Explanation) -> Dict[str, pd.DataFrame] """ Export an explanation to a dictionary with ``pandas.DataFrame`` values and string keys that correspond to explanation attributes. Use this method if several dataframes can be exported from a single explanatio...
Return an iterator of X matrices which have one or more columns shuffled. After each iteration yielded matrix is mutated inplace, so if you want to use multiple of them at the same time, make copies. ``columns_to_shuffle`` is a sequence of column numbers to shuffle. By default, all columns are shuffled...
def iter_shuffled(X, columns_to_shuffle=None, pre_shuffle=False, random_state=None): """ Return an iterator of X matrices which have one or more columns shuffled. After each iteration yielded matrix is mutated inplace, so if you want to use multiple of them at the same time, make copie...
Return ``(base_score, score_decreases)`` tuple with the base score and score decreases when a feature is not available. ``base_score`` is ``score_func(X, y)``; ``score_decreases`` is a list of length ``n_iter`` with feature importance arrays (each array is of shape ``n_features``); feature importances ...
def get_score_importances( score_func, # type: Callable[[Any, Any], float] X, y, n_iter=5, # type: int columns_to_shuffle=None, random_state=None ): # type: (...) -> Tuple[float, List[np.ndarray]] """ Return ``(base_score, score_decreases)`` tuple with t...
Return an explanation of estimator parameters (weights) as an IPython.display.HTML object. Use this function to show classifier weights in IPython. :func:`show_weights` accepts all :func:`eli5.explain_weights` arguments and all :func:`eli5.formatters.html.format_as_html` keyword arguments, so i...
def show_weights(estimator, **kwargs): """ Return an explanation of estimator parameters (weights) as an IPython.display.HTML object. Use this function to show classifier weights in IPython. :func:`show_weights` accepts all :func:`eli5.explain_weights` arguments and all :func:`eli5.formatters.h...
Convert DecisionTreeClassifier or DecisionTreeRegressor to an inspectable object.
def get_tree_info(decision_tree, feature_names=None, **export_graphviz_kwargs): # type: (...) -> TreeInfo """ Convert DecisionTreeClassifier or DecisionTreeRegressor to an inspectable object. """ return TreeInfo( criterion=decision_tree.criterion, ...
Return an explanation of estimator prediction as an IPython.display.HTML object. Use this function to show information about classifier prediction in IPython. :func:`show_prediction` accepts all :func:`eli5.explain_prediction` arguments and all :func:`eli5.formatters.html.format_as_html` keywor...
def show_prediction(estimator, doc, **kwargs): """ Return an explanation of estimator prediction as an IPython.display.HTML object. Use this function to show information about classifier prediction in IPython. :func:`show_prediction` accepts all :func:`eli5.explain_prediction` arguments and all ...
Return ``n_samples`` changed versions of text (with some words removed), along with distances between the original text and a generated examples. If ``bow=False``, all tokens are considered unique (i.e. token position matters).
def generate_samples(text, # type: TokenizedText n_samples=500, # type: int bow=True, # type: bool random_state=None, replacement='', # type: str min_replace=1, # type: Uni...
Return cosine similarity between a binary vector with all ones of length ``num_tokens`` and vectors of the same length with ``num_removed_vec`` elements set to zero.
def cosine_similarity_vec(num_tokens, num_removed_vec): """ Return cosine similarity between a binary vector with all ones of length ``num_tokens`` and vectors of the same length with ``num_removed_vec`` elements set to zero. """ remaining = -np.array(num_removed_vec) + num_tokens return rem...
Return a list of ``(text, replaced_count, mask)`` tuples with n_samples versions of text with some words replaced. By default words are replaced with '', i.e. removed.
def replace_random_tokens(self, n_samples, # type: int replacement='', # type: str random_state=None, min_replace=1, # type: Union[int, float] max_replace=1.0, # type...
Return a list of ``(text, replaced_words_count, mask)`` tuples with n_samples versions of text with some words replaced. If a word is replaced, all duplicate words are also replaced from the text. By default words are replaced with '', i.e. removed.
def replace_random_tokens_bow(self, n_samples, # type: int replacement='', # type: str random_state=None, min_replace=1, # type: Union[int, float] ...
Explain ``predict_proba`` probabilistic classification function for the ``doc`` example. This method fits a local classification pipeline following LIME approach. To get the explanation use :meth:`show_prediction`, :meth:`show_weights`, :meth:`explain_prediction` or :meth:`expla...
def fit(self, doc, # type: str predict_proba, # type: Callable[[Any], Any] ): # type: (...) -> TextExplainer """ Explain ``predict_proba`` probabilistic classification function for the ``doc`` example. This method fits a local classificat...
Call :func:`eli5.show_prediction` for the locally-fit classification pipeline. Keyword arguments are passed to :func:`eli5.show_prediction`. :func:`fit` must be called before using this method.
def show_prediction(self, **kwargs): """ Call :func:`eli5.show_prediction` for the locally-fit classification pipeline. Keyword arguments are passed to :func:`eli5.show_prediction`. :func:`fit` must be called before using this method. """ self._fix_target_names(k...
Call :func:`eli5.show_weights` for the locally-fit classification pipeline. Keyword arguments are passed to :func:`eli5.show_weights`. :func:`fit` must be called before using this method.
def show_weights(self, **kwargs): """ Call :func:`eli5.show_weights` for the locally-fit classification pipeline. Keyword arguments are passed to :func:`eli5.show_weights`. :func:`fit` must be called before using this method. """ self._fix_target_names(kwargs) ...
Call :func:`eli5.show_weights` for the locally-fit classification pipeline. Keyword arguments are passed to :func:`eli5.show_weights`. :func:`fit` must be called before using this method.
def explain_weights(self, **kwargs): """ Call :func:`eli5.show_weights` for the locally-fit classification pipeline. Keyword arguments are passed to :func:`eli5.show_weights`. :func:`fit` must be called before using this method. """ self._fix_target_names(kwargs)...
Fit classifier ``clf`` to return probabilities close to ``y_proba``. scikit-learn can't optimize cross-entropy directly if target probability values are not indicator vectors. As a workaround this function expands the dataset according to target probabilities. Use expand_factor=None to turn it off ...
def fit_proba(clf, X, y_proba, expand_factor=10, sample_weight=None, shuffle=True, random_state=None, **fit_params): """ Fit classifier ``clf`` to return probabilities close to ``y_proba``. scikit-learn can't optimize cross-entropy directly if target probability values are n...
Return fit_params with added "sample_weight" argument. Unlike `fit_params['sample_weight'] = sample_weight` it handles a case where ``clf`` is a pipeline.
def with_sample_weight(clf, sample_weight, fit_params): """ Return fit_params with added "sample_weight" argument. Unlike `fit_params['sample_weight'] = sample_weight` it handles a case where ``clf`` is a pipeline. """ param_name = _get_classifier_prefix(clf) + "sample_weight" params = {para...
Add missing columns to predict_proba result. When a multiclass classifier is fit on a dataset which only contains a subset of possible classes its predict_proba result only has columns corresponding to seen classes. This function adds missing columns.
def fix_multiclass_predict_proba(y_proba, # type: np.ndarray seen_classes, complete_classes ): # type: (...) -> np.ndarray """ Add missing columns to predict_proba result. When a multiclass class...
Convert a dataset with float multiclass probabilities to a dataset with indicator probabilities by duplicating X rows and sampling true labels.
def expand_dataset(X, y_proba, factor=10, random_state=None, extra_arrays=None): """ Convert a dataset with float multiclass probabilities to a dataset with indicator probabilities by duplicating X rows and sampling true labels. """ rng = check_random_state(random_state) extra_arrays = extra...
scikit-learn can't optimize cross-entropy directly if target probability values are not indicator vectors. As a workaround this function expands the dataset according to target probabilities. ``expand_factor=None`` means no dataset expansion.
def expanded_X_y_sample_weights(X, y_proba, expand_factor=10, sample_weight=None, shuffle=True, random_state=None): """ scikit-learn can't optimize cross-entropy directly if target probability values are not indicator vectors. As a workarou...
Get feature names for transformer output as a function of input names. Used by :func:`explain_weights` when applied to a scikit-learn Pipeline, this ``singledispatch`` should be registered with custom name transformations for each class of transformer. If there is no ``singledispatch`` handler reg...
def transform_feature_names(transformer, in_names=None): """Get feature names for transformer output as a function of input names. Used by :func:`explain_weights` when applied to a scikit-learn Pipeline, this ``singledispatch`` should be registered with custom name transformations for each class of tra...
If possible, return a dict with preprocessed document and a list of spans with weights, corresponding to features in the document.
def get_weighted_spans(doc, vec, feature_weights): # type: (Any, Any, FeatureWeights) -> Optional[WeightedSpans] """ If possible, return a dict with preprocessed document and a list of spans with weights, corresponding to features in the document. """ if isinstance(vec, FeatureUnion): return...
Compute and set ``target_expl.weighted_spans`` attribute, when possible.
def add_weighted_spans(doc, vec, vectorized, target_expl): # type: (Any, Any, bool, TargetExplanation) -> None """ Compute and set ``target_expl.weighted_spans`` attribute, when possible. """ if vec is None or vectorized: return weighted_spans = get_weighted_spans(doc, vec, target_expl....
Compute ``feature_importances_`` attribute and optionally fit the base estimator. Parameters ---------- X : array-like of shape (n_samples, n_features) The training input samples. y : array-like, shape (n_samples,) The target values (integers that corres...
def fit(self, X, y, groups=None, **fit_params): # type: (...) -> PermutationImportance """Compute ``feature_importances_`` attribute and optionally fit the base estimator. Parameters ---------- X : array-like of shape (n_samples, n_features) The training inpu...
Return an explanation of an estimator prediction. :func:`explain_prediction` is not doing any work itself, it dispatches to a concrete implementation based on estimator type. Parameters ---------- estimator : object Estimator instance. This argument must be positional. doc : object ...
def explain_prediction(estimator, doc, **kwargs): """ Return an explanation of an estimator prediction. :func:`explain_prediction` is not doing any work itself, it dispatches to a concrete implementation based on estimator type. Parameters ---------- estimator : object Estimator in...
Get directions between an origin point and a destination point. :param origin: The address or latitude/longitude value from which you wish to calculate directions. :type origin: string, dict, list, or tuple :param destination: The address or latitude/longitude value from which you wish to ...
def directions(client, origin, destination, mode=None, waypoints=None, alternatives=False, avoid=None, language=None, units=None, region=None, departure_time=None, arrival_time=None, optimize_waypoints=False, transit_mode=None, transit_routing_preference=None,...
Geocoding is the process of converting addresses (like ``"1600 Amphitheatre Parkway, Mountain View, CA"``) into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map. :param address: The address to geocode. :type address: ...
def geocode(client, address=None, components=None, bounds=None, region=None, language=None): """ Geocoding is the process of converting addresses (like ``"1600 Amphitheatre Parkway, Mountain View, CA"``) into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which y...
Reverse geocoding is the process of converting geographic coordinates into a human-readable address. :param latlng: The latitude/longitude value or place_id for which you wish to obtain the closest, human-readable address. :type latlng: string, dict, list, or tuple :param result_type: One or m...
def reverse_geocode(client, latlng, result_type=None, location_type=None, language=None): """ Reverse geocoding is the process of converting geographic coordinates into a human-readable address. :param latlng: The latitude/longitude value or place_id for which you wish to ob...
Provides elevation data for locations provided on the surface of the earth, including depth locations on the ocean floor (which return negative values) :param locations: List of latitude/longitude values from which you wish to calculate elevation data. :type locations: a single location, or a l...
def elevation(client, locations): """ Provides elevation data for locations provided on the surface of the earth, including depth locations on the ocean floor (which return negative values) :param locations: List of latitude/longitude values from which you wish to calculate elevation data. ...
Converts a lat/lon pair to a comma-separated string. For example: sydney = { "lat" : -33.8674869, "lng" : 151.2069902 } convert.latlng(sydney) # '-33.8674869,151.2069902' For convenience, also accepts lat/lon pair as a string, in which case it's returned unchanged. :...
def latlng(arg): """Converts a lat/lon pair to a comma-separated string. For example: sydney = { "lat" : -33.8674869, "lng" : 151.2069902 } convert.latlng(sydney) # '-33.8674869,151.2069902' For convenience, also accepts lat/lon pair as a string, in which case it's re...
Take the various lat/lng representations and return a tuple. Accepts various representations: 1) dict with two entries - "lat" and "lng" 2) list or tuple - e.g. (-33, 151) or [-33, 151] :param arg: The lat/lng pair. :type arg: dict or list or tuple :rtype: tuple (lat, lng)
def normalize_lat_lng(arg): """Take the various lat/lng representations and return a tuple. Accepts various representations: 1) dict with two entries - "lat" and "lng" 2) list or tuple - e.g. (-33, 151) or [-33, 151] :param arg: The lat/lng pair. :type arg: dict or list or tuple :rtype: t...
Joins a list of locations into a pipe separated string, handling the various formats supported for lat/lng values. For example: p = [{"lat" : -33.867486, "lng" : 151.206990}, "Sydney"] convert.waypoint(p) # '-33.867486,151.206990|Sydney' :param arg: The lat/lng list. :type arg: list :...
def location_list(arg): """Joins a list of locations into a pipe separated string, handling the various formats supported for lat/lng values. For example: p = [{"lat" : -33.867486, "lng" : 151.206990}, "Sydney"] convert.waypoint(p) # '-33.867486,151.206990|Sydney' :param arg: The lat/lng l...
Checks if arg is list-like. This excludes strings and dicts.
def _is_list(arg): """Checks if arg is list-like. This excludes strings and dicts.""" if isinstance(arg, dict): return False if isinstance(arg, str): # Python 3-only, as str has __iter__ return False return (not _has_method(arg, "strip") and _has_method(arg, "__getitem__") ...
Determines whether the passed value is a string, safe for 2/3.
def is_string(val): """Determines whether the passed value is a string, safe for 2/3.""" try: basestring except NameError: return isinstance(val, str) return isinstance(val, basestring)
Converts the value into a unix time (seconds since unix epoch). For example: convert.time(datetime.now()) # '1409810596' :param arg: The time. :type arg: datetime.datetime or int
def time(arg): """Converts the value into a unix time (seconds since unix epoch). For example: convert.time(datetime.now()) # '1409810596' :param arg: The time. :type arg: datetime.datetime or int """ # handle datetime instances. if _has_method(arg, "timetuple"): ar...
Returns true if the given object has a method with the given name. :param arg: the object :param method: the method name :type method: string :rtype: bool
def _has_method(arg, method): """Returns true if the given object has a method with the given name. :param arg: the object :param method: the method name :type method: string :rtype: bool """ return hasattr(arg, method) and callable(getattr(arg, method))
Converts a dict of components to the format expected by the Google Maps server. For example: c = {"country": "US", "postal_code": "94043"} convert.components(c) # 'country:US|postal_code:94043' :param arg: The component filter. :type arg: dict :rtype: basestring
def components(arg): """Converts a dict of components to the format expected by the Google Maps server. For example: c = {"country": "US", "postal_code": "94043"} convert.components(c) # 'country:US|postal_code:94043' :param arg: The component filter. :type arg: dict :rtype: bases...
Converts a lat/lon bounds to a comma- and pipe-separated string. Accepts two representations: 1) string: pipe-separated pair of comma-separated lat/lon pairs. 2) dict with two entries - "southwest" and "northeast". See convert.latlng for information on how these can be represented. For example: ...
def bounds(arg): """Converts a lat/lon bounds to a comma- and pipe-separated string. Accepts two representations: 1) string: pipe-separated pair of comma-separated lat/lon pairs. 2) dict with two entries - "southwest" and "northeast". See convert.latlng for information on how these can be represent...
Decodes a Polyline string into a list of lat/lng dicts. See the developer docs for a detailed description of this encoding: https://developers.google.com/maps/documentation/utilities/polylinealgorithm :param polyline: An encoded polyline :type polyline: string :rtype: list of dicts with lat/lng k...
def decode_polyline(polyline): """Decodes a Polyline string into a list of lat/lng dicts. See the developer docs for a detailed description of this encoding: https://developers.google.com/maps/documentation/utilities/polylinealgorithm :param polyline: An encoded polyline :type polyline: string ...
Encodes a list of points into a polyline string. See the developer docs for a detailed description of this encoding: https://developers.google.com/maps/documentation/utilities/polylinealgorithm :param points: a list of lat/lng pairs :type points: list of dicts or tuples :rtype: string
def encode_polyline(points): """Encodes a list of points into a polyline string. See the developer docs for a detailed description of this encoding: https://developers.google.com/maps/documentation/utilities/polylinealgorithm :param points: a list of lat/lng pairs :type points: list of dicts or tu...
Get time zone for a location on the earth, as well as that location's time offset from UTC. :param location: The latitude/longitude value representing the location to look up. :type location: string, dict, list, or tuple :param timestamp: Timestamp specifies the desired time as seconds since ...
def timezone(client, location, timestamp=None, language=None): """Get time zone for a location on the earth, as well as that location's time offset from UTC. :param location: The latitude/longitude value representing the location to look up. :type location: string, dict, list, or tuple :pa...
Snaps a path to the most likely roads travelled. Takes up to 100 GPS points collected along a route, and returns a similar set of data with the points snapped to the most likely roads the vehicle was traveling along. :param path: The path to be snapped. :type path: a single location, or a list of ...
def snap_to_roads(client, path, interpolate=False): """Snaps a path to the most likely roads travelled. Takes up to 100 GPS points collected along a route, and returns a similar set of data with the points snapped to the most likely roads the vehicle was traveling along. :param path: The path to b...
Find the closest road segments for each point Takes up to 100 independent coordinates, and returns the closest road segment for each point. The points passed do not need to be part of a continuous path. :param points: The points for which the nearest road segments are to be located. :type ...
def nearest_roads(client, points): """Find the closest road segments for each point Takes up to 100 independent coordinates, and returns the closest road segment for each point. The points passed do not need to be part of a continuous path. :param points: The points for which the nearest road segm...
Returns the posted speed limit (in km/h) for given road segments. :param place_ids: The Place ID of the road segment. Place IDs are returned by the snap_to_roads function. You can pass up to 100 Place IDs. :type place_ids: str or list :rtype: list of speed limits.
def speed_limits(client, place_ids): """Returns the posted speed limit (in km/h) for given road segments. :param place_ids: The Place ID of the road segment. Place IDs are returned by the snap_to_roads function. You can pass up to 100 Place IDs. :type place_ids: str or list :rtype: list of spe...
Returns the posted speed limit (in km/h) for given road segments. The provided points will first be snapped to the most likely roads the vehicle was traveling along. :param path: The path of points to be snapped. :type path: a single location, or a list of locations, where a location is a stri...
def snapped_speed_limits(client, path): """Returns the posted speed limit (in km/h) for given road segments. The provided points will first be snapped to the most likely roads the vehicle was traveling along. :param path: The path of points to be snapped. :type path: a single location, or a list o...
Extracts a result from a Roads API HTTP response.
def _roads_extract(resp): """Extracts a result from a Roads API HTTP response.""" try: j = resp.json() except: if resp.status_code != 200: raise googlemaps.exceptions.HTTPError(resp.status_code) raise googlemaps.exceptions.ApiError("UNKNOWN_ERROR", ...
A Find Place request takes a text input, and returns a place. The text input can be any kind of Places data, for example, a name, address, or phone number. :param input: The text input specifying which place to search for (for example, a name, address, or phone number). :type input: s...
def find_place(client, input, input_type, fields=None, location_bias=None, language=None): """ A Find Place request takes a text input, and returns a place. The text input can be any kind of Places data, for example, a name, address, or phone number. :param input: The text input spe...
Places search. :param query: The text string on which to search, for example: "restaurant". :type query: string :param location: The latitude/longitude value for which you wish to obtain the closest, human-readable address. :type location: string, dict, list, or tuple :param radius: Dista...
def places(client, query, location=None, radius=None, language=None, min_price=None, max_price=None, open_now=False, type=None, region=None, page_token=None): """ Places search. :param query: The text string on which to search, for example: "restaurant". :type query: string :...
Performs nearby search for places. :param location: The latitude/longitude value for which you wish to obtain the closest, human-readable address. :type location: string, dict, list, or tuple :param radius: Distance in meters within which to bias results. :type radius: int :p...
def places_nearby(client, location=None, radius=None, keyword=None, language=None, min_price=None, max_price=None, name=None, open_now=False, rank_by=None, type=None, page_token=None): """ Performs nearby search for places. :param location: The latitude/longitude value f...
Performs radar search for places. :param location: The latitude/longitude value for which you wish to obtain the closest, human-readable address. :type location: string, dict, list, or tuple :param radius: Distance in meters within which to bias results. :type radius: int :pa...
def places_radar(client, location, radius, keyword=None, min_price=None, max_price=None, name=None, open_now=False, type=None): """ Performs radar search for places. :param location: The latitude/longitude value for which you wish to obtain the closest, human-readable ...
Internal handler for ``places``, ``places_nearby``, and ``places_radar``. See each method's docs for arg details.
def _places(client, url_part, query=None, location=None, radius=None, keyword=None, language=None, min_price=0, max_price=4, name=None, open_now=False, rank_by=None, type=None, region=None, page_token=None): """ Internal handler for ``places``, ``places_nearby``, and ``places_radar``. ...
Comprehensive details for an individual place. :param place_id: A textual identifier that uniquely identifies a place, returned from a Places search. :type place_id: string :param session_token: A random string which identifies an autocomplete session for billing purposes...
def place(client, place_id, session_token=None, fields=None, language=None): """ Comprehensive details for an individual place. :param place_id: A textual identifier that uniquely identifies a place, returned from a Places search. :type place_id: string :param session_token: A random strin...
Downloads a photo from the Places API. :param photo_reference: A string identifier that uniquely identifies a photo, as provided by either a Places search or Places detail request. :type photo_reference: string :param max_width: Specifies the maximum desired width, in pixels. :type max_width: ...
def places_photo(client, photo_reference, max_width=None, max_height=None): """ Downloads a photo from the Places API. :param photo_reference: A string identifier that uniquely identifies a photo, as provided by either a Places search or Places detail request. :type photo_reference: string ...
Returns Place predictions given a textual search string and optional geographic bounds. :param input_text: The text string on which to search. :type input_text: string :param session_token: A random string which identifies an autocomplete session for billing purposes. :ty...
def places_autocomplete(client, input_text, session_token, offset=None, location=None, radius=None, language=None, types=None, components=None, strict_bounds=False): """ Returns Place predictions given a textual search string and optional geographic bounds. ...