INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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. | 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. | 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. | 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. | 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) |
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):
""" Return an explanation of a lightning estimator predicti... |
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 for predictions where i... | 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 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 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 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. | 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. | 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 ) 0 0a0 0b0 00 0 | 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. | 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. | def explain_prediction_linear_classifier(clf, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets... |
Explain prediction of a linear regressor. | def explain_prediction_linear_regressor(reg, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets=None,... |
Explain prediction of a tree classifier. | 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 tree regressor. | 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 definitions... | 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. | 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. | 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 ( coef [ 0 1 2 ] ) array ( [... | 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: | 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,
... |
Sample near the document by replacing some of its features with values sampled from distribution found by KDE. | def sample_near(self, doc, n_samples=1):
"""
Sample near the document by replacing some of its features
with values sampled from distribution found by KDE.
"""
doc = np.asarray(doc)
num_features = len(self.kdes_)
sizes = self.rng_.randint(low=1, high=num_features ... |
All feature names for a feature: usually just the feature itself but can be several features for unhashed features with collisions. | def _all_feature_names(name):
# type: (Union[str, bytes, List[Dict]]) -> List[str]
""" All feature names for a feature: usually just the feature itself,
but can be several features for unhashed features with collisions.
"""
if isinstance(name, bytes):
return [name.decode('utf8')]
elif is... |
Return feature names filtered by a regular expression feature_re and indices of filtered elements. | def filtered(self, feature_filter, x=None):
# type: (Callable, Any) -> Tuple[FeatureNames, List[int]]
""" Return feature names filtered by a regular expression
``feature_re``, and indices of filtered elements.
"""
indices = []
filtered_feature_names = []
indexed_... |
Add a new feature name return it s index. | def add_feature(self, feature):
# type: (Any) -> int
""" Add a new feature name, return it's index.
"""
# A copy of self.feature_names is always made, because it might be
# "owned" by someone else.
# It's possible to make the copy only at the first call to
# self.... |
Format explanation as text. | def format_as_text(expl, # type: Explanation
show=fields.ALL,
highlight_spaces=None, # type: Optional[bool]
show_feature_values=False, # type: bool
):
# type: (...) -> str
""" Format explanation as text.
Parameters
---------... |
Format feature name for hashed features. | def _format_unhashed_feature(name, hl_spaces, sep=' | '):
# type: (List, bool, str) -> str
"""
Format feature name for hashed features.
"""
return sep.join(
format_signed(n, _format_single_feature, hl_spaces=hl_spaces)
for n in name) |
Return a ( pos neg ) tuple. pos and neg are lists of ( name value ) tuples for features with positive and negative coefficients. | def _get_top_features(feature_names, coef, top, x):
"""
Return a ``(pos, neg)`` tuple. ``pos`` and ``neg`` are lists of
``(name, value)`` tuples for features with positive and negative
coefficients.
Parameters:
* ``feature_names`` - a vector of feature names;
* ``coef`` - coefficient vecto... |
Return character weights for a text document with highlighted features. If preserve_density is True then color for longer fragments will be less intensive than for shorter fragments so that sum of intensities will correspond to feature weight. If preserve_density is None then it s value is taken from the corresponding ... | def get_char_weights(doc_weighted_spans, preserve_density=None):
# type: (DocWeightedSpans, Optional[bool]) -> np.ndarray
""" Return character weights for a text document with highlighted features.
If preserve_density is True, then color for longer fragments will be
less intensive than for shorter fragm... |
Return weighted spans prepared for rendering. Calculate a separate weight range for each different weighted span ( for each different index ): each target has the same number of weighted spans. | def prepare_weighted_spans(targets, # type: List[TargetExplanation]
preserve_density=None, # type: Optional[bool]
):
# type: (...) -> List[Optional[List[PreparedWeightedSpans]]]
""" Return weighted spans prepared for rendering.
Calculate a separate wei... |
Return an analyzer and the preprocessed doc. Analyzer will yield pairs of spans and feature where spans are pairs of indices into the preprocessed doc. The idea here is to do minimal preprocessing so that we can still recover the same features as sklearn vectorizers but with spans that will allow us to highlight featur... | def build_span_analyzer(document, vec):
""" Return an analyzer and the preprocessed doc.
Analyzer will yield pairs of spans and feature, where spans are pairs
of indices into the preprocessed doc. The idea here is to do minimal
preprocessing so that we can still recover the same features as sklearn
... |
Return an explanation of an XGBoost estimator ( via scikit - learn wrapper XGBClassifier or XGBRegressor or via xgboost. Booster ) as feature importances. | def explain_weights_xgboost(xgb,
vec=None,
top=20,
target_names=None, # ignored
targets=None, # ignored
feature_names=None,
feature_re=None, # type: ... |
Return an explanation of XGBoost prediction ( via scikit - learn wrapper XGBClassifier or XGBRegressor or via xgboost. Booster ) as feature weights. | def explain_prediction_xgboost(
xgb, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets=None,
feature_names=None,
feature_re=None, # type: Pattern[str]
feature_filter=None,
vectorized=False, # type: bool
is_regr... |
For each target return score and numpy array with feature weights on this prediction following an idea from http:// blog. datadive. net/ interpreting - random - forests/ | def _prediction_feature_weights(booster, dmatrix, n_targets,
feature_names, xgb_feature_names):
""" For each target, return score and numpy array with feature weights
on this prediction, following an idea from
http://blog.datadive.net/interpreting-random-forests/
"""
... |
Return a leaf nodeid - > node dictionary with parent and leaf ( average child leaf value ) added to all nodes. | def _indexed_leafs(parent):
""" Return a leaf nodeid -> node dictionary with
"parent" and "leaf" (average child "leaf" value) added to all nodes.
"""
if not parent.get('children'):
return {parent['nodeid']: parent}
indexed = {}
for child in parent['children']:
child['parent'] = p... |
Value of the parent node: a weighted sum of child values. | def _parent_value(children):
# type: (...) -> int
""" Value of the parent node: a weighted sum of child values.
"""
covers = np.array([child['cover'] for child in children])
covers /= np.sum(covers)
leafs = np.array([child['leaf'] for child in children])
return np.sum(leafs * covers) |
Parse text tree dump ( one item of a list returned by Booster. get_dump () ) into json format that will be used by next XGBoost release. | def _parse_tree_dump(text_dump):
# type: (str) -> Optional[Dict[str, Any]]
""" Parse text tree dump (one item of a list returned by Booster.get_dump())
into json format that will be used by next XGBoost release.
"""
result = None
stack = [] # type: List[Dict]
for line in text_dump.split('\n... |
Return a copy of values where missing values ( equal to missing_value ) are replaced to nan according. If sparse_missing is True entries missing in a sparse matrix will also be set to nan. Sparse matrices will be converted to dense format. | def _missing_values_set_to_nan(values, missing_value, sparse_missing):
""" Return a copy of values where missing values (equal to missing_value)
are replaced to nan according. If sparse_missing is True,
entries missing in a sparse matrix will also be set to nan.
Sparse matrices will be converted to dens... |
Return no more than k indices of smallest values. | def argsort_k_smallest(x, k):
""" Return no more than ``k`` indices of smallest values. """
if k == 0:
return np.array([], dtype=np.intp)
if k is None or k >= len(x):
return np.argsort(x)
indices = np.argpartition(x, k)[:k]
values = x[indices]
return indices[np.argsort(values)] |
The same as x [ indices ] but return an empty array if indices are empty instead of returning all x elements and handles sparse vectors. | def mask(x, indices):
"""
The same as x[indices], but return an empty array if indices are empty,
instead of returning all x elements,
and handles sparse "vectors".
"""
indices_shape = (
[len(indices)] if isinstance(indices, list) else indices.shape)
if not indices_shape[0]:
... |
x is a 2D sparse matrix with it s first shape equal to 1. | def is_sparse_vector(x):
""" x is a 2D sparse matrix with it's first shape equal to 1.
"""
return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1 |
Convert indices to a boolean ( integer ) mask. | def indices_to_bool_mask(indices, size):
""" Convert indices to a boolean (integer) mask.
>>> list(indices_to_bool_mask(np.array([2, 3]), 4))
[False, False, True, True]
>>> list(indices_to_bool_mask([2, 3], 4))
[False, False, True, True]
>>> indices_to_bool_mask(np.array([5]), 2)
Tracebac... |
Return a list of ( target_id display_name ) tuples. | def get_target_display_names(original_names=None, target_names=None,
targets=None, top_targets=None, score=None):
"""
Return a list of (target_id, display_name) tuples.
By default original names are passed as-is, only indices are added:
>>> get_target_display_names(['x', 'y... |
Return ( target_name scale label_id ) tuple for a binary classifier. | def get_binary_target_scale_label_id(score, display_names, proba=None):
"""
Return (target_name, scale, label_id) tuple for a binary classifier.
>>> get_binary_target_scale_label_id(+5.0, get_target_display_names([False, True]))
(True, 1, 1)
>>> get_binary_target_scale_label_id(-5.0, get_target_dis... |
>>> _get_value_indices ( [ foo bar baz ] [ foo bar baz ]... [ bar foo ] ) [ 1 0 ] >>> _get_value_indices ( [ foo bar baz ] [ FOO bar baz ]... [ bar FOO ] ) [ 1 0 ] >>> _get_value_indices ( [ foo bar BAZ ] [ foo BAZ baz ]... [ BAZ foo ] ) [ 2 0 ] >>> _get_value_indices ( [ foo bar baz ] [ foo bar baz ]... [ spam ] ) Tra... | def _get_value_indices(names1, names2, lookups):
"""
>>> _get_value_indices(['foo', 'bar', 'baz'], ['foo', 'bar', 'baz'],
... ['bar', 'foo'])
[1, 0]
>>> _get_value_indices(['foo', 'bar', 'baz'], ['FOO', 'bar', 'baz'],
... ['bar', 'FOO'])
[1, 0]
>>> _... |
Render Graphviz data to SVG | def dot2svg(dot):
# type: (str) -> str
""" Render Graphviz data to SVG """
svg = graphviz.Source(dot).pipe(format='svg').decode('utf8') # type: str
# strip doctype and xml declaration
svg = svg[svg.index('<svg'):]
return svg |
Return an explanation of an estimator | def explain_weights_sklearn(estimator, vec=None, top=_TOP,
target_names=None,
targets=None,
feature_names=None, coef_scale=None,
feature_re=None, feature_filter=None):
""" Return an explanation of an esti... |
Return an explanation of a linear classifier weights. | def explain_linear_classifier_weights(clf,
vec=None,
top=_TOP,
target_names=None,
targets=None,
feature_names=None,
... |
Return an explanation of a tree - based ensemble estimator. | def explain_rf_feature_importance(estimator,
vec=None,
top=_TOP,
target_names=None, # ignored
targets=None, # ignored
feature_names=None,
... |
Return an explanation of a decision tree. | def explain_decision_tree(estimator,
vec=None,
top=_TOP,
target_names=None,
targets=None, # ignored
feature_names=None,
feature_re=None,
... |
Return an explanation of a linear regressor weights. | def explain_linear_regressor_weights(reg,
vec=None,
top=_TOP,
target_names=None,
targets=None,
feature_names=None,
... |
Return an explanation of PermutationImportance. | def explain_permutation_importance(estimator,
vec=None,
top=_TOP,
target_names=None, # ignored
targets=None, # ignored
feature_names=None,
... |
Return a dict { column_id: [ possible term ids ] } with collision information. | def _get_collisions(indices):
# type: (...) -> Dict[int, List[int]]
"""
Return a dict ``{column_id: [possible term ids]}``
with collision information.
"""
collisions = defaultdict(list) # type: Dict[int, List[int]]
for term_id, hash_id in enumerate(indices):
collisions[hash_id].appe... |
For each term from terms return its column index and sign as assigned by FeatureHasher hasher. | def _get_indices_and_signs(hasher, terms):
"""
For each term from ``terms`` return its column index and sign,
as assigned by FeatureHasher ``hasher``.
"""
X = _transform_terms(hasher, terms)
indices = X.nonzero()[1]
signs = X.sum(axis=1).A.ravel()
return indices, signs |
Return feature_names and coef_scale ( if with_coef_scale is True ) calling. get_feature_names for invhashing vectorizers. | def handle_hashing_vec(vec, feature_names, coef_scale, with_coef_scale=True):
""" Return feature_names and coef_scale (if with_coef_scale is True),
calling .get_feature_names for invhashing vectorizers.
"""
needs_coef_scale = with_coef_scale and coef_scale is None
if is_invhashing(vec):
if f... |
Create an: class: ~. InvertableHashingVectorizer from hashing vectorizer vec and fit it on docs. If vec is a FeatureUnion do it for all hashing vectorizers in the union. Return an: class: ~. InvertableHashingVectorizer or a FeatureUnion or an unchanged vectorizer. | def invert_hashing_and_fit(
vec, # type: Union[FeatureUnion, HashingVectorizer]
docs
):
# type: (...) -> Union[FeatureUnion, InvertableHashingVectorizer]
""" Create an :class:`~.InvertableHashingVectorizer` from hashing
vectorizer vec and fit it on docs. If vec is a FeatureUnion, do it ... |
Fit InvertableHashingVectorizer on doc inside a FeatureUnion. | def _fit_invhashing_union(vec_union, docs):
# type: (FeatureUnion, Any) -> FeatureUnion
""" Fit InvertableHashingVectorizer on doc inside a FeatureUnion.
"""
return FeatureUnion(
[(name, invert_hashing_and_fit(v, docs))
for name, v in vec_union.transformer_list],
transformer_wei... |
Extract possible terms from documents | def fit(self, X, y=None):
""" Extract possible terms from documents """
self.unhasher.fit(self._get_terms_iter(X))
return self |
Return feature names. This is a best - effort function which tries to reconstruct feature names based on what it has seen so far. | def get_feature_names(self, always_signed=True):
# type: (bool) -> FeatureNames
"""
Return feature names.
This is a best-effort function which tries to reconstruct feature
names based on what it has seen so far.
HashingVectorizer uses a signed hash function. If always_si... |
Return a numpy array with expected signs of features. Values are | def column_signs_(self):
"""
Return a numpy array with expected signs of features.
Values are
* +1 when all known terms which map to the column have positive sign;
* -1 when all known terms which map to the column have negative sign;
* ``nan`` when there are both positiv... |
Update all computed attributes. It is only needed if you need to access computed attributes after: meth: patrial_fit was called. | def recalculate_attributes(self, force=False):
# type: (bool) -> None
"""
Update all computed attributes. It is only needed if you need to access
computed attributes after :meth:`patrial_fit` was called.
"""
if not self._attributes_dirty and not force:
return
... |
Return text representation of a decision tree. | def tree2text(tree_obj, indent=4):
# type: (TreeInfo, int) -> str
"""
Return text representation of a decision tree.
"""
parts = []
def _format_node(node, depth=0):
# type: (NodeInfo, int) -> None
def p(*args):
# type: (*str) -> None
parts.append(" " * de... |
>>> _format_array ( [ 0 1. 0 ] {: 0. 3f } ) [ 0. 000 1. 000 ] | def _format_array(x, fmt):
# type: (Any, str) -> str
"""
>>> _format_array([0, 1.0], "{:0.3f}")
'[0.000, 1.000]'
"""
value_repr = ", ".join(fmt.format(v) for v in x)
return "[{}]".format(value_repr) |
Explain weights and export them to pandas. DataFrame. All keyword arguments are passed to: func: eli5. explain_weights. Weights of all features are exported by default. | def explain_weights_df(estimator, **kwargs):
# type: (...) -> pd.DataFrame
""" Explain weights and export them to ``pandas.DataFrame``.
All keyword arguments are passed to :func:`eli5.explain_weights`.
Weights of all features are exported by default.
"""
kwargs = _set_defaults(kwargs)
return... |
Explain weights and export them to a dict with pandas. DataFrame values ( as: func: eli5. formatters. as_dataframe. format_as_dataframes does ). All keyword arguments are passed to: func: eli5. explain_weights. Weights of all features are exported by default. | def explain_weights_dfs(estimator, **kwargs):
# type: (...) -> Dict[str, pd.DataFrame]
""" Explain weights and export them to a dict with ``pandas.DataFrame``
values (as :func:`eli5.formatters.as_dataframe.format_as_dataframes` does).
All keyword arguments are passed to :func:`eli5.explain_weights`.
... |
Explain prediction and export explanation to pandas. DataFrame All keyword arguments are passed to: func: eli5. explain_prediction. Weights of all features are exported by default. | def explain_prediction_df(estimator, doc, **kwargs):
# type: (...) -> pd.DataFrame
""" Explain prediction and export explanation to ``pandas.DataFrame``
All keyword arguments are passed to :func:`eli5.explain_prediction`.
Weights of all features are exported by default.
"""
kwargs = _set_default... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.