text
stringlengths
81
112k
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...
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_...
>>> _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'...
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 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...
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 ...
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...
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 ...
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...
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[in...
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) ...
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 invhash...
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( ...
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 ...
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...
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...
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 com...
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: ...
>>> _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.DataFram...
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): ...
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 ex...
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(esti...
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 ...
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 ...
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...
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 ...
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...
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...
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 inspectab...
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 ...
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 ...
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='', # ...
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, ...
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...
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 l...
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 ...
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-fi...
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 ...
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_we...
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, # t...
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...
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 wit...
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...
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...
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 {feat_name: (weight, (group, idx))} mapping. def _get_feature_weights_dict(feature_weights, # type: FeatureWeights feature_fn # type: Optional[Callable[[str], str]] ): # type: (...) -> Dict[str, Tuple[float, Tuple[str, int]]] """ Return...
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...
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 ...
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 ...
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: ...
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...
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...
Provides elevation data sampled along a path on the surface of the earth. :param path: An encoded polyline string, or a list of latitude/longitude values from which you wish to calculate elevation data. :type path: string, dict, list, or tuple :param samples: The number of sample points along a pa...
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. :...
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_...
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 :...
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(ar...
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: ...
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 m...
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 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: ...
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...
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...
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 ...
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 ...
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 ...
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_i...
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...
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.excepti...
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...
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...
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...
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...
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, ...
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...
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: ...
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...
Returns Place predictions given a textual search query, such as "pizza near New York", and optional geographic bounds. :param input_text: The text query on which to search. :type input_text: string :param offset: The position, in the input term, of the last character that the service uses to m...
Internal handler for ``autocomplete`` and ``autocomplete_query``. See each method's docs for arg details. def _autocomplete(client, url_part, input_text, session_token=None, offset=None, location=None, radius=None, language=None, types=None, components=None, strict_bounds=False)...
Mimics the exception handling logic in ``client._get_body``, but for geolocation which uses a different response format. def _geolocation_extract(response): """ Mimics the exception handling logic in ``client._get_body``, but for geolocation which uses a different response format. """ body = re...
The Google Maps Geolocation API returns a location and accuracy radius based on information about cell towers and WiFi nodes given. See https://developers.google.com/maps/documentation/geolocation/intro for more info, including more detail for each parameter below. :param home_mobile_country_code: The...
Gets travel distance and time for a matrix of origins and destinations. :param origins: One or more locations and/or latitude/longitude values, from which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a latitude/lon...
Provides a single entry point for modifying all API methods. For now this is limited to allowing the client object to be modified with an `extra_params` keyword arg to each method, that is then used as the params for each web service request. Please note that this is an unsupported feature for advanced...
Returns a base64-encoded HMAC-SHA1 signature of a given string. :param secret: The key used for the signature, base64 encoded. :type secret: string :param payload: The payload to sign. :type payload: string :rtype: string def sign_hmac(secret, payload): """Returns a base64-encoded HMAC-SHA1 ...
URL encodes the parameters. :param params: The parameters :type params: list of key/value tuples. :rtype: string def urlencode_params(params): """URL encodes the parameters. :param params: The parameters :type params: list of key/value tuples. :rtype: string """ # urlencode does...
Performs HTTP GET/POST with credentials, returning the body as JSON. :param url: URL path for the request. Should begin with a slash. :type url: string :param params: HTTP GET parameters. :type params: dict or list of key/value tuples :param first_request_time: The tim...
Returns the path and query string portion of the request URL, first adding any necessary parameters. :param path: The path portion of the URL. :type path: string :param params: URL parameters. :type params: dict or list of key/value tuples :rtype: string def _generate...
Run all jobs that are scheduled to run. Please note that it is *intended behavior that run_pending() does not run missed jobs*. For example, if you've registered a job that should run every minute and you only call run_pending() in one hour increments then your job won't be run 60 times...
Run all jobs regardless if they are scheduled to run or not. A delay of `delay` seconds is added between each job. This helps distribute system load generated by the jobs more evenly over time. :param delay_seconds: A delay added between every executed job def run_all(self, delay_seco...
Deletes scheduled jobs marked with the given tag, or all jobs if tag is omitted. :param tag: An identifier used to identify a subset of jobs to delete def clear(self, tag=None): """ Deletes scheduled jobs marked with the given tag, or all jobs if tag is omit...
Tags the job with one or more unique indentifiers. Tags must be hashable. Duplicate tags are discarded. :param tags: A unique list of ``Hashable`` tags. :return: The invoked job instance def tag(self, *tags): """ Tags the job with one or more unique indentifiers. Tags...
Specify a particular time that the job should be run at. :param time_str: A string in one of the following formats: `HH:MM:SS`, `HH:MM`,`:MM`, `:SS`. The format must make sense given how often the job is repeating; for example, a job that repeats every minute should not be g...
Specifies the job_func that should be called every time the job runs. Any additional arguments are passed on to job_func when the job runs. :param job_func: The function to be scheduled :return: The invoked job instance def do(self, job_func, *args, **kwargs): """ ...
Run the job and immediately reschedule it. :return: The return value returned by the `job_func` def run(self): """ Run the job and immediately reschedule it. :return: The return value returned by the `job_func` """ logger.info('Running job %s', self) ret = self...
Compute the instant when this job should run next. def _schedule_next_run(self): """ Compute the instant when this job should run next. """ if self.unit not in ('seconds', 'minutes', 'hours', 'days', 'weeks'): raise ScheduleValueError('Invalid unit') if self.latest ...
Creates a Class representing an Issuer Credential :param source_id: Tag associated by user of sdk :param attrs: attributes that will form the credential :param cred_def_handle: Handle from previously created credential def object :param name: Name given to the Credential ...