INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Remove all elements in the sorted set ``name`` between the lexicographical range specified by ``min`` and ``max``. Returns the number of elements removed.
def zremrangebylex(self, name, min, max): """ Remove all elements in the sorted set ``name`` between the lexicographical range specified by ``min`` and ``max``. Returns the number of elements removed. """ return self.execute_command('ZREMRANGEBYLEX', name, min, max)
Remove all elements in the sorted set ``name`` with ranks between ``min`` and ``max``. Values are 0-based, ordered from smallest score to largest. Values can be negative indicating the highest scores. Returns the number of elements removed
def zremrangebyrank(self, name, min, max): """ Remove all elements in the sorted set ``name`` with ranks between ``min`` and ``max``. Values are 0-based, ordered from smallest score to largest. Values can be negative indicating the highest scores. Returns the number of elements r...
Return a range of values from the sorted set ``name`` with scores between ``min`` and ``max`` in descending order. If ``start`` and ``num`` are specified, then return a slice of the range. ``withscores`` indicates to return the scores along with the values. The return type is a...
def zrevrangebyscore(self, name, max, min, start=None, num=None, withscores=False, score_cast_func=float): """ Return a range of values from the sorted set ``name`` with scores between ``min`` and ``max`` in descending order. If ``start`` and ``num`` are specifi...
Union multiple sorted sets specified by ``keys`` into a new sorted set, ``dest``. Scores in the destination will be aggregated based on the ``aggregate``, or SUM if none is provided.
def zunionstore(self, dest, keys, aggregate=None): """ Union multiple sorted sets specified by ``keys`` into a new sorted set, ``dest``. Scores in the destination will be aggregated based on the ``aggregate``, or SUM if none is provided. """ return self._zaggregate('ZUNIO...
Returns a list of values ordered identically to ``keys``
def hmget(self, name, keys, *args): "Returns a list of values ordered identically to ``keys``" args = list_or_args(keys, args) return self.execute_command('HMGET', name, *args)
Execute the Lua ``script``, specifying the ``numkeys`` the script will touch and the key names and argument values in ``keys_and_args``. Returns the result of the script. In practice, use the object returned by ``register_script``. This function exists purely for Redis API completion.
def eval(self, script, numkeys, *keys_and_args): """ Execute the Lua ``script``, specifying the ``numkeys`` the script will touch and the key names and argument values in ``keys_and_args``. Returns the result of the script. In practice, use the object returned by ``register_scri...
Use the ``sha`` to execute a Lua script already registered via EVAL or SCRIPT LOAD. Specify the ``numkeys`` the script will touch and the key names and argument values in ``keys_and_args``. Returns the result of the script. In practice, use the object returned by ``register_script``. Th...
def evalsha(self, sha, numkeys, *keys_and_args): """ Use the ``sha`` to execute a Lua script already registered via EVAL or SCRIPT LOAD. Specify the ``numkeys`` the script will touch and the key names and argument values in ``keys_and_args``. Returns the result of the script. ...
Add the specified geospatial items to the specified key identified by the ``name`` argument. The Geospatial items are given as ordered members of the ``values`` argument, each item or place is formed by the triad longitude, latitude and name.
def geoadd(self, name, *values): """ Add the specified geospatial items to the specified key identified by the ``name`` argument. The Geospatial items are given as ordered members of the ``values`` argument, each item or place is formed by the triad longitude, latitude and name. ...
Return the distance between ``place1`` and ``place2`` members of the ``name`` key. The units must be one of the following : m, km mi, ft. By default meters are used.
def geodist(self, name, place1, place2, unit=None): """ Return the distance between ``place1`` and ``place2`` members of the ``name`` key. The units must be one of the following : m, km mi, ft. By default meters are used. """ pieces = [name, place1, place2] ...
Re-subscribe to any channels and patterns previously subscribed to
def on_connect(self, connection): "Re-subscribe to any channels and patterns previously subscribed to" # NOTE: for python3, we can't pass bytestrings as keyword arguments # so we need to decode channel/pattern names back to unicode strings # before passing them to [p]subscribe. s...
Parse the response from a publish/subscribe command
def parse_response(self, block=True, timeout=0): "Parse the response from a publish/subscribe command" connection = self.connection if connection is None: raise RuntimeError( 'pubsub connection not set: ' 'did you forget to call subscribe() or psubscri...
normalize channel/pattern names to be either bytes or strings based on whether responses are automatically decoded. this saves us from coercing the value for each message coming in.
def _normalize_keys(self, data): """ normalize channel/pattern names to be either bytes or strings based on whether responses are automatically decoded. this saves us from coercing the value for each message coming in. """ encode = self.encoder.encode decode = sel...
Subscribe to channel patterns. Patterns supplied as keyword arguments expect a pattern name as the key and a callable as the value. A pattern's callable will be invoked automatically when a message is received on that pattern rather than producing a message via ``listen()``.
def psubscribe(self, *args, **kwargs): """ Subscribe to channel patterns. Patterns supplied as keyword arguments expect a pattern name as the key and a callable as the value. A pattern's callable will be invoked automatically when a message is received on that pattern rather than...
Unsubscribe from the supplied patterns. If empty, unsubscribe from all patterns.
def punsubscribe(self, *args): """ Unsubscribe from the supplied patterns. If empty, unsubscribe from all patterns. """ if args: args = list_or_args(args[0], args[1:]) patterns = self._normalize_keys(dict.fromkeys(args)) else: patterns ...
Subscribe to channels. Channels supplied as keyword arguments expect a channel name as the key and a callable as the value. A channel's callable will be invoked automatically when a message is received on that channel rather than producing a message via ``listen()`` or ``get_message()``.
def subscribe(self, *args, **kwargs): """ Subscribe to channels. Channels supplied as keyword arguments expect a channel name as the key and a callable as the value. A channel's callable will be invoked automatically when a message is received on that channel rather than producin...
Unsubscribe from the supplied channels. If empty, unsubscribe from all channels
def unsubscribe(self, *args): """ Unsubscribe from the supplied channels. If empty, unsubscribe from all channels """ if args: args = list_or_args(args[0], args[1:]) channels = self._normalize_keys(dict.fromkeys(args)) else: channels = ...
Parses a pub/sub message. If the channel or pattern was subscribed to with a message handler, the handler is invoked instead of a parsed message being returned.
def handle_message(self, response, ignore_subscribe_messages=False): """ Parses a pub/sub message. If the channel or pattern was subscribed to with a message handler, the handler is invoked instead of a parsed message being returned. """ message_type = nativestr(response[...
Start a transactional block of the pipeline after WATCH commands are issued. End the transactional block with `execute`.
def multi(self): """ Start a transactional block of the pipeline after WATCH commands are issued. End the transactional block with `execute`. """ if self.explicit_transaction: raise RedisError('Cannot issue nested calls to MULTI') if self.command_stack: ...
Stage a command to be executed when execute() is next called Returns the current Pipeline object back so commands can be chained together, such as: pipe = pipe.set('foo', 'bar').incr('baz').decr('bang') At some other point, you can then run: pipe.execute(), which will execute ...
def pipeline_execute_command(self, *args, **options): """ Stage a command to be executed when execute() is next called Returns the current Pipeline object back so commands can be chained together, such as: pipe = pipe.set('foo', 'bar').incr('baz').decr('bang') At some ...
Reset the state of the instance to when it was constructed
def reset(self): """ Reset the state of the instance to when it was constructed """ self.operations = [] self._last_overflow = 'WRAP' self.overflow(self._default_overflow or self._last_overflow)
Update the overflow algorithm of successive INCRBY operations :param overflow: Overflow algorithm, one of WRAP, SAT, FAIL. See the Redis docs for descriptions of these algorithmsself. :returns: a :py:class:`BitFieldOperation` instance.
def overflow(self, overflow): """ Update the overflow algorithm of successive INCRBY operations :param overflow: Overflow algorithm, one of WRAP, SAT, FAIL. See the Redis docs for descriptions of these algorithmsself. :returns: a :py:class:`BitFieldOperation` instance. ...
Get the value of a given bitfield. :param fmt: format-string for the bitfield being read, e.g. 'u8' for an unsigned 8-bit integer. :param offset: offset (in number of bits). If prefixed with a '#', this is an offset multiplier, e.g. given the arguments fmt='u8', offse...
def get(self, fmt, offset): """ Get the value of a given bitfield. :param fmt: format-string for the bitfield being read, e.g. 'u8' for an unsigned 8-bit integer. :param offset: offset (in number of bits). If prefixed with a '#', this is an offset multiplier, e.g....
Set the value of a given bitfield. :param fmt: format-string for the bitfield being read, e.g. 'u8' for an unsigned 8-bit integer. :param offset: offset (in number of bits). If prefixed with a '#', this is an offset multiplier, e.g. given the arguments fmt='u8', offse...
def set(self, fmt, offset, value): """ Set the value of a given bitfield. :param fmt: format-string for the bitfield being read, e.g. 'u8' for an unsigned 8-bit integer. :param offset: offset (in number of bits). If prefixed with a '#', this is an offset multiplie...
Execute the operation(s) in a single BITFIELD command. The return value is a list of values corresponding to each operation. If the client used to create this instance was a pipeline, the list of values will be present within the pipeline's execute.
def execute(self): """ Execute the operation(s) in a single BITFIELD command. The return value is a list of values corresponding to each operation. If the client used to create this instance was a pipeline, the list of values will be present within the pipeline's execute. ...
Gets a cached token object or creates a new one if not already cached
def get_token(cls, value): "Gets a cached token object or creates a new one if not already cached" # Use try/except because after running for a short time most tokens # should already be cached try: return cls._cache[value] except KeyError: token = Token(...
Return a bytestring representation of the value
def encode(self, value): "Return a bytestring representation of the value" if isinstance(value, Token): return value.encoded_value elif isinstance(value, bytes): return value elif isinstance(value, bool): # special case bool since it is a subclass of i...
Return a unicode string from the byte representation
def decode(self, value, force=False): "Return a unicode string from the byte representation" if (self.decode_responses or force) and isinstance(value, bytes): value = value.decode(self.encoding, self.encoding_errors) return value
Called when the socket connects
def on_connect(self, connection): "Called when the socket connects" self._sock = connection._sock self._buffer = SocketBuffer(self._sock, self.socket_read_size) self.encoder = connection.encoder
Parse an error response
def parse_error(self, response): "Parse an error response" error_code = response.split(' ')[0] if error_code in self.EXCEPTION_CLASSES: response = response[len(error_code) + 1:] exception_class = self.EXCEPTION_CLASSES[error_code] if isinstance(exception_class...
Called when the socket disconnects
def on_disconnect(self): "Called when the socket disconnects" self._sock = None if self._buffer is not None: self._buffer.close() self._buffer = None self.encoder = None
Connects to the Redis server if not already connected
def connect(self): "Connects to the Redis server if not already connected" if self._sock: return try: sock = self._connect() except socket.timeout: raise TimeoutError("Timeout connecting to server") except socket.error: e = sys.exc_...
Disconnects from the Redis server
def disconnect(self): "Disconnects from the Redis server" self._parser.on_disconnect() if self._sock is None: return if self._selector is not None: self._selector.close() self._selector = None try: if os.getpid() == self.pid: ...
Send an already packed command to the Redis server
def send_packed_command(self, command): "Send an already packed command to the Redis server" if not self._sock: self.connect() try: if isinstance(command, str): command = [command] for item in command: self._sock.sendall(item) ...
Poll the socket to see if there's data that can be read.
def can_read(self, timeout=0): "Poll the socket to see if there's data that can be read." sock = self._sock if not sock: self.connect() sock = self._sock return self._parser.can_read() or self._selector.can_read(timeout)
Read the response from a previously sent command
def read_response(self): "Read the response from a previously sent command" try: response = self._parser.read_response() except socket.timeout: self.disconnect() raise TimeoutError("Timeout reading from %s:%s" % (self.host, self....
Pack a series of arguments into the Redis protocol
def pack_command(self, *args): "Pack a series of arguments into the Redis protocol" output = [] # the client might have included 1 or more literal arguments in # the command name, e.g., 'CONFIG GET'. The Redis server expects these # arguments to be sent separately, so split the f...
Wrap the socket with SSL support
def _connect(self): "Wrap the socket with SSL support" sock = super(SSLConnection, self)._connect() if hasattr(ssl, "create_default_context"): context = ssl.create_default_context() context.check_hostname = False context.verify_mode = self.cert_reqs ...
Create a Unix domain socket connection
def _connect(self): "Create a Unix domain socket connection" sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(self.socket_timeout) sock.connect(self.path) return sock
Return a connection pool configured from the given URL. For example:: redis://[:password]@localhost:6379/0 rediss://[:password]@localhost:6379/0 unix://[:password]@/path/to/socket.sock?db=0 Three URL schemes are supported: - ```redis://`` <https:...
def from_url(cls, url, db=None, decode_components=False, **kwargs): """ Return a connection pool configured from the given URL. For example:: redis://[:password]@localhost:6379/0 rediss://[:password]@localhost:6379/0 unix://[:password]@/path/to/socket.sock?d...
Get a connection from the pool
def get_connection(self, command_name, *keys, **options): "Get a connection from the pool" self._checkpid() try: connection = self._available_connections.pop() except IndexError: connection = self.make_connection() self._in_use_connections.add(connection) ...
Return an encoder based on encoding settings
def get_encoder(self): "Return an encoder based on encoding settings" kwargs = self.connection_kwargs return Encoder( encoding=kwargs.get('encoding', 'utf-8'), encoding_errors=kwargs.get('encoding_errors', 'strict'), decode_responses=kwargs.get('decode_respons...
Create a new connection
def make_connection(self): "Create a new connection" if self._created_connections >= self.max_connections: raise ConnectionError("Too many connections") self._created_connections += 1 return self.connection_class(**self.connection_kwargs)
Disconnects all connections in the pool
def disconnect(self): "Disconnects all connections in the pool" self._checkpid() all_conns = chain(self._available_connections, self._in_use_connections) for connection in all_conns: connection.disconnect()
Make a fresh connection.
def make_connection(self): "Make a fresh connection." connection = self.connection_class(**self.connection_kwargs) self._connections.append(connection) return connection
Get a connection, blocking for ``self.timeout`` until a connection is available from the pool. If the connection returned is ``None`` then creates a new connection. Because we use a last-in first-out queue, the existing connections (having been returned to the pool after the initial ``N...
def get_connection(self, command_name, *keys, **options): """ Get a connection, blocking for ``self.timeout`` until a connection is available from the pool. If the connection returned is ``None`` then creates a new connection. Because we use a last-in first-out queue, the existi...
Releases the connection back to the pool.
def release(self, connection): "Releases the connection back to the pool." # Make sure we haven't changed process. self._checkpid() if connection.pid != self.pid: return # Put the connection back into the pool. try: self.pool.put_nowait(connection...
Pack a series of arguments into a value Redis command
def pack_command(self, *args): "Pack a series of arguments into a value Redis command" args_output = SYM_EMPTY.join([ SYM_EMPTY.join( (SYM_DOLLAR, str(len(k)).encode(), SYM_CRLF, k, SYM_CRLF)) for k in imap(self.encoder.encode, args)]) output = SYM_EMPTY.j...
Determine if the current platform has the selector available
def has_selector(selector): "Determine if the current platform has the selector available" try: if selector == 'poll': # the select module offers the poll selector even if the platform # doesn't support it. Attempt to poll for nothing to make sure # poll is available ...
Return the best selector for the platform
def DefaultSelector(sock): "Return the best selector for the platform" global _DEFAULT_SELECTOR if _DEFAULT_SELECTOR is None: if has_selector('poll'): _DEFAULT_SELECTOR = PollSelector elif hasattr(select, 'select'): _DEFAULT_SELECTOR = SelectSelector else: ...
Return True if data is ready to be read from the socket, otherwise False. This doesn't guarentee that the socket is still connected, just that there is data to read. Automatically retries EINTR errors based on PEP 475.
def can_read(self, timeout=0): """ Return True if data is ready to be read from the socket, otherwise False. This doesn't guarentee that the socket is still connected, just that there is data to read. Automatically retries EINTR errors based on PEP 475. """ ...
Return True if the socket is ready to send a command, otherwise False. Automatically retries EINTR errors based on PEP 475.
def is_ready_for_command(self, timeout=0): """ Return True if the socket is ready to send a command, otherwise False. Automatically retries EINTR errors based on PEP 475. """ while True: try: return self.check_is_ready_for_command(timeout) ...
Get the error number from an exception
def errno_from_exception(self, ex): """ Get the error number from an exception """ if hasattr(ex, 'errno'): return ex.errno elif ex.args: return ex.args[0] else: return None
Returns an active Redis client generated from the given database URL. Will attempt to extract the database id from the path url fragment, if none is provided.
def from_url(url, db=None, **kwargs): """ Returns an active Redis client generated from the given database URL. Will attempt to extract the database id from the path url fragment, if none is provided. """ from redis.client import Redis return Redis.from_url(url, db, **kwargs)
Round-robin slave balancer
def rotate_slaves(self): "Round-robin slave balancer" slaves = self.sentinel_manager.discover_slaves(self.service_name) if slaves: if self.slave_rr_counter is None: self.slave_rr_counter = random.randint(0, len(slaves) - 1) for _ in xrange(len(slaves)): ...
Asks sentinel servers for the Redis master's address corresponding to the service labeled ``service_name``. Returns a pair (address, port) or raises MasterNotFoundError if no master is found.
def discover_master(self, service_name): """ Asks sentinel servers for the Redis master's address corresponding to the service labeled ``service_name``. Returns a pair (address, port) or raises MasterNotFoundError if no master is found. """ for sentinel_no, senti...
Remove slaves that are in an ODOWN or SDOWN state
def filter_slaves(self, slaves): "Remove slaves that are in an ODOWN or SDOWN state" slaves_alive = [] for slave in slaves: if slave['is_odown'] or slave['is_sdown']: continue slaves_alive.append((slave['ip'], slave['port'])) return slaves_alive
Returns a list of alive slaves for service ``service_name``
def discover_slaves(self, service_name): "Returns a list of alive slaves for service ``service_name``" for sentinel in self.sentinels: try: slaves = sentinel.sentinel_slaves(service_name) except (ConnectionError, ResponseError, TimeoutError): conti...
Return an explanation of a lightning estimator weights
def explain_weights_lightning(estimator, vec=None, top=20, target_names=None, targets=None, feature_names=None, coef_scale=None): """ Return an explanation of a lightning estimator weights """ return explain_weights_lightning_not_supported(estimator)
Format explanation as html. Most styles are inline, but some are included separately in <style> tag, you can omit them by passing ``include_styles=False`` and call ``format_html_styles`` to render them separately (or just omit them). With ``force_weights=False``, weights will not be displayed in a table...
def format_as_html(explanation, # type: Explanation include_styles=True, # type: bool force_weights=True, # type: bool show=fields.ALL, preserve_density=None, # type: Optional[bool] highlight_spaces=None, # type: Optiona...
Return a list of rendered weighted spans for targets. Function must accept a list in order to select consistent weight ranges across all targets.
def render_targets_weighted_spans( targets, # type: List[TargetExplanation] preserve_density, # type: Optional[bool] ): # type: (...) -> List[Optional[str]] """ Return a list of rendered weighted spans for targets. Function must accept a list in order to select consistent weight ra...
Return opacity value for given weight as a string.
def _weight_opacity(weight, weight_range): # type: (float, float) -> str """ Return opacity value for given weight as a string. """ min_opacity = 0.8 if np.isclose(weight, 0) and np.isclose(weight_range, 0): rel_weight = 0.0 else: rel_weight = abs(weight) / weight_range retur...
Return token wrapped in a span with some styles (calculated from weight and weight_range) applied.
def _colorize(token, # type: str weight, # type: float weight_range, # type: float ): # type: (...) -> str """ Return token wrapped in a span with some styles (calculated from weight and weight_range) applied. """ token = html_escape(token) if np.iscl...
Return HSL color components for given weight, where the max absolute weight is given by weight_range.
def weight_color_hsl(weight, weight_range, min_lightness=0.8): # type: (float, float, float) -> _HSL_COLOR """ Return HSL color components for given weight, where the max absolute weight is given by weight_range. """ hue = _hue(weight) saturation = 1 rel_weight = (abs(weight) / weight_range)...
Format hsl color as css color string.
def format_hsl(hsl_color): # type: (_HSL_COLOR) -> str """ Format hsl color as css color string. """ hue, saturation, lightness = hsl_color return 'hsl({}, {:.2%}, {:.2%})'.format(hue, saturation, lightness)
Max absolute feature for pos and neg weights.
def get_weight_range(weights): # type: (FeatureWeights) -> float """ Max absolute feature for pos and neg weights. """ return max_or_0(abs(fw.weight) for lst in [weights.pos, weights.neg] for fw in lst or [])
Color for "remaining" row. Handles a number of edge cases: if there are no weights in ws or weight_range is zero, assume the worst (most intensive positive or negative color).
def remaining_weight_color_hsl( ws, # type: List[FeatureWeight] weight_range, # type: float pos_neg, # type: str ): # type: (...) -> _HSL_COLOR """ Color for "remaining" row. Handles a number of edge cases: if there are no weights in ws or weight_range is zero, assume the ...
Format unhashed feature: show first (most probable) candidate, display other candidates in title attribute.
def _format_unhashed_feature(feature, weight, hl_spaces): # type: (...) -> str """ Format unhashed feature: show first (most probable) candidate, display other candidates in title attribute. """ if not feature: return '' else: first, rest = feature[0], feature[1:] html = ...
Format any feature.
def _format_feature(feature, weight, hl_spaces): # type: (...) -> str """ Format any feature. """ if isinstance(feature, FormattedFeatureName): return feature.format() elif (isinstance(feature, list) and all('name' in x and 'sign' in x for x in feature)): return _format_u...
Return an explanation of an LightGBM estimator (via scikit-learn wrapper LGBMClassifier or LGBMRegressor) as feature importances. See :func:`eli5.explain_weights` for description of ``top``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``target_names`` and ``targets`` param...
def explain_weights_lightgbm(lgb, vec=None, top=20, target_names=None, # ignored targets=None, # ignored feature_names=None, feature_re=None, ...
Return an explanation of LightGBM prediction (via scikit-learn wrapper LGBMClassifier or LGBMRegressor) as feature weights. See :func:`eli5.explain_prediction` for description of ``top``, ``top_targets``, ``target_names``, ``targets``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters...
def explain_prediction_lightgbm( lgb, doc, vec=None, top=None, top_targets=None, target_names=None, targets=None, feature_names=None, feature_re=None, feature_filter=None, vectorized=False, ): """ Return an explanation of LightG...
Add node_value key with an expected value for non-leaf nodes
def _compute_node_values(tree_info): """ Add node_value key with an expected value for non-leaf nodes """ def walk(tree): if 'leaf_value' in tree: return tree['leaf_value'], tree.get('leaf_count', 0) left_value, left_count = walk(tree['left_child']) right_value, right_count =...
>>> _changes([2, 3, 0, 5]) [2, 1, -3, 5] >>> _changes([2]) [2]
def _changes(path): """ >>> _changes([2, 3, 0, 5]) [2, 1, -3, 5] >>> _changes([2]) [2] """ res = [path[0]] res += [p - p_prev for p, p_prev in zip(path[1:], path)] return res
Return a list of {feat_id: value} dicts with feature weights, following ideas from http://blog.datadive.net/interpreting-random-forests/
def _get_prediction_feature_weights(lgb, X, n_targets): """ Return a list of {feat_id: value} dicts with feature weights, following ideas from http://blog.datadive.net/interpreting-random-forests/ """ if n_targets == 2: n_targets = 1 dump = lgb.booster_.dump_model() tree_info = ...
>>> replace_spaces('ab', lambda n, l: '_' * n) 'ab' >>> replace_spaces('a b', lambda n, l: '_' * n) 'a_b' >>> replace_spaces(' ab', lambda n, l: '_' * n) '_ab' >>> replace_spaces(' a b ', lambda n, s: s * n) 'leftleftacenterbright' >>> replace_spaces(' a b ', lambda n, _: '0 0' * n) ...
def replace_spaces(s, replacer): # type: (str, Callable[[int, str], str]) -> str """ >>> replace_spaces('ab', lambda n, l: '_' * n) 'ab' >>> replace_spaces('a b', lambda n, l: '_' * n) 'a_b' >>> replace_spaces(' ab', lambda n, l: '_' * n) '_ab' >>> replace_spaces(' a b ', lambda n, ...
Format unhashed feature with sign. >>> format_signed({'name': 'foo', 'sign': 1}) 'foo' >>> format_signed({'name': 'foo', 'sign': -1}) '(-)foo' >>> format_signed({'name': ' foo', 'sign': -1}, lambda x: '"{}"'.format(x)) '(-)" foo"'
def format_signed(feature, # type: Dict[str, Any] formatter=None, # type: Callable[..., str] **kwargs ): # type: (...) -> str """ Format unhashed feature with sign. >>> format_signed({'name': 'foo', 'sign': 1}) 'foo' >>> format_signed({'na...
Format data as a table without any fancy features. col_align: l/r/c or a list/string of l/r/c. l = left, r = right, c = center Return a list of strings (lines of the table).
def tabulate(data, # type: List[List[Any]] header=None, # type: Optional[List[Any]] col_align=None, # type: Union[str, List[str]] ): # type: (...) -> List[str] """ Format data as a table without any fancy features. col_align: l/r/c or a list/string of l/r/c. l = lef...
Return an explanation of a scikit-learn estimator
def explain_prediction_sklearn(estimator, doc, vec=None, top=None, top_targets=None, target_names=None, targets=None, feature_names=No...
Explain prediction of a linear classifier. See :func:`eli5.explain_prediction` for description of ``top``, ``top_targets``, ``target_names``, ``targets``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``vec`` is a vectorizer instance used to transform raw features to the inp...
def explain_prediction_linear_classifier(clf, doc, vec=None, top=None, top_targets=None, target_names=None, targets...
Explain prediction of a tree classifier. See :func:`eli5.explain_prediction` for description of ``top``, ``top_targets``, ``target_names``, ``targets``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``vec`` is a vectorizer instance used to transform raw features to the input...
def explain_prediction_tree_classifier( clf, doc, vec=None, top=None, top_targets=None, target_names=None, targets=None, feature_names=None, feature_re=None, feature_filter=None, vectorized=False): """ Explain prediction of a tree class...
Explain prediction of a linear regressor. See :func:`eli5.explain_prediction` for description of ``top``, ``top_targets``, ``target_names``, ``targets``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``vec`` is a vectorizer instance used to transform raw features to the inpu...
def explain_prediction_linear_regressor(reg, doc, vec=None, top=None, top_targets=None, target_names=None, targets=None,...
Explain prediction of a tree regressor. See :func:`eli5.explain_prediction` for description of ``top``, ``top_targets``, ``target_names``, ``targets``, ``feature_names``, ``feature_re`` and ``feature_filter`` parameters. ``vec`` is a vectorizer instance used to transform raw features to the input ...
def explain_prediction_tree_regressor( reg, doc, vec=None, top=None, top_targets=None, target_names=None, targets=None, feature_names=None, feature_re=None, feature_filter=None, vectorized=False): """ Explain prediction of a tree regres...
Return feature weights for a tree or a tree ensemble.
def _trees_feature_weights(clf, X, feature_names, num_targets): """ Return feature weights for a tree or a tree ensemble. """ feature_weights = np.zeros([len(feature_names), num_targets]) if hasattr(clf, 'tree_'): _update_tree_feature_weights(X, feature_names, clf, feature_weights) else: ...
Update tree feature weights using decision path method.
def _update_tree_feature_weights(X, feature_names, clf, feature_weights): """ Update tree feature weights using decision path method. """ tree_value = clf.tree_.value if tree_value.shape[1] == 1: squeeze_axis = 1 else: assert tree_value.shape[2] == 1 squeeze_axis = 2 tree...
Multiple X by coef element-wise, preserving sparsity.
def _multiply(X, coef): """ Multiple X by coef element-wise, preserving sparsity. """ if sp.issparse(X): return X.multiply(sp.csr_matrix(coef)) else: return np.multiply(X, coef)
Return top weights getter for label_id.
def _linear_weights(clf, x, top, flt_feature_names, flt_indices): """ Return top weights getter for label_id. """ def _weights(label_id, scale=1.0): coef = get_coef(clf, label_id) scores = _multiply(x, coef) return get_top_features_filtered(x, flt_feature_names, flt_indices, ...
Like attr.s with slots=True, but with attributes extracted from __init__ method signature. slots=True ensures that signature matches what really happens (we can't define different attributes on self). It is useful if we still want __init__ for proper type-checking and do not want to repeat attribute...
def attrs(class_): """ Like attr.s with slots=True, but with attributes extracted from __init__ method signature. slots=True ensures that signature matches what really happens (we can't define different attributes on self). It is useful if we still want __init__ for proper type-checking and do n...
Return True if a classifier can return probabilities
def is_probabilistic_classifier(clf): # type: (Any) -> bool """ Return True if a classifier can return probabilities """ if not hasattr(clf, 'predict_proba'): return False if isinstance(clf, OneVsRestClassifier): # It currently has a predict_proba method, but does not check if # ...
Return result of predict_proba, if an estimator supports it, or None.
def predict_proba(estimator, X): # type: (Any, Any) -> Optional[np.ndarray] """ Return result of predict_proba, if an estimator supports it, or None. """ if is_probabilistic_classifier(estimator): try: proba, = estimator.predict_proba(X) return proba except NotImp...
Return True if an estimator has intercept fit.
def has_intercept(estimator): # type: (Any) -> bool """ Return True if an estimator has intercept fit. """ if hasattr(estimator, 'fit_intercept'): return estimator.fit_intercept if hasattr(estimator, 'intercept_'): if estimator.intercept_ is None: return False # sciki...
Return a FeatureNames instance that holds all feature names and a bias feature. If vec is None or doesn't have get_feature_names() method, features are named x0, x1, x2, etc.
def get_feature_names(clf, vec=None, bias_name='<BIAS>', feature_names=None, num_features=None, estimator_feature_names=None): # type: (Any, Any, Optional[str], Any, int, Any) -> FeatureNames """ Return a FeatureNames instance that holds all feature names and a bias feature. If...
Return a vector of target names: "y" if there is only one target, and "y0", "y1", ... if there are multiple targets.
def get_default_target_names(estimator, num_targets=None): """ Return a vector of target names: "y" if there is only one target, and "y0", "y1", ... if there are multiple targets. """ if num_targets is None: if len(estimator.coef_.shape) <= 1: num_targets = 1 else: ...
Return a vector of coefficients for a given label, including bias feature. ``scale`` (optional) is a scaling vector; coef_[i] => coef[i] * scale[i] if scale[i] is not nan. Intercept is not scaled.
def get_coef(clf, label_id, scale=None): """ Return a vector of coefficients for a given label, including bias feature. ``scale`` (optional) is a scaling vector; coef_[i] => coef[i] * scale[i] if scale[i] is not nan. Intercept is not scaled. """ if len(clf.coef_.shape) == 2: # Most ...
Return size of a feature vector estimator expects as an input.
def get_num_features(estimator): """ Return size of a feature vector estimator expects as an input. """ if hasattr(estimator, 'coef_'): # linear models if len(estimator.coef_.shape) == 0: return 1 return estimator.coef_.shape[-1] elif hasattr(estimator, 'feature_importances_'): ...
Return zero-th element of a one-element data container.
def get_X0(X): """ Return zero-th element of a one-element data container. """ if pandas_available and isinstance(X, pd.DataFrame): assert len(X) == 1 x = np.array(X.iloc[0]) else: x, = X return x
Add intercept column to X
def add_intercept(X): """ Add intercept column to X """ intercept = np.ones((X.shape[0], 1)) if sp.issparse(X): return sp.hstack([X, intercept]).tocsr() else: return np.hstack([X, intercept])
Explain sklearn_crfsuite.CRF weights. See :func:`eli5.explain_weights` for description of ``top``, ``target_names``, ``targets``, ``feature_re`` and ``feature_filter`` parameters.
def explain_weights_sklearn_crfsuite(crf, top=20, target_names=None, targets=None, feature_re=None, feature_filter=None): """ Expla...
>>> coef = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> filter_transition_coefs(coef, [0]) array([[0]]) >>> filter_transition_coefs(coef, [1, 2]) array([[4, 5], [7, 8]]) >>> filter_transition_coefs(coef, [2, 0]) array([[8, 6], [2, 0]]) >>> filter_transition_coefs(coe...
def filter_transition_coefs(transition_coef, indices): """ >>> coef = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> filter_transition_coefs(coef, [0]) array([[0]]) >>> filter_transition_coefs(coef, [1, 2]) array([[4, 5], [7, 8]]) >>> filter_transition_coefs(coef, [2, 0]) arr...
Return labels sorted in a default order suitable for NER tasks: >>> sorted_for_ner(['B-ORG', 'B-PER', 'O', 'I-PER']) ['O', 'B-ORG', 'B-PER', 'I-PER']
def sorted_for_ner(crf_classes): """ Return labels sorted in a default order suitable for NER tasks: >>> sorted_for_ner(['B-ORG', 'B-PER', 'O', 'I-PER']) ['O', 'B-ORG', 'B-PER', 'I-PER'] """ def key(cls): if len(cls) > 2 and cls[1] == '-': # group names like B-ORG and I-ORG ...
Convert an nested dict/list/tuple that might contain numpy objects to their python equivalents. Return converted object.
def _numpy_to_python(obj): """ Convert an nested dict/list/tuple that might contain numpy objects to their python equivalents. Return converted object. """ if isinstance(obj, dict): return {k: _numpy_to_python(v) for k, v in obj.items()} elif isinstance(obj, (list, tuple, np.ndarray)): ...
Return (sampler, n_samplers) tuples
def _sampler_n_samples(self, n_samples): """ Return (sampler, n_samplers) tuples """ sampler_indices = self.rng_.choice(range(len(self.samplers)), size=n_samples, replace=True, ...