text stringlengths 81 112k |
|---|
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... |
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):
"""
Execut... |
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:
retur... |
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):
... |
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 |
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 i... |
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 |
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"... |
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:
... |
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... |
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 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" ... |
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
... |
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.verif... |
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:... |
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_... |
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'),
... |
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... |
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:
... |
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(se... |
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 ... |
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_... |
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 ... |
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... |
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 th... |
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 ... |
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 maste... |
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['i... |
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 (Connect... |
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 """
ret... |
Return an explanation of a lightning estimator predictions
def explain_prediction_lightning(estimator, doc, vec=None, top=None,
target_names=None, targets=None,
feature_names=None, vectorized=False,
coef_scale=None):
... |
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... |
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: (...) -> Li... |
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
... |
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:
... |
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 we... |
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:... |
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.
... |
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 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... |
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... |
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... |
>>> _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.datadi... |
>>> 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)
... |
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]
... |
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: ... |
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=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... |
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... |
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... |
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 ... |
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_weight... |
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 t... |
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,... |
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... |
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 ... |
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, = es... |
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_ i... |
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_feat... |
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.
""... |
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,
i... |
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_... |
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,
ta... |
>>> 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... |
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-... |
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, dic... |
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,
... |
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.
"""
... |
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 severa... |
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 i... |
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 co... |
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
... |
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;
* ... |
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... |
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=No... |
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 ... |
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... |
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... |
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 ta... |
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'):
... |
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 ch... |
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 t... |
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 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]
value... |
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 "v... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.