partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | StringJoiningConnection.pack_command | Pack a series of arguments into a value Redis command | benchmarks/command_packer_benchmark.py | 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... | 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... | [
"Pack",
"a",
"series",
"of",
"arguments",
"into",
"a",
"value",
"Redis",
"command"
] | andymccurdy/redis-py | python | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/benchmarks/command_packer_benchmark.py#L29-L37 | [
"def",
"pack_command",
"(",
"self",
",",
"*",
"args",
")",
":",
"args_output",
"=",
"SYM_EMPTY",
".",
"join",
"(",
"[",
"SYM_EMPTY",
".",
"join",
"(",
"(",
"SYM_DOLLAR",
",",
"str",
"(",
"len",
"(",
"k",
")",
")",
".",
"encode",
"(",
")",
",",
"S... | cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db |
train | has_selector | Determine if the current platform has the selector available | redis/selector.py | 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
... | 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
... | [
"Determine",
"if",
"the",
"current",
"platform",
"has",
"the",
"selector",
"available"
] | andymccurdy/redis-py | python | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/selector.py#L169-L183 | [
"def",
"has_selector",
"(",
"selector",
")",
":",
"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",
"p",
"=",
"select",
... | cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db |
train | DefaultSelector | Return the best selector for the platform | redis/selector.py | 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:
... | 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",
"the",
"best",
"selector",
"for",
"the",
"platform"
] | andymccurdy/redis-py | python | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/selector.py#L186-L196 | [
"def",
"DefaultSelector",
"(",
"sock",
")",
":",
"global",
"_DEFAULT_SELECTOR",
"if",
"_DEFAULT_SELECTOR",
"is",
"None",
":",
"if",
"has_selector",
"(",
"'poll'",
")",
":",
"_DEFAULT_SELECTOR",
"=",
"PollSelector",
"elif",
"hasattr",
"(",
"select",
",",
"'select... | cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db |
train | BaseSelector.can_read | 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. | redis/selector.py | 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.
"""
... | 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",
"data",
"is",
"ready",
"to",
"be",
"read",
"from",
"the",
"socket",
"otherwise",
"False",
"."
] | andymccurdy/redis-py | python | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/selector.py#L16-L32 | [
"def",
"can_read",
"(",
"self",
",",
"timeout",
"=",
"0",
")",
":",
"while",
"True",
":",
"try",
":",
"return",
"self",
".",
"check_can_read",
"(",
"timeout",
")",
"except",
"(",
"select",
".",
"error",
",",
"IOError",
")",
"as",
"ex",
":",
"if",
"... | cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db |
train | BaseSelector.is_ready_for_command | Return True if the socket is ready to send a command,
otherwise False.
Automatically retries EINTR errors based on PEP 475. | redis/selector.py | 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)
... | 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)
... | [
"Return",
"True",
"if",
"the",
"socket",
"is",
"ready",
"to",
"send",
"a",
"command",
"otherwise",
"False",
"."
] | andymccurdy/redis-py | python | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/selector.py#L34-L47 | [
"def",
"is_ready_for_command",
"(",
"self",
",",
"timeout",
"=",
"0",
")",
":",
"while",
"True",
":",
"try",
":",
"return",
"self",
".",
"check_is_ready_for_command",
"(",
"timeout",
")",
"except",
"(",
"select",
".",
"error",
",",
"IOError",
")",
"as",
... | cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db |
train | BaseSelector.errno_from_exception | Get the error number from an exception | redis/selector.py | 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 | 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 | [
"Get",
"the",
"error",
"number",
"from",
"an",
"exception"
] | andymccurdy/redis-py | python | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/selector.py#L68-L77 | [
"def",
"errno_from_exception",
"(",
"self",
",",
"ex",
")",
":",
"if",
"hasattr",
"(",
"ex",
",",
"'errno'",
")",
":",
"return",
"ex",
".",
"errno",
"elif",
"ex",
".",
"args",
":",
"return",
"ex",
".",
"args",
"[",
"0",
"]",
"else",
":",
"return",
... | cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db |
train | from_url | 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. | redis/utils.py | 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) | 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) | [
"Returns",
"an",
"active",
"Redis",
"client",
"generated",
"from",
"the",
"given",
"database",
"URL",
"."
] | andymccurdy/redis-py | python | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/utils.py#L11-L19 | [
"def",
"from_url",
"(",
"url",
",",
"db",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"redis",
".",
"client",
"import",
"Redis",
"return",
"Redis",
".",
"from_url",
"(",
"url",
",",
"db",
",",
"*",
"*",
"kwargs",
")"
] | cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db |
train | SentinelConnectionPool.rotate_slaves | Round-robin slave balancer | redis/sentinel.py | 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)):
... | 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)):
... | [
"Round",
"-",
"robin",
"slave",
"balancer"
] | andymccurdy/redis-py | python | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/sentinel.py#L109-L125 | [
"def",
"rotate_slaves",
"(",
"self",
")",
":",
"slaves",
"=",
"self",
".",
"sentinel_manager",
".",
"discover_slaves",
"(",
"self",
".",
"service_name",
")",
"if",
"slaves",
":",
"if",
"self",
".",
"slave_rr_counter",
"is",
"None",
":",
"self",
".",
"slave... | cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db |
train | Sentinel.discover_master | 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. | redis/sentinel.py | 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... | 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... | [
"Asks",
"sentinel",
"servers",
"for",
"the",
"Redis",
"master",
"s",
"address",
"corresponding",
"to",
"the",
"service",
"labeled",
"service_name",
"."
] | andymccurdy/redis-py | python | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/sentinel.py#L193-L212 | [
"def",
"discover_master",
"(",
"self",
",",
"service_name",
")",
":",
"for",
"sentinel_no",
",",
"sentinel",
"in",
"enumerate",
"(",
"self",
".",
"sentinels",
")",
":",
"try",
":",
"masters",
"=",
"sentinel",
".",
"sentinel_masters",
"(",
")",
"except",
"(... | cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db |
train | Sentinel.filter_slaves | Remove slaves that are in an ODOWN or SDOWN state | redis/sentinel.py | 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 | 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 | [
"Remove",
"slaves",
"that",
"are",
"in",
"an",
"ODOWN",
"or",
"SDOWN",
"state"
] | andymccurdy/redis-py | python | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/sentinel.py#L214-L221 | [
"def",
"filter_slaves",
"(",
"self",
",",
"slaves",
")",
":",
"slaves_alive",
"=",
"[",
"]",
"for",
"slave",
"in",
"slaves",
":",
"if",
"slave",
"[",
"'is_odown'",
"]",
"or",
"slave",
"[",
"'is_sdown'",
"]",
":",
"continue",
"slaves_alive",
".",
"append"... | cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db |
train | Sentinel.discover_slaves | Returns a list of alive slaves for service ``service_name`` | redis/sentinel.py | 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... | 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... | [
"Returns",
"a",
"list",
"of",
"alive",
"slaves",
"for",
"service",
"service_name"
] | andymccurdy/redis-py | python | https://github.com/andymccurdy/redis-py/blob/cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db/redis/sentinel.py#L223-L233 | [
"def",
"discover_slaves",
"(",
"self",
",",
"service_name",
")",
":",
"for",
"sentinel",
"in",
"self",
".",
"sentinels",
":",
"try",
":",
"slaves",
"=",
"sentinel",
".",
"sentinel_slaves",
"(",
"service_name",
")",
"except",
"(",
"ConnectionError",
",",
"Res... | cdfe2befbe00db4a3c48c9ddd6d64dea15f6f0db |
train | explain_weights_lightning | Return an explanation of a lightning estimator weights | eli5/lightning.py | 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) | 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",
"weights"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/lightning.py#L20-L24 | [
"def",
"explain_weights_lightning",
"(",
"estimator",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"20",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"coef_scale",
"=",
"None",
")",
":",
"return",
"e... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_prediction_lightning | Return an explanation of a lightning estimator predictions | eli5/lightning.py | 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... | 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... | [
"Return",
"an",
"explanation",
"of",
"a",
"lightning",
"estimator",
"predictions"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/lightning.py#L39-L44 | [
"def",
"explain_prediction_lightning",
"(",
"estimator",
",",
"doc",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"vectorized",
"=",
"False",
",",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | format_as_html | 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... | eli5/formatters/html.py | 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... | 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... | [
"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_h... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/html.py#L37-L118 | [
"def",
"format_as_html",
"(",
"explanation",
",",
"# type: Explanation",
"include_styles",
"=",
"True",
",",
"# type: bool",
"force_weights",
"=",
"True",
",",
"# type: bool",
"show",
"=",
"fields",
".",
"ALL",
",",
"preserve_density",
"=",
"None",
",",
"# type: O... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | render_targets_weighted_spans | Return a list of rendered weighted spans for targets.
Function must accept a list in order to select consistent weight
ranges across all targets. | eli5/formatters/html.py | 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... | 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",
"a",
"list",
"of",
"rendered",
"weighted",
"spans",
"for",
"targets",
".",
"Function",
"must",
"accept",
"a",
"list",
"in",
"order",
"to",
"select",
"consistent",
"weight",
"ranges",
"across",
"all",
"targets",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/html.py#L142-L165 | [
"def",
"render_targets_weighted_spans",
"(",
"targets",
",",
"# type: List[TargetExplanation]",
"preserve_density",
",",
"# type: Optional[bool]",
")",
":",
"# type: (...) -> List[Optional[str]]",
"prepared_weighted_spans",
"=",
"prepare_weighted_spans",
"(",
"targets",
",",
"pre... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _colorize | Return token wrapped in a span with some styles
(calculated from weight and weight_range) applied. | eli5/formatters/html.py | 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... | 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",
"token",
"wrapped",
"in",
"a",
"span",
"with",
"some",
"styles",
"(",
"calculated",
"from",
"weight",
"and",
"weight_range",
")",
"applied",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/html.py#L181-L209 | [
"def",
"_colorize",
"(",
"token",
",",
"# type: str",
"weight",
",",
"# type: float",
"weight_range",
",",
"# type: float",
")",
":",
"# type: (...) -> str",
"token",
"=",
"html_escape",
"(",
"token",
")",
"if",
"np",
".",
"isclose",
"(",
"weight",
",",
"0.",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _weight_opacity | Return opacity value for given weight as a string. | eli5/formatters/html.py | 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... | 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",
"opacity",
"value",
"for",
"given",
"weight",
"as",
"a",
"string",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/html.py#L212-L221 | [
"def",
"_weight_opacity",
"(",
"weight",
",",
"weight_range",
")",
":",
"# type: (float, float) -> str",
"min_opacity",
"=",
"0.8",
"if",
"np",
".",
"isclose",
"(",
"weight",
",",
"0",
")",
"and",
"np",
".",
"isclose",
"(",
"weight_range",
",",
"0",
")",
"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | weight_color_hsl | Return HSL color components for given weight,
where the max absolute weight is given by weight_range. | eli5/formatters/html.py | 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)... | 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)... | [
"Return",
"HSL",
"color",
"components",
"for",
"given",
"weight",
"where",
"the",
"max",
"absolute",
"weight",
"is",
"given",
"by",
"weight_range",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/html.py#L227-L236 | [
"def",
"weight_color_hsl",
"(",
"weight",
",",
"weight_range",
",",
"min_lightness",
"=",
"0.8",
")",
":",
"# type: (float, float, float) -> _HSL_COLOR",
"hue",
"=",
"_hue",
"(",
"weight",
")",
"saturation",
"=",
"1",
"rel_weight",
"=",
"(",
"abs",
"(",
"weight"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | format_hsl | Format hsl color as css color string. | eli5/formatters/html.py | 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) | 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) | [
"Format",
"hsl",
"color",
"as",
"css",
"color",
"string",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/html.py#L239-L244 | [
"def",
"format_hsl",
"(",
"hsl_color",
")",
":",
"# type: (_HSL_COLOR) -> str",
"hue",
",",
"saturation",
",",
"lightness",
"=",
"hsl_color",
"return",
"'hsl({}, {:.2%}, {:.2%})'",
".",
"format",
"(",
"hue",
",",
"saturation",
",",
"lightness",
")"
] | 371b402a0676295c05e582a2dd591f7af476b86b |
train | get_weight_range | Max absolute feature for pos and neg weights. | eli5/formatters/html.py | 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 []) | 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 []) | [
"Max",
"absolute",
"feature",
"for",
"pos",
"and",
"neg",
"weights",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/html.py#L252-L258 | [
"def",
"get_weight_range",
"(",
"weights",
")",
":",
"# type: (FeatureWeights) -> float",
"return",
"max_or_0",
"(",
"abs",
"(",
"fw",
".",
"weight",
")",
"for",
"lst",
"in",
"[",
"weights",
".",
"pos",
",",
"weights",
".",
"neg",
"]",
"for",
"fw",
"in",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | remaining_weight_color_hsl | 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). | eli5/formatters/html.py | 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 ... | 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 ... | [
"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",
"n... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/html.py#L261-L279 | [
"def",
"remaining_weight_color_hsl",
"(",
"ws",
",",
"# type: List[FeatureWeight]",
"weight_range",
",",
"# type: float",
"pos_neg",
",",
"# type: str",
")",
":",
"# type: (...) -> _HSL_COLOR",
"sign",
"=",
"{",
"'pos'",
":",
"1.0",
",",
"'neg'",
":",
"-",
"1.0",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _format_unhashed_feature | Format unhashed feature: show first (most probable) candidate,
display other candidates in title attribute. | eli5/formatters/html.py | 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 = ... | 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",
"unhashed",
"feature",
":",
"show",
"first",
"(",
"most",
"probable",
")",
"candidate",
"display",
"other",
"candidates",
"in",
"title",
"attribute",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/html.py#L282-L296 | [
"def",
"_format_unhashed_feature",
"(",
"feature",
",",
"weight",
",",
"hl_spaces",
")",
":",
"# type: (...) -> str",
"if",
"not",
"feature",
":",
"return",
"''",
"else",
":",
"first",
",",
"rest",
"=",
"feature",
"[",
"0",
"]",
",",
"feature",
"[",
"1",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _format_feature | Format any feature. | eli5/formatters/html.py | 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... | 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... | [
"Format",
"any",
"feature",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/html.py#L299-L309 | [
"def",
"_format_feature",
"(",
"feature",
",",
"weight",
",",
"hl_spaces",
")",
":",
"# type: (...) -> str",
"if",
"isinstance",
"(",
"feature",
",",
"FormattedFeatureName",
")",
":",
"return",
"feature",
".",
"format",
"(",
")",
"elif",
"(",
"isinstance",
"("... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_weights_lightgbm | 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... | eli5/lightgbm.py | def explain_weights_lightgbm(lgb,
vec=None,
top=20,
target_names=None, # ignored
targets=None, # ignored
feature_names=None,
feature_re=None,
... | 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",
"an",
"LightGBM",
"estimator",
"(",
"via",
"scikit",
"-",
"learn",
"wrapper",
"LGBMClassifier",
"or",
"LGBMRegressor",
")",
"as",
"feature",
"importances",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/lightgbm.py#L23-L65 | [
"def",
"explain_weights_lightgbm",
"(",
"lgb",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"20",
",",
"target_names",
"=",
"None",
",",
"# ignored",
"targets",
"=",
"None",
",",
"# ignored",
"feature_names",
"=",
"None",
",",
"feature_re",
"=",
"None",
",",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_prediction_lightgbm | 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... | eli5/lightgbm.py | 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... | 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... | [
"Return",
"an",
"explanation",
"of",
"LightGBM",
"prediction",
"(",
"via",
"scikit",
"-",
"learn",
"wrapper",
"LGBMClassifier",
"or",
"LGBMRegressor",
")",
"as",
"feature",
"weights",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/lightgbm.py#L70-L151 | [
"def",
"explain_prediction_lightgbm",
"(",
"lgb",
",",
"doc",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"None",
",",
"top_targets",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"featu... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _compute_node_values | Add node_value key with an expected value for non-leaf nodes | eli5/lightgbm.py | 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 =... | 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 =... | [
"Add",
"node_value",
"key",
"with",
"an",
"expected",
"value",
"for",
"non",
"-",
"leaf",
"nodes"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/lightgbm.py#L170-L187 | [
"def",
"_compute_node_values",
"(",
"tree_info",
")",
":",
"def",
"walk",
"(",
"tree",
")",
":",
"if",
"'leaf_value'",
"in",
"tree",
":",
"return",
"tree",
"[",
"'leaf_value'",
"]",
",",
"tree",
".",
"get",
"(",
"'leaf_count'",
",",
"0",
")",
"left_value... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _changes | >>> _changes([2, 3, 0, 5])
[2, 1, -3, 5]
>>> _changes([2])
[2] | eli5/lightgbm.py | 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 | 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 | [
">>>",
"_changes",
"(",
"[",
"2",
"3",
"0",
"5",
"]",
")",
"[",
"2",
"1",
"-",
"3",
"5",
"]",
">>>",
"_changes",
"(",
"[",
"2",
"]",
")",
"[",
"2",
"]"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/lightgbm.py#L207-L216 | [
"def",
"_changes",
"(",
"path",
")",
":",
"res",
"=",
"[",
"path",
"[",
"0",
"]",
"]",
"res",
"+=",
"[",
"p",
"-",
"p_prev",
"for",
"p",
",",
"p_prev",
"in",
"zip",
"(",
"path",
"[",
"1",
":",
"]",
",",
"path",
")",
"]",
"return",
"res"
] | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _get_prediction_feature_weights | Return a list of {feat_id: value} dicts with feature weights,
following ideas from http://blog.datadive.net/interpreting-random-forests/ | eli5/lightgbm.py | 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 = ... | 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 = ... | [
"Return",
"a",
"list",
"of",
"{",
"feat_id",
":",
"value",
"}",
"dicts",
"with",
"feature",
"weights",
"following",
"ideas",
"from",
"http",
":",
"//",
"blog",
".",
"datadive",
".",
"net",
"/",
"interpreting",
"-",
"random",
"-",
"forests",
"/"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/lightgbm.py#L240-L266 | [
"def",
"_get_prediction_feature_weights",
"(",
"lgb",
",",
"X",
",",
"n_targets",
")",
":",
"if",
"n_targets",
"==",
"2",
":",
"n_targets",
"=",
"1",
"dump",
"=",
"lgb",
".",
"booster_",
".",
"dump_model",
"(",
")",
"tree_info",
"=",
"dump",
"[",
"'tree_... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | replace_spaces | >>> 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)
... | eli5/formatters/utils.py | 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, ... | 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, ... | [
">>>",
"replace_spaces",
"(",
"ab",
"lambda",
"n",
"l",
":",
"_",
"*",
"n",
")",
"ab",
">>>",
"replace_spaces",
"(",
"a",
"b",
"lambda",
"n",
"l",
":",
"_",
"*",
"n",
")",
"a_b",
">>>",
"replace_spaces",
"(",
"ab",
"lambda",
"n",
"l",
":",
"_",
... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/utils.py#L14-L38 | [
"def",
"replace_spaces",
"(",
"s",
",",
"replacer",
")",
":",
"# type: (str, Callable[[int, str], str]) -> str",
"def",
"replace",
"(",
"m",
")",
":",
"# type: (Match[str]) -> str",
"if",
"m",
".",
"start",
"(",
")",
"==",
"0",
":",
"side",
"=",
"'left'",
"eli... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | format_signed | 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"' | eli5/formatters/utils.py | 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... | 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",
"unhashed",
"feature",
"with",
"sign",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/utils.py#L41-L60 | [
"def",
"format_signed",
"(",
"feature",
",",
"# type: Dict[str, Any]",
"formatter",
"=",
"None",
",",
"# type: Callable[..., str]",
"*",
"*",
"kwargs",
")",
":",
"# type: (...) -> str",
"txt",
"=",
"''",
"if",
"feature",
"[",
"'sign'",
"]",
">",
"0",
"else",
"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | tabulate | 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). | eli5/formatters/utils.py | 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... | 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... | [
"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",
"=",
... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/utils.py#L99-L140 | [
"def",
"tabulate",
"(",
"data",
",",
"# type: List[List[Any]]",
"header",
"=",
"None",
",",
"# type: Optional[List[Any]]",
"col_align",
"=",
"None",
",",
"# type: Union[str, List[str]]",
")",
":",
"# type: (...) -> List[str]",
"if",
"not",
"data",
"and",
"not",
"heade... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_prediction_sklearn | Return an explanation of a scikit-learn estimator | eli5/sklearn/explain_prediction.py | def explain_prediction_sklearn(estimator, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets=None,
feature_names=No... | def explain_prediction_sklearn(estimator, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets=None,
feature_names=No... | [
"Return",
"an",
"explanation",
"of",
"a",
"scikit",
"-",
"learn",
"estimator"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_prediction.py#L77-L88 | [
"def",
"explain_prediction_sklearn",
"(",
"estimator",
",",
"doc",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"None",
",",
"top_targets",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_prediction_linear_classifier | 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... | eli5/sklearn/explain_prediction.py | def explain_prediction_linear_classifier(clf, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets... | def explain_prediction_linear_classifier(clf, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets... | [
"Explain",
"prediction",
"of",
"a",
"linear",
"classifier",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_prediction.py#L140-L221 | [
"def",
"explain_prediction_linear_classifier",
"(",
"clf",
",",
"doc",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"None",
",",
"top_targets",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_prediction_linear_regressor | 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... | eli5/sklearn/explain_prediction.py | def explain_prediction_linear_regressor(reg, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets=None,... | def explain_prediction_linear_regressor(reg, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets=None,... | [
"Explain",
"prediction",
"of",
"a",
"linear",
"regressor",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_prediction.py#L258-L331 | [
"def",
"explain_prediction_linear_regressor",
"(",
"reg",
",",
"doc",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"None",
",",
"top_targets",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_prediction_tree_classifier | 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... | eli5/sklearn/explain_prediction.py | 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... | 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",
"classifier",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_prediction.py#L363-L459 | [
"def",
"explain_prediction_tree_classifier",
"(",
"clf",
",",
"doc",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"None",
",",
"top_targets",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_prediction_tree_regressor | 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 ... | eli5/sklearn/explain_prediction.py | 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... | 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... | [
"Explain",
"prediction",
"of",
"a",
"tree",
"regressor",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_prediction.py#L466-L554 | [
"def",
"explain_prediction_tree_regressor",
"(",
"reg",
",",
"doc",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"None",
",",
"top_targets",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _trees_feature_weights | Return feature weights for a tree or a tree ensemble. | eli5/sklearn/explain_prediction.py | 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:
... | 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:
... | [
"Return",
"feature",
"weights",
"for",
"a",
"tree",
"or",
"a",
"tree",
"ensemble",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_prediction.py#L557-L582 | [
"def",
"_trees_feature_weights",
"(",
"clf",
",",
"X",
",",
"feature_names",
",",
"num_targets",
")",
":",
"feature_weights",
"=",
"np",
".",
"zeros",
"(",
"[",
"len",
"(",
"feature_names",
")",
",",
"num_targets",
"]",
")",
"if",
"hasattr",
"(",
"clf",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _update_tree_feature_weights | Update tree feature weights using decision path method. | eli5/sklearn/explain_prediction.py | 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... | 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... | [
"Update",
"tree",
"feature",
"weights",
"using",
"decision",
"path",
"method",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_prediction.py#L585-L606 | [
"def",
"_update_tree_feature_weights",
"(",
"X",
",",
"feature_names",
",",
"clf",
",",
"feature_weights",
")",
":",
"tree_value",
"=",
"clf",
".",
"tree_",
".",
"value",
"if",
"tree_value",
".",
"shape",
"[",
"1",
"]",
"==",
"1",
":",
"squeeze_axis",
"=",... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _multiply | Multiple X by coef element-wise, preserving sparsity. | eli5/sklearn/explain_prediction.py | 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) | 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) | [
"Multiple",
"X",
"by",
"coef",
"element",
"-",
"wise",
"preserving",
"sparsity",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_prediction.py#L610-L615 | [
"def",
"_multiply",
"(",
"X",
",",
"coef",
")",
":",
"if",
"sp",
".",
"issparse",
"(",
"X",
")",
":",
"return",
"X",
".",
"multiply",
"(",
"sp",
".",
"csr_matrix",
"(",
"coef",
")",
")",
"else",
":",
"return",
"np",
".",
"multiply",
"(",
"X",
"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _linear_weights | Return top weights getter for label_id. | eli5/sklearn/explain_prediction.py | 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,
... | 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,
... | [
"Return",
"top",
"weights",
"getter",
"for",
"label_id",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_prediction.py#L618-L626 | [
"def",
"_linear_weights",
"(",
"clf",
",",
"x",
",",
"top",
",",
"flt_feature_names",
",",
"flt_indices",
")",
":",
"def",
"_weights",
"(",
"label_id",
",",
"scale",
"=",
"1.0",
")",
":",
"coef",
"=",
"get_coef",
"(",
"clf",
",",
"label_id",
")",
"scor... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | attrs | 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... | eli5/base_utils.py | 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... | 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... | [
"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",
... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/base_utils.py#L11-L36 | [
"def",
"attrs",
"(",
"class_",
")",
":",
"attrs_kwargs",
"=",
"{",
"}",
"for",
"method",
",",
"kw_name",
"in",
"[",
"(",
"'__repr__'",
",",
"'repr'",
")",
",",
"(",
"'__eq__'",
",",
"'cmp'",
")",
",",
"(",
"'__hash__'",
",",
"'hash'",
")",
",",
"]"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | is_probabilistic_classifier | Return True if a classifier can return probabilities | eli5/sklearn/utils.py | 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
# ... | 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",
"True",
"if",
"a",
"classifier",
"can",
"return",
"probabilities"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/utils.py#L31-L40 | [
"def",
"is_probabilistic_classifier",
"(",
"clf",
")",
":",
"# type: (Any) -> bool",
"if",
"not",
"hasattr",
"(",
"clf",
",",
"'predict_proba'",
")",
":",
"return",
"False",
"if",
"isinstance",
"(",
"clf",
",",
"OneVsRestClassifier",
")",
":",
"# It currently has ... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | predict_proba | Return result of predict_proba, if an estimator supports it, or None. | eli5/sklearn/utils.py | 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... | 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",
"result",
"of",
"predict_proba",
"if",
"an",
"estimator",
"supports",
"it",
"or",
"None",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/utils.py#L43-L54 | [
"def",
"predict_proba",
"(",
"estimator",
",",
"X",
")",
":",
"# type: (Any, Any) -> Optional[np.ndarray]",
"if",
"is_probabilistic_classifier",
"(",
"estimator",
")",
":",
"try",
":",
"proba",
",",
"=",
"estimator",
".",
"predict_proba",
"(",
"X",
")",
"return",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | has_intercept | Return True if an estimator has intercept fit. | eli5/sklearn/utils.py | 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... | 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",
"True",
"if",
"an",
"estimator",
"has",
"intercept",
"fit",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/utils.py#L57-L67 | [
"def",
"has_intercept",
"(",
"estimator",
")",
":",
"# type: (Any) -> bool",
"if",
"hasattr",
"(",
"estimator",
",",
"'fit_intercept'",
")",
":",
"return",
"estimator",
".",
"fit_intercept",
"if",
"hasattr",
"(",
"estimator",
",",
"'intercept_'",
")",
":",
"if",... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | get_feature_names | 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. | eli5/sklearn/utils.py | 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... | 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",
"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",
"... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/utils.py#L70-L112 | [
"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, ... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | get_default_target_names | Return a vector of target names: "y" if there is only one target,
and "y0", "y1", ... if there are multiple targets. | eli5/sklearn/utils.py | 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:
... | 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",
"target",
"names",
":",
"y",
"if",
"there",
"is",
"only",
"one",
"target",
"and",
"y0",
"y1",
"...",
"if",
"there",
"are",
"multiple",
"targets",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/utils.py#L131-L145 | [
"def",
"get_default_target_names",
"(",
"estimator",
",",
"num_targets",
"=",
"None",
")",
":",
"if",
"num_targets",
"is",
"None",
":",
"if",
"len",
"(",
"estimator",
".",
"coef_",
".",
"shape",
")",
"<=",
"1",
":",
"num_targets",
"=",
"1",
"else",
":",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | get_coef | 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. | eli5/sklearn/utils.py | 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 ... | 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",
"a",
"vector",
"of",
"coefficients",
"for",
"a",
"given",
"label",
"including",
"bias",
"feature",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/utils.py#L148-L187 | [
"def",
"get_coef",
"(",
"clf",
",",
"label_id",
",",
"scale",
"=",
"None",
")",
":",
"if",
"len",
"(",
"clf",
".",
"coef_",
".",
"shape",
")",
"==",
"2",
":",
"# Most classifiers (even in binary case) and regressors",
"coef",
"=",
"_dense_1d",
"(",
"clf",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | get_num_features | Return size of a feature vector estimator expects as an input. | eli5/sklearn/utils.py | 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_'): ... | 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",
"size",
"of",
"a",
"feature",
"vector",
"estimator",
"expects",
"as",
"an",
"input",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/utils.py#L196-L213 | [
"def",
"get_num_features",
"(",
"estimator",
")",
":",
"if",
"hasattr",
"(",
"estimator",
",",
"'coef_'",
")",
":",
"# linear models",
"if",
"len",
"(",
"estimator",
".",
"coef_",
".",
"shape",
")",
"==",
"0",
":",
"return",
"1",
"return",
"estimator",
"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | get_X0 | Return zero-th element of a one-element data container. | eli5/sklearn/utils.py | 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 | 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 | [
"Return",
"zero",
"-",
"th",
"element",
"of",
"a",
"one",
"-",
"element",
"data",
"container",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/utils.py#L239-L247 | [
"def",
"get_X0",
"(",
"X",
")",
":",
"if",
"pandas_available",
"and",
"isinstance",
"(",
"X",
",",
"pd",
".",
"DataFrame",
")",
":",
"assert",
"len",
"(",
"X",
")",
"==",
"1",
"x",
"=",
"np",
".",
"array",
"(",
"X",
".",
"iloc",
"[",
"0",
"]",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | add_intercept | Add intercept column to X | eli5/sklearn/utils.py | 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]) | 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]) | [
"Add",
"intercept",
"column",
"to",
"X"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/utils.py#L266-L272 | [
"def",
"add_intercept",
"(",
"X",
")",
":",
"intercept",
"=",
"np",
".",
"ones",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"1",
")",
")",
"if",
"sp",
".",
"issparse",
"(",
"X",
")",
":",
"return",
"sp",
".",
"hstack",
"(",
"[",
"X",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_weights_sklearn_crfsuite | Explain sklearn_crfsuite.CRF weights.
See :func:`eli5.explain_weights` for description of
``top``, ``target_names``, ``targets``,
``feature_re`` and ``feature_filter`` parameters. | eli5/sklearn_crfsuite/explain_weights.py | def explain_weights_sklearn_crfsuite(crf,
top=20,
target_names=None,
targets=None,
feature_re=None,
feature_filter=None):
""" Expla... | def explain_weights_sklearn_crfsuite(crf,
top=20,
target_names=None,
targets=None,
feature_re=None,
feature_filter=None):
""" Expla... | [
"Explain",
"sklearn_crfsuite",
".",
"CRF",
"weights",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn_crfsuite/explain_weights.py#L16-L65 | [
"def",
"explain_weights_sklearn_crfsuite",
"(",
"crf",
",",
"top",
"=",
"20",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_re",
"=",
"None",
",",
"feature_filter",
"=",
"None",
")",
":",
"feature_names",
"=",
"np",
".",
"arr... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | filter_transition_coefs | >>> 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... | eli5/sklearn_crfsuite/explain_weights.py | 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... | 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... | [
">>>",
"coef",
"=",
"np",
".",
"array",
"(",
"[[",
"0",
"1",
"2",
"]",
"[",
"3",
"4",
"5",
"]",
"[",
"6",
"7",
"8",
"]]",
")",
">>>",
"filter_transition_coefs",
"(",
"coef",
"[",
"0",
"]",
")",
"array",
"(",
"[[",
"0",
"]]",
")",
">>>",
"fi... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn_crfsuite/explain_weights.py#L94-L112 | [
"def",
"filter_transition_coefs",
"(",
"transition_coef",
",",
"indices",
")",
":",
"indices",
"=",
"np",
".",
"array",
"(",
"indices",
")",
"rows",
"=",
"transition_coef",
"[",
"indices",
"]",
"return",
"rows",
"[",
":",
",",
"indices",
"]"
] | 371b402a0676295c05e582a2dd591f7af476b86b |
train | sorted_for_ner | 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'] | eli5/sklearn_crfsuite/explain_weights.py | 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 ... | 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 ... | [
"Return",
"labels",
"sorted",
"in",
"a",
"default",
"order",
"suitable",
"for",
"NER",
"tasks",
":"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn_crfsuite/explain_weights.py#L115-L127 | [
"def",
"sorted_for_ner",
"(",
"crf_classes",
")",
":",
"def",
"key",
"(",
"cls",
")",
":",
"if",
"len",
"(",
"cls",
")",
">",
"2",
"and",
"cls",
"[",
"1",
"]",
"==",
"'-'",
":",
"# group names like B-ORG and I-ORG together",
"return",
"cls",
".",
"split"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _numpy_to_python | Convert an nested dict/list/tuple that might contain numpy objects
to their python equivalents. Return converted object. | eli5/formatters/as_dict.py | 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)):
... | 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)):
... | [
"Convert",
"an",
"nested",
"dict",
"/",
"list",
"/",
"tuple",
"that",
"might",
"contain",
"numpy",
"objects",
"to",
"their",
"python",
"equivalents",
".",
"Return",
"converted",
"object",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/as_dict.py#L19-L38 | [
"def",
"_numpy_to_python",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"{",
"k",
":",
"_numpy_to_python",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"obj",
".",
"items",
"(",
")",
"}",
"elif",
"isinstance"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | MaskingTextSamplers._sampler_n_samples | Return (sampler, n_samplers) tuples | eli5/lime/samplers.py | 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,
... | 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,
... | [
"Return",
"(",
"sampler",
"n_samplers",
")",
"tuples"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/lime/samplers.py#L183-L192 | [
"def",
"_sampler_n_samples",
"(",
"self",
",",
"n_samples",
")",
":",
"sampler_indices",
"=",
"self",
".",
"rng_",
".",
"choice",
"(",
"range",
"(",
"len",
"(",
"self",
".",
"samplers",
")",
")",
",",
"size",
"=",
"n_samples",
",",
"replace",
"=",
"Tru... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | UnivariateKernelDensitySampler.sample_near | Sample near the document by replacing some of its features
with values sampled from distribution found by KDE. | eli5/lime/samplers.py | 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 ... | 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 ... | [
"Sample",
"near",
"the",
"document",
"by",
"replacing",
"some",
"of",
"its",
"features",
"with",
"values",
"sampled",
"from",
"distribution",
"found",
"by",
"KDE",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/lime/samplers.py#L295-L312 | [
"def",
"sample_near",
"(",
"self",
",",
"doc",
",",
"n_samples",
"=",
"1",
")",
":",
"doc",
"=",
"np",
".",
"asarray",
"(",
"doc",
")",
"num_features",
"=",
"len",
"(",
"self",
".",
"kdes_",
")",
"sizes",
"=",
"self",
".",
"rng_",
".",
"randint",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _all_feature_names | All feature names for a feature: usually just the feature itself,
but can be several features for unhashed features with collisions. | eli5/_feature_names.py | 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... | 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... | [
"All",
"feature",
"names",
"for",
"a",
"feature",
":",
"usually",
"just",
"the",
"feature",
"itself",
"but",
"can",
"be",
"several",
"features",
"for",
"unhashed",
"features",
"with",
"collisions",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/_feature_names.py#L182-L192 | [
"def",
"_all_feature_names",
"(",
"name",
")",
":",
"# type: (Union[str, bytes, List[Dict]]) -> List[str]",
"if",
"isinstance",
"(",
"name",
",",
"bytes",
")",
":",
"return",
"[",
"name",
".",
"decode",
"(",
"'utf8'",
")",
"]",
"elif",
"isinstance",
"(",
"name",... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | FeatureNames.filtered | Return feature names filtered by a regular expression
``feature_re``, and indices of filtered elements. | eli5/_feature_names.py | 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_... | 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_... | [
"Return",
"feature",
"names",
"filtered",
"by",
"a",
"regular",
"expression",
"feature_re",
"and",
"indices",
"of",
"filtered",
"elements",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/_feature_names.py#L98-L140 | [
"def",
"filtered",
"(",
"self",
",",
"feature_filter",
",",
"x",
"=",
"None",
")",
":",
"# type: (Callable, Any) -> Tuple[FeatureNames, List[int]]",
"indices",
"=",
"[",
"]",
"filtered_feature_names",
"=",
"[",
"]",
"indexed_names",
"=",
"None",
"# type: Optional[Iter... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | FeatureNames.add_feature | Add a new feature name, return it's index. | eli5/_feature_names.py | 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.... | 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.... | [
"Add",
"a",
"new",
"feature",
"name",
"return",
"it",
"s",
"index",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/_feature_names.py#L161-L179 | [
"def",
"add_feature",
"(",
"self",
",",
"feature",
")",
":",
"# type: (Any) -> int",
"# 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.add_feature to improve performance.... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | format_as_text | 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
... | eli5/formatters/text.py | 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
---------... | 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",
"explanation",
"as",
"text",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/text.py#L21-L99 | [
"def",
"format_as_text",
"(",
"expl",
",",
"# type: Explanation",
"show",
"=",
"fields",
".",
"ALL",
",",
"highlight_spaces",
"=",
"None",
",",
"# type: Optional[bool]",
"show_feature_values",
"=",
"False",
",",
"# type: bool",
")",
":",
"# type: (...) -> str",
"lin... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _format_unhashed_feature | Format feature name for hashed features. | eli5/formatters/text.py | 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) | 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) | [
"Format",
"feature",
"name",
"for",
"hashed",
"features",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/text.py#L270-L277 | [
"def",
"_format_unhashed_feature",
"(",
"name",
",",
"hl_spaces",
",",
"sep",
"=",
"' | '",
")",
":",
"# type: (List, bool, str) -> str",
"return",
"sep",
".",
"join",
"(",
"format_signed",
"(",
"n",
",",
"_format_single_feature",
",",
"hl_spaces",
"=",
"hl_spaces... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _get_top_features | 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;
* ... | eli5/_feature_weights.py | 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... | 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",
"a",
"(",
"pos",
"neg",
")",
"tuple",
".",
"pos",
"and",
"neg",
"are",
"lists",
"of",
"(",
"name",
"value",
")",
"tuples",
"for",
"features",
"with",
"positive",
"and",
"negative",
"coefficients",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/_feature_weights.py#L10-L35 | [
"def",
"_get_top_features",
"(",
"feature_names",
",",
"coef",
",",
"top",
",",
"x",
")",
":",
"if",
"isinstance",
"(",
"top",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"num_pos",
",",
"num_neg",
"=",
"list",
"(",
"top",
")",
"# \"list\" is just f... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | get_char_weights | 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... | eli5/formatters/text_helpers.py | 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... | 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",
"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",
"fragmen... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/text_helpers.py#L11-L32 | [
"def",
"get_char_weights",
"(",
"doc_weighted_spans",
",",
"preserve_density",
"=",
"None",
")",
":",
"# type: (DocWeightedSpans, Optional[bool]) -> np.ndarray",
"if",
"preserve_density",
"is",
"None",
":",
"preserve_density",
"=",
"doc_weighted_spans",
".",
"preserve_density... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | prepare_weighted_spans | 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. | eli5/formatters/text_helpers.py | 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... | 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",
"weighted",
"spans",
"prepared",
"for",
"rendering",
".",
"Calculate",
"a",
"separate",
"weight",
"range",
"for",
"each",
"different",
"weighted",
"span",
"(",
"for",
"each",
"different",
"index",
")",
":",
"each",
"target",
"has",
"the",
"same",
"... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/text_helpers.py#L58-L90 | [
"def",
"prepare_weighted_spans",
"(",
"targets",
",",
"# type: List[TargetExplanation]",
"preserve_density",
"=",
"None",
",",
"# type: Optional[bool]",
")",
":",
"# type: (...) -> List[Optional[List[PreparedWeightedSpans]]]",
"targets_char_weights",
"=",
"[",
"[",
"get_char_weig... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | build_span_analyzer | 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 ... | eli5/sklearn/_span_analyzers.py | 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
... | 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",
"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",
... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/_span_analyzers.py#L7-L28 | [
"def",
"build_span_analyzer",
"(",
"document",
",",
"vec",
")",
":",
"preprocessed_doc",
"=",
"vec",
".",
"build_preprocessor",
"(",
")",
"(",
"vec",
".",
"decode",
"(",
"document",
")",
")",
"analyzer",
"=",
"None",
"if",
"vec",
".",
"analyzer",
"==",
"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_weights_xgboost | 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... | eli5/xgboost.py | def explain_weights_xgboost(xgb,
vec=None,
top=20,
target_names=None, # ignored
targets=None, # ignored
feature_names=None,
feature_re=None, # type: ... | 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",
"an",
"XGBoost",
"estimator",
"(",
"via",
"scikit",
"-",
"learn",
"wrapper",
"XGBClassifier",
"or",
"XGBRegressor",
"or",
"via",
"xgboost",
".",
"Booster",
")",
"as",
"feature",
"importances",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/xgboost.py#L38-L83 | [
"def",
"explain_weights_xgboost",
"(",
"xgb",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"20",
",",
"target_names",
"=",
"None",
",",
"# ignored",
"targets",
"=",
"None",
",",
"# ignored",
"feature_names",
"=",
"None",
",",
"feature_re",
"=",
"None",
",",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_prediction_xgboost | 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... | eli5/xgboost.py | 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... | 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... | [
"Return",
"an",
"explanation",
"of",
"XGBoost",
"prediction",
"(",
"via",
"scikit",
"-",
"learn",
"wrapper",
"XGBClassifier",
"or",
"XGBRegressor",
"or",
"via",
"xgboost",
".",
"Booster",
")",
"as",
"feature",
"weights",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/xgboost.py#L89-L217 | [
"def",
"explain_prediction_xgboost",
"(",
"xgb",
",",
"doc",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"None",
",",
"top_targets",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"featur... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _prediction_feature_weights | 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/ | eli5/xgboost.py | 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/
"""
... | 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/
"""
... | [
"For",
"each",
"target",
"return",
"score",
"and",
"numpy",
"array",
"with",
"feature",
"weights",
"on",
"this",
"prediction",
"following",
"an",
"idea",
"from",
"http",
":",
"//",
"blog",
".",
"datadive",
".",
"net",
"/",
"interpreting",
"-",
"random",
"-... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/xgboost.py#L239-L264 | [
"def",
"_prediction_feature_weights",
"(",
"booster",
",",
"dmatrix",
",",
"n_targets",
",",
"feature_names",
",",
"xgb_feature_names",
")",
":",
"# XGBClassifier does not have pred_leaf argument, so use booster",
"leaf_ids",
",",
"=",
"booster",
".",
"predict",
"(",
"dma... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _indexed_leafs | Return a leaf nodeid -> node dictionary with
"parent" and "leaf" (average child "leaf" value) added to all nodes. | eli5/xgboost.py | 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... | 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... | [
"Return",
"a",
"leaf",
"nodeid",
"-",
">",
"node",
"dictionary",
"with",
"parent",
"and",
"leaf",
"(",
"average",
"child",
"leaf",
"value",
")",
"added",
"to",
"all",
"nodes",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/xgboost.py#L291-L305 | [
"def",
"_indexed_leafs",
"(",
"parent",
")",
":",
"if",
"not",
"parent",
".",
"get",
"(",
"'children'",
")",
":",
"return",
"{",
"parent",
"[",
"'nodeid'",
"]",
":",
"parent",
"}",
"indexed",
"=",
"{",
"}",
"for",
"child",
"in",
"parent",
"[",
"'chil... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _parent_value | Value of the parent node: a weighted sum of child values. | eli5/xgboost.py | 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) | 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) | [
"Value",
"of",
"the",
"parent",
"node",
":",
"a",
"weighted",
"sum",
"of",
"child",
"values",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/xgboost.py#L308-L315 | [
"def",
"_parent_value",
"(",
"children",
")",
":",
"# type: (...) -> int",
"covers",
"=",
"np",
".",
"array",
"(",
"[",
"child",
"[",
"'cover'",
"]",
"for",
"child",
"in",
"children",
"]",
")",
"covers",
"/=",
"np",
".",
"sum",
"(",
"covers",
")",
"lea... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _parse_tree_dump | 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. | eli5/xgboost.py | 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... | 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... | [
"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",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/xgboost.py#L335-L356 | [
"def",
"_parse_tree_dump",
"(",
"text_dump",
")",
":",
"# type: (str) -> Optional[Dict[str, Any]]",
"result",
"=",
"None",
"stack",
"=",
"[",
"]",
"# type: List[Dict]",
"for",
"line",
"in",
"text_dump",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"line",
":",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _missing_values_set_to_nan | 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. | eli5/xgboost.py | 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... | 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",
"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"... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/xgboost.py#L392-L415 | [
"def",
"_missing_values_set_to_nan",
"(",
"values",
",",
"missing_value",
",",
"sparse_missing",
")",
":",
"if",
"sp",
".",
"issparse",
"(",
"values",
")",
":",
"assert",
"values",
".",
"shape",
"[",
"0",
"]",
"==",
"1",
"if",
"sparse_missing",
"and",
"sp"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | argsort_k_smallest | Return no more than ``k`` indices of smallest values. | eli5/utils.py | 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)] | 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)] | [
"Return",
"no",
"more",
"than",
"k",
"indices",
"of",
"smallest",
"values",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/utils.py#L23-L31 | [
"def",
"argsort_k_smallest",
"(",
"x",
",",
"k",
")",
":",
"if",
"k",
"==",
"0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
",",
"dtype",
"=",
"np",
".",
"intp",
")",
"if",
"k",
"is",
"None",
"or",
"k",
">=",
"len",
"(",
"x",
")",
":... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | mask | The same as x[indices], but return an empty array if indices are empty,
instead of returning all x elements,
and handles sparse "vectors". | eli5/utils.py | 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]:
... | 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]:
... | [
"The",
"same",
"as",
"x",
"[",
"indices",
"]",
"but",
"return",
"an",
"empty",
"array",
"if",
"indices",
"are",
"empty",
"instead",
"of",
"returning",
"all",
"x",
"elements",
"and",
"handles",
"sparse",
"vectors",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/utils.py#L34-L47 | [
"def",
"mask",
"(",
"x",
",",
"indices",
")",
":",
"indices_shape",
"=",
"(",
"[",
"len",
"(",
"indices",
")",
"]",
"if",
"isinstance",
"(",
"indices",
",",
"list",
")",
"else",
"indices",
".",
"shape",
")",
"if",
"not",
"indices_shape",
"[",
"0",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | is_sparse_vector | x is a 2D sparse matrix with it's first shape equal to 1. | eli5/utils.py | 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 | 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 | [
"x",
"is",
"a",
"2D",
"sparse",
"matrix",
"with",
"it",
"s",
"first",
"shape",
"equal",
"to",
"1",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/utils.py#L50-L53 | [
"def",
"is_sparse_vector",
"(",
"x",
")",
":",
"return",
"sp",
".",
"issparse",
"(",
"x",
")",
"and",
"len",
"(",
"x",
".",
"shape",
")",
"==",
"2",
"and",
"x",
".",
"shape",
"[",
"0",
"]",
"==",
"1"
] | 371b402a0676295c05e582a2dd591f7af476b86b |
train | indices_to_bool_mask | 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... | eli5/utils.py | 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... | 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... | [
"Convert",
"indices",
"to",
"a",
"boolean",
"(",
"integer",
")",
"mask",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/utils.py#L56-L72 | [
"def",
"indices_to_bool_mask",
"(",
"indices",
",",
"size",
")",
":",
"mask",
"=",
"np",
".",
"zeros",
"(",
"size",
",",
"dtype",
"=",
"bool",
")",
"mask",
"[",
"indices",
"]",
"=",
"1",
"return",
"mask"
] | 371b402a0676295c05e582a2dd591f7af476b86b |
train | get_target_display_names | Return a list of (target_id, display_name) tuples.
By default original names are passed as-is, only indices are added:
>>> get_target_display_names(['x', 'y'])
[(0, 'x'), (1, 'y')]
``targets`` can be written using both names from ``target_names` and
from ``original_names``:
>>> get_target_disp... | eli5/utils.py | 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... | 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",
"a",
"list",
"of",
"(",
"target_id",
"display_name",
")",
"tuples",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/utils.py#L84-L177 | [
"def",
"get_target_display_names",
"(",
"original_names",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"top_targets",
"=",
"None",
",",
"score",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"target_names",
",",
"(",
"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | get_binary_target_scale_label_id | Return (target_name, scale, label_id) tuple for a binary classifier.
>>> get_binary_target_scale_label_id(+5.0, get_target_display_names([False, True]))
(True, 1, 1)
>>> get_binary_target_scale_label_id(-5.0, get_target_display_names([False, True]))
(False, -1, 0)
>>> get_binary_target_scale_label_... | eli5/utils.py | 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... | 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... | [
"Return",
"(",
"target_name",
"scale",
"label_id",
")",
"tuple",
"for",
"a",
"binary",
"classifier",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/utils.py#L180-L210 | [
"def",
"get_binary_target_scale_label_id",
"(",
"score",
",",
"display_names",
",",
"proba",
"=",
"None",
")",
":",
"if",
"score",
"is",
"not",
"None",
":",
"label_id",
"=",
"1",
"if",
"score",
">=",
"0",
"else",
"0",
"scale",
"=",
"-",
"1",
"if",
"lab... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _get_value_indices | >>> _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'... | eli5/utils.py | 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]
>>> _... | 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]
>>> _... | [
">>>",
"_get_value_indices",
"(",
"[",
"foo",
"bar",
"baz",
"]",
"[",
"foo",
"bar",
"baz",
"]",
"...",
"[",
"bar",
"foo",
"]",
")",
"[",
"1",
"0",
"]",
">>>",
"_get_value_indices",
"(",
"[",
"foo",
"bar",
"baz",
"]",
"[",
"FOO",
"bar",
"baz",
"]"... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/utils.py#L213-L232 | [
"def",
"_get_value_indices",
"(",
"names1",
",",
"names2",
",",
"lookups",
")",
":",
"positions",
"=",
"{",
"name",
":",
"idx",
"for",
"idx",
",",
"name",
"in",
"enumerate",
"(",
"names2",
")",
"}",
"positions",
".",
"update",
"(",
"{",
"name",
":",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | dot2svg | Render Graphviz data to SVG | eli5/_graphviz.py | 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 | 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 | [
"Render",
"Graphviz",
"data",
"to",
"SVG"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/_graphviz.py#L14-L20 | [
"def",
"dot2svg",
"(",
"dot",
")",
":",
"# type: (str) -> str",
"svg",
"=",
"graphviz",
".",
"Source",
"(",
"dot",
")",
".",
"pipe",
"(",
"format",
"=",
"'svg'",
")",
".",
"decode",
"(",
"'utf8'",
")",
"# type: str",
"# strip doctype and xml declaration",
"s... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_weights_sklearn | Return an explanation of an estimator | eli5/sklearn/explain_weights.py | 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... | 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",
"an",
"estimator"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_weights.py#L136-L142 | [
"def",
"explain_weights_sklearn",
"(",
"estimator",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"_TOP",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"coef_scale",
"=",
"None",
",",
"feature_re",
"=",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_linear_classifier_weights | Return an explanation of a linear classifier weights.
See :func:`eli5.explain_weights` for description of
``top``, ``target_names``, ``targets``, ``feature_names``,
``feature_re`` and ``feature_filter`` parameters.
``vec`` is a vectorizer instance used to transform
raw features to the input of the... | eli5/sklearn/explain_weights.py | def explain_linear_classifier_weights(clf,
vec=None,
top=_TOP,
target_names=None,
targets=None,
feature_names=None,
... | def explain_linear_classifier_weights(clf,
vec=None,
top=_TOP,
target_names=None,
targets=None,
feature_names=None,
... | [
"Return",
"an",
"explanation",
"of",
"a",
"linear",
"classifier",
"weights",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_weights.py#L189-L261 | [
"def",
"explain_linear_classifier_weights",
"(",
"clf",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"_TOP",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"coef_scale",
"=",
"None",
",",
"feature_re",
"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_rf_feature_importance | Return an explanation of a tree-based ensemble estimator.
See :func:`eli5.explain_weights` for description of
``top``, ``feature_names``, ``feature_re`` and ``feature_filter``
parameters.
``target_names`` and ``targets`` parameters are ignored.
``vec`` is a vectorizer instance used to transform
... | eli5/sklearn/explain_weights.py | def explain_rf_feature_importance(estimator,
vec=None,
top=_TOP,
target_names=None, # ignored
targets=None, # ignored
feature_names=None,
... | 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",
"tree",
"-",
"based",
"ensemble",
"estimator",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_weights.py#L291-L324 | [
"def",
"explain_rf_feature_importance",
"(",
"estimator",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"_TOP",
",",
"target_names",
"=",
"None",
",",
"# ignored",
"targets",
"=",
"None",
",",
"# ignored",
"feature_names",
"=",
"None",
",",
"feature_re",
"=",
"N... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_decision_tree | Return an explanation of a decision tree.
See :func:`eli5.explain_weights` for description of
``top``, ``target_names``, ``feature_names``,
``feature_re`` and ``feature_filter`` parameters.
``targets`` parameter is ignored.
``vec`` is a vectorizer instance used to transform
raw features to th... | eli5/sklearn/explain_weights.py | def explain_decision_tree(estimator,
vec=None,
top=_TOP,
target_names=None,
targets=None, # ignored
feature_names=None,
feature_re=None,
... | 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",
"decision",
"tree",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_weights.py#L329-L377 | [
"def",
"explain_decision_tree",
"(",
"estimator",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"_TOP",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"# ignored",
"feature_names",
"=",
"None",
",",
"feature_re",
"=",
"None",
",",
"feature... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_linear_regressor_weights | Return an explanation of a linear regressor weights.
See :func:`eli5.explain_weights` for description of
``top``, ``target_names``, ``targets``, ``feature_names``,
``feature_re`` and ``feature_filter`` parameters.
``vec`` is a vectorizer instance used to transform
raw features to the input of the ... | eli5/sklearn/explain_weights.py | def explain_linear_regressor_weights(reg,
vec=None,
top=_TOP,
target_names=None,
targets=None,
feature_names=None,
... | def explain_linear_regressor_weights(reg,
vec=None,
top=_TOP,
target_names=None,
targets=None,
feature_names=None,
... | [
"Return",
"an",
"explanation",
"of",
"a",
"linear",
"regressor",
"weights",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_weights.py#L396-L467 | [
"def",
"explain_linear_regressor_weights",
"(",
"reg",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"_TOP",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"coef_scale",
"=",
"None",
",",
"feature_re",
"=... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_permutation_importance | Return an explanation of PermutationImportance.
See :func:`eli5.explain_weights` for description of
``top``, ``feature_names``, ``feature_re`` and ``feature_filter``
parameters.
``target_names`` and ``targets`` parameters are ignored.
``vec`` is a vectorizer instance used to transform
raw fea... | eli5/sklearn/explain_weights.py | def explain_permutation_importance(estimator,
vec=None,
top=_TOP,
target_names=None, # ignored
targets=None, # ignored
feature_names=None,
... | def explain_permutation_importance(estimator,
vec=None,
top=_TOP,
target_names=None, # ignored
targets=None, # ignored
feature_names=None,
... | [
"Return",
"an",
"explanation",
"of",
"PermutationImportance",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/explain_weights.py#L485-L517 | [
"def",
"explain_permutation_importance",
"(",
"estimator",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"_TOP",
",",
"target_names",
"=",
"None",
",",
"# ignored",
"targets",
"=",
"None",
",",
"# ignored",
"feature_names",
"=",
"None",
",",
"feature_re",
"=",
"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _get_collisions | Return a dict ``{column_id: [possible term ids]}``
with collision information. | eli5/sklearn/unhashing.py | 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... | 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... | [
"Return",
"a",
"dict",
"{",
"column_id",
":",
"[",
"possible",
"term",
"ids",
"]",
"}",
"with",
"collision",
"information",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/unhashing.py#L210-L219 | [
"def",
"_get_collisions",
"(",
"indices",
")",
":",
"# type: (...) -> Dict[int, List[int]]",
"collisions",
"=",
"defaultdict",
"(",
"list",
")",
"# type: Dict[int, List[int]]",
"for",
"term_id",
",",
"hash_id",
"in",
"enumerate",
"(",
"indices",
")",
":",
"collisions"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _get_indices_and_signs | For each term from ``terms`` return its column index and sign,
as assigned by FeatureHasher ``hasher``. | eli5/sklearn/unhashing.py | 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 | 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 | [
"For",
"each",
"term",
"from",
"terms",
"return",
"its",
"column",
"index",
"and",
"sign",
"as",
"assigned",
"by",
"FeatureHasher",
"hasher",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/unhashing.py#L222-L230 | [
"def",
"_get_indices_and_signs",
"(",
"hasher",
",",
"terms",
")",
":",
"X",
"=",
"_transform_terms",
"(",
"hasher",
",",
"terms",
")",
"indices",
"=",
"X",
".",
"nonzero",
"(",
")",
"[",
"1",
"]",
"signs",
"=",
"X",
".",
"sum",
"(",
"axis",
"=",
"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | handle_hashing_vec | Return feature_names and coef_scale (if with_coef_scale is True),
calling .get_feature_names for invhashing vectorizers. | eli5/sklearn/unhashing.py | 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... | 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... | [
"Return",
"feature_names",
"and",
"coef_scale",
"(",
"if",
"with_coef_scale",
"is",
"True",
")",
"calling",
".",
"get_feature_names",
"for",
"invhashing",
"vectorizers",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/unhashing.py#L248-L266 | [
"def",
"handle_hashing_vec",
"(",
"vec",
",",
"feature_names",
",",
"coef_scale",
",",
"with_coef_scale",
"=",
"True",
")",
":",
"needs_coef_scale",
"=",
"with_coef_scale",
"and",
"coef_scale",
"is",
"None",
"if",
"is_invhashing",
"(",
"vec",
")",
":",
"if",
"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | invert_hashing_and_fit | 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. | eli5/sklearn/unhashing.py | 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 ... | 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 ... | [
"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",
"th... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/unhashing.py#L305-L323 | [
"def",
"invert_hashing_and_fit",
"(",
"vec",
",",
"# type: Union[FeatureUnion, HashingVectorizer]",
"docs",
")",
":",
"# type: (...) -> Union[FeatureUnion, InvertableHashingVectorizer]",
"if",
"isinstance",
"(",
"vec",
",",
"HashingVectorizer",
")",
":",
"vec",
"=",
"Invertab... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _fit_invhashing_union | Fit InvertableHashingVectorizer on doc inside a FeatureUnion. | eli5/sklearn/unhashing.py | 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... | 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... | [
"Fit",
"InvertableHashingVectorizer",
"on",
"doc",
"inside",
"a",
"FeatureUnion",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/unhashing.py#L326-L334 | [
"def",
"_fit_invhashing_union",
"(",
"vec_union",
",",
"docs",
")",
":",
"# type: (FeatureUnion, Any) -> FeatureUnion",
"return",
"FeatureUnion",
"(",
"[",
"(",
"name",
",",
"invert_hashing_and_fit",
"(",
"v",
",",
"docs",
")",
")",
"for",
"name",
",",
"v",
"in"... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | InvertableHashingVectorizer.fit | Extract possible terms from documents | eli5/sklearn/unhashing.py | def fit(self, X, y=None):
""" Extract possible terms from documents """
self.unhasher.fit(self._get_terms_iter(X))
return self | def fit(self, X, y=None):
""" Extract possible terms from documents """
self.unhasher.fit(self._get_terms_iter(X))
return self | [
"Extract",
"possible",
"terms",
"from",
"documents"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/unhashing.py#L55-L58 | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"self",
".",
"unhasher",
".",
"fit",
"(",
"self",
".",
"_get_terms_iter",
"(",
"X",
")",
")",
"return",
"self"
] | 371b402a0676295c05e582a2dd591f7af476b86b |
train | InvertableHashingVectorizer.get_feature_names | Return feature names.
This is a best-effort function which tries to reconstruct feature
names based on what it has seen so far.
HashingVectorizer uses a signed hash function. If always_signed is True,
each term in feature names is prepended with its sign. If it is False,
signs a... | eli5/sklearn/unhashing.py | 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... | 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",
"feature",
"names",
".",
"This",
"is",
"a",
"best",
"-",
"effort",
"function",
"which",
"tries",
"to",
"reconstruct",
"feature",
"names",
"based",
"on",
"what",
"it",
"has",
"seen",
"so",
"far",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/unhashing.py#L67-L85 | [
"def",
"get_feature_names",
"(",
"self",
",",
"always_signed",
"=",
"True",
")",
":",
"# type: (bool) -> FeatureNames",
"return",
"self",
".",
"unhasher",
".",
"get_feature_names",
"(",
"always_signed",
"=",
"always_signed",
",",
"always_positive",
"=",
"self",
".",... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | InvertableHashingVectorizer.column_signs_ | Return a numpy array with expected signs of features.
Values are
* +1 when all known terms which map to the column have positive sign;
* -1 when all known terms which map to the column have negative sign;
* ``nan`` when there are both positive and negative known terms
for this... | eli5/sklearn/unhashing.py | 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... | 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... | [
"Return",
"a",
"numpy",
"array",
"with",
"expected",
"signs",
"of",
"features",
".",
"Values",
"are"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/unhashing.py#L92-L106 | [
"def",
"column_signs_",
"(",
"self",
")",
":",
"if",
"self",
".",
"_always_positive",
"(",
")",
":",
"return",
"np",
".",
"ones",
"(",
"self",
".",
"n_features",
")",
"self",
".",
"unhasher",
".",
"recalculate_attributes",
"(",
")",
"return",
"self",
"."... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | FeatureUnhasher.recalculate_attributes | Update all computed attributes. It is only needed if you need to access
computed attributes after :meth:`patrial_fit` was called. | eli5/sklearn/unhashing.py | 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
... | 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
... | [
"Update",
"all",
"computed",
"attributes",
".",
"It",
"is",
"only",
"needed",
"if",
"you",
"need",
"to",
"access",
"computed",
"attributes",
"after",
":",
"meth",
":",
"patrial_fit",
"was",
"called",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/sklearn/unhashing.py#L166-L188 | [
"def",
"recalculate_attributes",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"# type: (bool) -> None",
"if",
"not",
"self",
".",
"_attributes_dirty",
"and",
"not",
"force",
":",
"return",
"terms",
"=",
"[",
"term",
"for",
"term",
",",
"_",
"in",
"se... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | tree2text | Return text representation of a decision tree. | eli5/formatters/trees.py | 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... | 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... | [
"Return",
"text",
"representation",
"of",
"a",
"decision",
"tree",
"."
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/trees.py#L7-L49 | [
"def",
"tree2text",
"(",
"tree_obj",
",",
"indent",
"=",
"4",
")",
":",
"# type: (TreeInfo, int) -> str",
"parts",
"=",
"[",
"]",
"def",
"_format_node",
"(",
"node",
",",
"depth",
"=",
"0",
")",
":",
"# type: (NodeInfo, int) -> None",
"def",
"p",
"(",
"*",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | _format_array | >>> _format_array([0, 1.0], "{:0.3f}")
'[0.000, 1.000]' | eli5/formatters/trees.py | 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) | 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) | [
">>>",
"_format_array",
"(",
"[",
"0",
"1",
".",
"0",
"]",
"{",
":",
"0",
".",
"3f",
"}",
")",
"[",
"0",
".",
"000",
"1",
".",
"000",
"]"
] | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/trees.py#L68-L75 | [
"def",
"_format_array",
"(",
"x",
",",
"fmt",
")",
":",
"# type: (Any, str) -> str",
"value_repr",
"=",
"\", \"",
".",
"join",
"(",
"fmt",
".",
"format",
"(",
"v",
")",
"for",
"v",
"in",
"x",
")",
"return",
"\"[{}]\"",
".",
"format",
"(",
"value_repr",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_weights_df | 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. | eli5/formatters/as_dataframe.py | 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... | 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",
"pandas",
".",
"DataFrame",
".",
"All",
"keyword",
"arguments",
"are",
"passed",
"to",
":",
"func",
":",
"eli5",
".",
"explain_weights",
".",
"Weights",
"of",
"all",
"features",
"are",
"exported",
"by",
... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/as_dataframe.py#L15-L23 | [
"def",
"explain_weights_df",
"(",
"estimator",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (...) -> pd.DataFrame",
"kwargs",
"=",
"_set_defaults",
"(",
"kwargs",
")",
"return",
"format_as_dataframe",
"(",
"eli5",
".",
"explain_weights",
"(",
"estimator",
",",
"*",... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_weights_dfs | 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. | eli5/formatters/as_dataframe.py | 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`.
... | 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",
"weights",
"and",
"export",
"them",
"to",
"a",
"dict",
"with",
"pandas",
".",
"DataFrame",
"values",
"(",
"as",
":",
"func",
":",
"eli5",
".",
"formatters",
".",
"as_dataframe",
".",
"format_as_dataframes",
"does",
")",
".",
"All",
"keyword",
"a... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/as_dataframe.py#L26-L35 | [
"def",
"explain_weights_dfs",
"(",
"estimator",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (...) -> Dict[str, pd.DataFrame]",
"kwargs",
"=",
"_set_defaults",
"(",
"kwargs",
")",
"return",
"format_as_dataframes",
"(",
"eli5",
".",
"explain_weights",
"(",
"estimator",
... | 371b402a0676295c05e582a2dd591f7af476b86b |
train | explain_prediction_df | 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. | eli5/formatters/as_dataframe.py | 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... | def explain_prediction_df(estimator, doc, **kwargs):
# type: (...) -> pd.DataFrame
""" Explain prediction and export explanation to ``pandas.DataFrame``
All keyword arguments are passed to :func:`eli5.explain_prediction`.
Weights of all features are exported by default.
"""
kwargs = _set_default... | [
"Explain",
"prediction",
"and",
"export",
"explanation",
"to",
"pandas",
".",
"DataFrame",
"All",
"keyword",
"arguments",
"are",
"passed",
"to",
":",
"func",
":",
"eli5",
".",
"explain_prediction",
".",
"Weights",
"of",
"all",
"features",
"are",
"exported",
"b... | TeamHG-Memex/eli5 | python | https://github.com/TeamHG-Memex/eli5/blob/371b402a0676295c05e582a2dd591f7af476b86b/eli5/formatters/as_dataframe.py#L38-L46 | [
"def",
"explain_prediction_df",
"(",
"estimator",
",",
"doc",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (...) -> pd.DataFrame",
"kwargs",
"=",
"_set_defaults",
"(",
"kwargs",
")",
"return",
"format_as_dataframe",
"(",
"eli5",
".",
"explain_prediction",
"(",
"est... | 371b402a0676295c05e582a2dd591f7af476b86b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.