INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Quite often an API is defined both in Implicit and Explicit API definitions. In such cases Implicit API definition wins because that conveys clear intent that the API is backed by a function. This method will merge two such list of Apis with the right order of precedence. If a Path + Method combination is defined in bo... | def _merge_apis(collector):
"""
Quite often, an API is defined both in Implicit and Explicit API definitions. In such cases, Implicit API
definition wins because that conveys clear intent that the API is backed by a function. This method will
merge two such list of Apis with the right or... |
Normalize the APIs to use standard method name | def _normalize_apis(apis):
"""
Normalize the APIs to use standard method name
Parameters
----------
apis : list of samcli.commands.local.lib.provider.Api
List of APIs to replace normalize
Returns
-------
list of samcli.commands.local.lib.prov... |
Fetches a list of APIs configured for this SAM Function resource. | def _extract_apis_from_function(logical_id, function_resource, collector):
"""
Fetches a list of APIs configured for this SAM Function resource.
Parameters
----------
logical_id : str
Logical ID of the resource
function_resource : dict
Contents o... |
Given an AWS:: Serverless:: Function Event Dictionary extract out all Api events and store within the collector | def _extract_apis_from_events(function_logical_id, serverless_function_events, collector):
"""
Given an AWS::Serverless::Function Event Dictionary, extract out all 'Api' events and store within the
collector
Parameters
----------
function_logical_id : str
Lo... |
Converts a AWS:: Serverless:: Function s Event Property to an Api configuration usable by the provider. | def _convert_event_api(lambda_logical_id, event_properties):
"""
Converts a AWS::Serverless::Function's Event Property to an Api configuration usable by the provider.
:param str lambda_logical_id: Logical Id of the AWS::Serverless::Function
:param dict event_properties: Dictionary of th... |
Normalizes Http Methods. Api Gateway allows a Http Methods of ANY. This is a special verb to denote all supported Http Methods on Api Gateway. | def _normalize_http_methods(http_method):
"""
Normalizes Http Methods. Api Gateway allows a Http Methods of ANY. This is a special verb to denote all
supported Http Methods on Api Gateway.
:param str http_method: Http method
:yield str: Either the input http_method or one of the... |
Stores the given APIs tagged under the given logicalId | def add_apis(self, logical_id, apis):
"""
Stores the given APIs tagged under the given logicalId
Parameters
----------
logical_id : str
LogicalId of the AWS::Serverless::Api resource
apis : list of samcli.commands.local.lib.provider.Api
List of A... |
Stores the binary media type configuration for the API with given logical ID | def add_binary_media_types(self, logical_id, binary_media_types):
"""
Stores the binary media type configuration for the API with given logical ID
Parameters
----------
logical_id : str
LogicalId of the AWS::Serverless::Api resource
binary_media_types : list... |
Returns the list of APIs in this resource along with other extra configuration such as binary media types cors etc. Additional configuration is merged directly into the API data because these properties although defined globally actually apply to each API. | def _get_apis_with_config(self, logical_id):
"""
Returns the list of APIs in this resource along with other extra configuration such as binary media types,
cors etc. Additional configuration is merged directly into the API data because these properties, although
defined globally, actuall... |
Returns the properties of resource with given logical ID. If a resource is not found then it returns an empty data. | def _get_properties(self, logical_id):
"""
Returns the properties of resource with given logical ID. If a resource is not found, then it returns an
empty data.
Parameters
----------
logical_id : str
Logical ID of the resource
Returns
-------
... |
Helper method to unzip a file to a temporary directory | def _unzip_file(filepath):
"""
Helper method to unzip a file to a temporary directory
:param string filepath: Absolute path to this file
:return string: Path to the temporary directory where it was unzipped
"""
temp_dir = tempfile.mkdtemp()
if os.name == 'posix':
os.chmod(temp_dir... |
Invoke the given Lambda function locally. | def invoke(self,
function_config,
event,
debug_context=None,
stdout=None,
stderr=None):
"""
Invoke the given Lambda function locally.
##### NOTE: THIS IS A LONG BLOCKING CALL #####
This method will block until ei... |
When a Lambda function is executing we setup certain interrupt handlers to stop the execution. Usually we setup a function timeout interrupt to kill the container after timeout expires. If debugging though we don t enforce a timeout. But we setup a SIGINT interrupt to catch Ctrl + C and terminate the container. | def _configure_interrupt(self, function_name, timeout, container, is_debugging):
"""
When a Lambda function is executing, we setup certain interrupt handlers to stop the execution.
Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though,
... |
Method to get a path to a directory where the Lambda function code is available. This directory will be mounted directly inside the Docker container. | def _get_code_dir(self, code_path):
"""
Method to get a path to a directory where the Lambda function code is available. This directory will
be mounted directly inside the Docker container.
This method handles a few different cases for ``code_path``:
- ``code_path``is a exis... |
Build the image if one is not already on the system that matches the runtime and layers | def build(self, runtime, layers):
"""
Build the image if one is not already on the system that matches the runtime and layers
Parameters
----------
runtime str
Name of the Lambda runtime
layers list(samcli.commands.local.lib.provider.Layer)
List o... |
Generate the Docker TAG that will be used to create the image | def _generate_docker_image_version(layers, runtime):
"""
Generate the Docker TAG that will be used to create the image
Parameters
----------
layers list(samcli.commands.local.lib.provider.Layer)
List of the layers
runtime str
Runtime of the image... |
Builds the image | def _build_image(self, base_image, docker_tag, layers):
"""
Builds the image
Parameters
----------
base_image str
Base Image to use for the new image
docker_tag
Docker tag (REPOSITORY:TAG) to use when building the image
layers list(samcli.... |
Generate the Dockerfile contents | def _generate_dockerfile(base_image, layers):
"""
Generate the Dockerfile contents
A generated Dockerfile will look like the following:
```
FROM lambci/lambda:python3.6
ADD --chown=sbx_user1051:495 layer1 /opt
ADD --chown=sbx_user1051:495 layer2 /opt
```... |
Creates and starts the local API Gateway service. This method will block until the service is stopped manually using an interrupt. After the service is started callers can make HTTP requests to the endpoint to invoke the Lambda function and receive a response. | def start(self):
"""
Creates and starts the local API Gateway service. This method will block until the service is stopped
manually using an interrupt. After the service is started, callers can make HTTP requests to the endpoint
to invoke the Lambda function and receive a response.
... |
Returns a list of routes to configure the Local API Service based on the APIs configured in the template. | def _make_routing_list(api_provider):
"""
Returns a list of routes to configure the Local API Service based on the APIs configured in the template.
Parameters
----------
api_provider : samcli.commands.local.lib.sam_api_provider.SamApiProvider
Returns
-------
... |
Helper method to print the APIs that will be mounted. This method is purely for printing purposes. This method takes in a list of Route Configurations and prints out the Routes grouped by path. Grouping routes by Function Name + Path is the bulk of the logic. | def _print_routes(api_provider, host, port):
"""
Helper method to print the APIs that will be mounted. This method is purely for printing purposes.
This method takes in a list of Route Configurations and prints out the Routes grouped by path.
Grouping routes by Function Name + Path is th... |
This method returns the path to the directory where static files are to be served from. If static_dir is a relative path then it is resolved to be relative to the current working directory. If no static directory is provided or if the resolved directory does not exist this method will return None | def _make_static_dir_path(cwd, static_dir):
"""
This method returns the path to the directory where static files are to be served from. If static_dir is a
relative path, then it is resolved to be relative to the current working directory. If no static directory is
provided, or if the res... |
Creates a Flask Application that can be started. | def create(self):
"""
Creates a Flask Application that can be started.
"""
self._app = Flask(__name__)
path = '/2015-03-31/functions/<function_name>/invocations'
self._app.add_url_rule(path,
endpoint=path,
vie... |
Validates the incoming request | def validate_request():
"""
Validates the incoming request
The following are invalid
1. The Request data is not json serializable
2. Query Parameters are sent to the endpoint
3. The Request Content-Type is not application/json
4. 'X-Amz-Log-Type' ... |
Updates the Flask app with Error Handlers for different Error Codes | def _construct_error_handling(self):
"""
Updates the Flask app with Error Handlers for different Error Codes
"""
self._app.register_error_handler(500, LambdaErrorResponses.generic_service_exception)
self._app.register_error_handler(404, LambdaErrorResponses.generic_path_not_foun... |
Request Handler for the Local Lambda Invoke path. This method is responsible for understanding the incoming request and invoking the Local Lambda Function | def _invoke_request_handler(self, function_name):
"""
Request Handler for the Local Lambda Invoke path. This method is responsible for understanding the incoming
request and invoking the Local Lambda Function
Parameters
----------
function_name str
Name of th... |
Unzip the given file into the given directory while preserving file permissions in the process. | def unzip(zip_file_path, output_dir, permission=None):
"""
Unzip the given file into the given directory while preserving file permissions in the process.
Parameters
----------
zip_file_path : str
Path to the zip file
output_dir : str
Path to the directory where the it should b... |
Sets permissions on the extracted file by reading the external_attr property of given file info. | def _set_permissions(zip_file_info, extracted_path):
"""
Sets permissions on the extracted file by reading the ``external_attr`` property of given file info.
Parameters
----------
zip_file_info : zipfile.ZipInfo
Object containing information about a file within a zip archive
extracted_... |
Download the LayerVersion Zip to the Layer Pkg Cache | def unzip_from_uri(uri, layer_zip_path, unzip_output_dir, progressbar_label):
"""
Download the LayerVersion Zip to the Layer Pkg Cache
Parameters
----------
uri str
Uri to download from
layer_zip_path str
Path to where the content from the uri should be downloaded to
unzip_o... |
Creates a Flask Application that can be started. | def create(self):
"""
Creates a Flask Application that can be started.
"""
self._app = Flask(__name__,
static_url_path="", # Mount static files at root '/'
static_folder=self.static_dir # Serve static files from this directory
... |
Generates the key to the _dict_of_routes based on the list of methods and path supplied | def _generate_route_keys(self, methods, path):
"""
Generates the key to the _dict_of_routes based on the list of methods
and path supplied
:param list(str) methods: List of HTTP Methods
:param str path: Path off the base url
:return: str of Path:Method
"""
... |
Updates the Flask app with Error Handlers for different Error Codes | def _construct_error_handling(self):
"""
Updates the Flask app with Error Handlers for different Error Codes
"""
# Both path and method not present
self._app.register_error_handler(404, ServiceErrorResponses.route_not_found)
# Path is present, but method not allowed
... |
We handle all requests to the host: port. The general flow of handling a request is as follows | def _request_handler(self, **kwargs):
"""
We handle all requests to the host:port. The general flow of handling a request is as follows
* Fetch request from the Flask Global state. This is where Flask places the request and is per thread so
multiple requests are still handled correctl... |
Get the route ( Route ) based on the current request | def _get_current_route(self, flask_request):
"""
Get the route (Route) based on the current request
:param request flask_request: Flask Request
:return: Route matching the endpoint and method of the request
"""
endpoint = flask_request.endpoint
method = flask_req... |
Parses the output from the Lambda Container | def _parse_lambda_output(lambda_output, binary_types, flask_request):
"""
Parses the output from the Lambda Container
:param str lambda_output: Output from Lambda Invoke
:return: Tuple(int, dict, str, bool)
"""
json_output = json.loads(lambda_output)
if not isin... |
Whether or not the body should be decoded from Base64 to Binary | def _should_base64_decode_body(binary_types, flask_request, lamba_response_headers, is_base_64_encoded):
"""
Whether or not the body should be decoded from Base64 to Binary
Parameters
----------
binary_types list(basestring)
Corresponds to self.binary_types (aka. wha... |
Helper method that constructs the Event to be passed to Lambda | def _construct_event(flask_request, port, binary_types):
"""
Helper method that constructs the Event to be passed to Lambda
:param request flask_request: Flask Request
:return: String representing the event
"""
identity = ContextIdentity(source_ip=flask_request.remote_a... |
Constructs an APIGW equivalent query string dictionary | def _query_string_params(flask_request):
"""
Constructs an APIGW equivalent query string dictionary
Parameters
----------
flask_request request
Request from Flask
Returns dict (str: str)
-------
Empty dict if no query params where in the ... |
Find the Lambda function with given name and invoke it. Pass the given event to the function and return response through the given streams. | def invoke(self, function_name, event, stdout=None, stderr=None):
"""
Find the Lambda function with given name and invoke it. Pass the given event to the function and return
response through the given streams.
This function will block until either the function completes or times out.
... |
Returns invoke configuration to pass to Lambda Runtime to invoke the given function | def _get_invoke_config(self, function):
"""
Returns invoke configuration to pass to Lambda Runtime to invoke the given function
:param samcli.commands.local.lib.provider.Function function: Lambda function to generate the configuration for
:return samcli.local.lambdafn.config.FunctionCon... |
Returns the environment variables configuration for this function | def _make_env_vars(self, function):
"""Returns the environment variables configuration for this function
Parameters
----------
function : samcli.commands.local.lib.provider.Function
Lambda function to generate the configuration for
Returns
-------
sa... |
Returns AWS credentials obtained from the shell environment or given profile | def get_aws_creds(self):
"""
Returns AWS credentials obtained from the shell environment or given profile
:return dict: A dictionary containing credentials. This dict has the structure
{"region": "", "key": "", "secret": "", "sessiontoken": ""}. If credentials could not be resolved... |
Constructs an dictionary representation of the Identity Object to be used in serializing to JSON | def to_dict(self):
"""
Constructs an dictionary representation of the Identity Object to be used in serializing to JSON
:return: dict representing the object
"""
json_dict = {"apiKey": self.api_key,
"userArn": self.user_arn,
"cognitoAuth... |
Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON | def to_dict(self):
"""
Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON
:return: dict representing the object
"""
identity_dict = {}
if self.identity:
identity_dict = self.identity.to_dict()
json_... |
Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON | def to_dict(self):
"""
Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON
:return: dict representing the object
"""
request_context_dict = {}
if self.request_context:
request_context_dict = self.reque... |
Implementation of the cli method | def do_cli(function_name, stack_name, filter_pattern, tailing, start_time, end_time):
"""
Implementation of the ``cli`` method
"""
LOG.debug("'logs' command is called")
with LogsCommandContext(function_name,
stack_name=stack_name,
filter_patt... |
Checks if Docker daemon is running. This is required for us to invoke the function locally | def is_docker_reachable(self):
"""
Checks if Docker daemon is running. This is required for us to invoke the function locally
Returns
-------
bool
True, if Docker is available, False otherwise
"""
try:
self.docker_client.ping()
... |
Create and run a Docker container based on the given configuration. | def run(self, container, input_data=None, warm=False):
"""
Create and run a Docker container based on the given configuration.
:param samcli.local.docker.container.Container container: Container to create and run
:param input_data: Optional. Input data sent to the container through cont... |
Ask Docker to pull the container image with given name. | def pull_image(self, image_name, stream=None):
"""
Ask Docker to pull the container image with given name.
Parameters
----------
image_name str
Name of the image
stream samcli.lib.utils.stream_writer.StreamWriter
Optional stream writer to output t... |
Is the container image with given name available? | def has_image(self, image_name):
"""
Is the container image with given name available?
:param string image_name: Name of the image
:return bool: True, if image is available. False, otherwise
"""
try:
self.docker_client.images.get(image_name)
retu... |
Publish the application based on command line inputs. | def do_cli(ctx, template, semantic_version):
"""Publish the application based on command line inputs."""
try:
template_data = get_template_data(template)
except ValueError as ex:
click.secho("Publish Failed", fg='red')
raise UserException(str(ex))
# Override SemanticVersion in t... |
Generate detailed success message for published applications. | def _gen_success_message(publish_output):
"""
Generate detailed success message for published applications.
Parameters
----------
publish_output : dict
Output from serverlessrepo publish_application
Returns
-------
str
Detailed success message
"""
application_id... |
Print link for the application in AWS Serverless Application Repository console. | def _print_console_link(region, application_id):
"""
Print link for the application in AWS Serverless Application Repository console.
Parameters
----------
region : str
AWS region name
application_id : str
The Amazon Resource Name (ARN) of the application
"""
if not reg... |
Helper function to create a Lambda Failure Response | def lambda_failure_response(*args):
"""
Helper function to create a Lambda Failure Response
:return: A Flask Response
"""
response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) |
Constructs a Flask Response for when a Lambda function is not found for an endpoint | def lambda_not_found_response(*args):
"""
Constructs a Flask Response for when a Lambda function is not found for an endpoint
:return: a Flask Response
"""
response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION)
return make_response(response_data, ServiceEr... |
Constructs a Flask Response for when a API Route ( path + method ) is not found. This is usually HTTP 404 but with API Gateway this is a HTTP 403 ( https:// forums. aws. amazon. com/ thread. jspa?threadID = 2166840 ) | def route_not_found(*args):
"""
Constructs a Flask Response for when a API Route (path+method) is not found. This is usually
HTTP 404 but with API Gateway this is a HTTP 403 (https://forums.aws.amazon.com/thread.jspa?threadID=2166840)
:return: a Flask Response
"""
respon... |
Creates a progressbar | def progressbar(length, label):
"""
Creates a progressbar
Parameters
----------
length int
Length of the ProgressBar
label str
Label to give to the progressbar
Returns
-------
click.progressbar
Progressbar
"""
return click.progressbar(length=length,... |
r Removes wrapping double quotes and any \ characters. They are usually added to preserve spaces when passing value thru shell. | def _unquote(value):
r"""
Removes wrapping double quotes and any '\ ' characters. They are usually added to preserve spaces when passing
value thru shell.
Examples
--------
>>> _unquote('val\ ue')
value
>>> _unquote("hel\ lo")
hello
Para... |
This starts up the ( threaded ) Local Server. Note: This is a ** blocking call ** | def run(self):
"""
This starts up the (threaded) Local Server.
Note: This is a **blocking call**
Raises
------
RuntimeError
if the service was not created
"""
if not self._app:
raise RuntimeError("The application must be created be... |
Constructs a Flask Response from the body headers and status_code. | def service_response(body, headers, status_code):
"""
Constructs a Flask Response from the body, headers, and status_code.
:param str body: Response body as a string
:param dict headers: headers for the response
:param int status_code: status_code for response
:return: F... |
This method will extract read the given stream and return the response from Lambda function separated out from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function wrote directly to stdout using System. out. println or equivalents. | def get_lambda_output(stdout_stream):
"""
This method will extract read the given stream and return the response from Lambda function separated out
from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function
wrote directly to stdout using Syst... |
Check to see if the output from the container is in the form of an Error/ Exception from the Lambda invoke | def is_lambda_error_response(lambda_response):
"""
Check to see if the output from the container is in the form of an Error/Exception from the Lambda invoke
Parameters
----------
lambda_response str
The response the container returned
Returns
-------... |
Build the entire application | def build(self):
"""
Build the entire application
Returns
-------
dict
Returns the path to where each resource was built as a map of resource's LogicalId to the path string
"""
result = {}
for lambda_function in self._functions_to_build:
... |
Given the path to built artifacts update the template to point appropriate resource CodeUris to the artifacts folder | def update_template(self, template_dict, original_template_path, built_artifacts):
"""
Given the path to built artifacts, update the template to point appropriate resource CodeUris to the artifacts
folder
Parameters
----------
template_dict
original_template_path... |
Given the function information this method will build the Lambda function. Depending on the configuration it will either build the function in process or by spinning up a Docker container. | def _build_function(self, function_name, codeuri, runtime):
"""
Given the function information, this method will build the Lambda function. Depending on the configuration
it will either build the function in process or by spinning up a Docker container.
Parameters
----------
... |
Provides paths to directories within the container that is required by the builder | def _get_container_dirs(source_dir, manifest_dir):
"""
Provides paths to directories within the container that is required by the builder
Parameters
----------
source_dir : str
Path to the function source code
manifest_dir : str
Path to the direc... |
Use this method to convert a list of host paths to a list of equivalent paths within the container where the given host path is mounted. This is necessary when SAM CLI needs to pass path information to the Lambda Builder running within the container. | def _convert_to_container_dirs(host_paths_to_convert, host_to_container_path_mapping):
"""
Use this method to convert a list of host paths to a list of equivalent paths within the container
where the given host path is mounted. This is necessary when SAM CLI needs to pass path information to
... |
This method is unused and a Work In Progress | def __translate(self, parameter_values):
"""
This method is unused and a Work In Progress
"""
template_copy = self.template
sam_parser = Parser()
sam_translator = Translator(managed_policy_map=self.__managed_policy_map(),
sam_parser=s... |
This method is unused and a Work In Progress | def __managed_policy_map(self):
"""
This method is unused and a Work In Progress
"""
try:
iam_client = boto3.client('iam')
return ManagedPolicyLoader(iam_client).load()
except Exception as ex:
if self._offline_fallback:
# If of... |
Validates the template and parameter values and raises exceptions if there s an issue | def _validate(self, sam_template):
""" Validates the template and parameter values and raises exceptions if there's an issue
:param dict sam_template: SAM template
"""
if "Resources" not in sam_template or not isinstance(sam_template["Resources"], dict) \
or not sam_tem... |
gets the subcommands under the service name | def get_command(self, ctx, cmd_name):
"""
gets the subcommands under the service name
Parameters
----------
ctx : Context
the context object passed into the method
cmd_name : str
the service name
Returns
-------
EventTypeSu... |
gets the Click Commands underneath a service name | def get_command(self, ctx, cmd_name):
"""
gets the Click Commands underneath a service name
Parameters
----------
ctx: Context
context object passed in
cmd_name: string
the service name
Returns
-------
cmd: Click.Command
... |
calls for value substitution in the event json and returns the customized json as a string | def cmd_implementation(self, events_lib, top_level_cmd_name, subcmd_name, *args, **kwargs):
"""
calls for value substitution in the event json and returns the
customized json as a string
Parameters
----------
events_lib
top_level_cmd_name: string
the ... |
Generates the lars path for weighted data. | def generate_lars_path(weighted_data, weighted_labels):
"""Generates the lars path for weighted data.
Args:
weighted_data: data that has been weighted by kernel
weighted_label: labels, weighted by kernel
Returns:
(alphas, coefs), both are arrays correspondin... |
Iteratively adds features to the model | def forward_selection(self, data, labels, weights, num_features):
"""Iteratively adds features to the model"""
clf = Ridge(alpha=0, fit_intercept=True, random_state=self.random_state)
used_features = []
for _ in range(min(num_features, data.shape[1])):
max_ = -100000000
... |
Selects features for the model. see explain_instance_with_data to understand the parameters. | def feature_selection(self, data, labels, weights, num_features, method):
"""Selects features for the model. see explain_instance_with_data to
understand the parameters."""
if method == 'none':
return np.array(range(data.shape[1]))
elif method == 'forward_selection':
... |
Takes perturbed data labels and distances returns explanation. | def explain_instance_with_data(self,
neighborhood_data,
neighborhood_labels,
distances,
label,
num_features,
f... |
Helper function to generate random div ids. This is useful for embedding HTML into ipython notebooks. | def id_generator(size=15, random_state=None):
"""Helper function to generate random div ids. This is useful for embedding
HTML into ipython notebooks."""
chars = list(string.ascii_uppercase + string.digits)
return ''.join(random_state.choice(chars, size, replace=True)) |
Returns the list of classification labels for which we have any explanations. | def available_labels(self):
"""
Returns the list of classification labels for which we have any explanations.
"""
try:
assert self.mode == "classification"
except AssertionError:
raise NotImplementedError('Not supported for regression explanations.')
... |
Returns the explanation as a list. | def as_list(self, label=1, **kwargs):
"""Returns the explanation as a list.
Args:
label: desired label. If you ask for a label for which an
explanation wasn't computed, will throw an exception.
Will be ignored for regression explanations.
kwargs: ... |
Returns the explanation as a pyplot figure. | def as_pyplot_figure(self, label=1, **kwargs):
"""Returns the explanation as a pyplot figure.
Will throw an error if you don't have matplotlib installed
Args:
label: desired label. If you ask for a label for which an
explanation wasn't computed, will throw an exce... |
Shows html explanation in ipython notebook. | def show_in_notebook(self,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
"""Shows html explanation in ipython notebook.
See as_html() for parameters.
This will throw an e... |
Saves html explanation to file.. | def save_to_file(self,
file_path,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
"""Saves html explanation to file. .
Params:
file_path: file to save explanations... |
Returns the explanation as an html page. | def as_html(self,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
"""Returns the explanation as an html page.
Args:
labels: desired labels to show explanations for (as barcharts).
If you a... |
Checks for mistakes in parameters | def _check_params(self, parameters):
"""Checks for mistakes in 'parameters'
Args :
parameters: dict, parameters to be checked
Raises :
ValueError: if any parameter is not a valid argument for the target function
or the target function is not defined
... |
Filters target_params and return those in fn s arguments. Args: fn: arbitrary function override: dict values to override target_params Returns: result: dict dictionary containing variables in both target_params and fn s arguments. | def filter_params(self, fn, override=None):
"""Filters `target_params` and return those in `fn`'s arguments.
Args:
fn : arbitrary function
override: dict, values to override target_params
Returns:
result : dict, dictionary containing variables
in b... |
Maps ids to words or word - position strings. | def map_exp_ids(self, exp, positions=False):
"""Maps ids to words or word-position strings.
Args:
exp: list of tuples [(id, weight), (id,weight)]
positions: if True, also return word positions
Returns:
list of tuples (word, weight), or (word_positions, weigh... |
Adds text with highlighted words to visualization. | def visualize_instance_html(self, exp, label, div_name, exp_object_name,
text=True, opacity=True):
"""Adds text with highlighted words to visualization.
Args:
exp: list of tuples [(id, weight), (id,weight)]
label: label id (integer)
... |
Returns a np array with indices to id_ ( int ) occurrences | def string_position(self, id_):
"""Returns a np array with indices to id_ (int) occurrences"""
if self.bow:
return self.string_start[self.positions[id_]]
else:
return self.string_start[[self.positions[id_]]] |
Returns a string after removing the appropriate words. | def inverse_removing(self, words_to_remove):
"""Returns a string after removing the appropriate words.
If self.bow is false, replaces word with UNKWORDZ instead of removing
it.
Args:
words_to_remove: list of ids (ints) to remove
Returns:
original raw st... |
Segment a string around the tokens created by a passed - in tokenizer | def _segment_with_tokens(text, tokens):
"""Segment a string around the tokens created by a passed-in tokenizer"""
list_form = []
text_ptr = 0
for token in tokens:
inter_token_string = []
while not text[text_ptr:].startswith(token):
inter_token_stri... |
Returns indexes to appropriate words. | def __get_idxs(self, words):
"""Returns indexes to appropriate words."""
if self.bow:
return list(itertools.chain.from_iterable(
[self.positions[z] for z in words]))
else:
return self.positions[words] |
Generates explanations for a prediction. | def explain_instance(self,
text_instance,
classifier_fn,
labels=(1,),
top_labels=None,
num_features=10,
num_samples=5000,
distance_metric='cosine... |
Generates a neighborhood around a prediction. | def __data_labels_distances(self,
indexed_string,
classifier_fn,
num_samples,
distance_metric='cosine'):
"""Generates a neighborhood around a prediction.
Generates neighborhoo... |
Maps ids to feature names. | def map_exp_ids(self, exp):
"""Maps ids to feature names.
Args:
exp: list of tuples [(id, weight), (id,weight)]
Returns:
list of tuples (feature_name, weight)
"""
names = self.exp_feature_names
if self.discretized_feature_names is not None:
... |
Shows the current example in a table format. | def visualize_instance_html(self,
exp,
label,
div_name,
exp_object_name,
show_table=True,
show_all=False):
"""Shows the ... |
Method to validate the structure of training data stats | def validate_training_data_stats(training_data_stats):
"""
Method to validate the structure of training data stats
"""
stat_keys = list(training_data_stats.keys())
valid_stat_keys = ["means", "mins", "maxs", "stds", "feature_values", "feature_frequencies"]
missing_key... |
Generates explanations for a prediction. | def explain_instance(self,
data_row,
predict_fn,
labels=(1,),
top_labels=None,
num_features=10,
num_samples=5000,
distance_metric='euclidean',
... |
Generates a neighborhood around a prediction. | def __data_inverse(self,
data_row,
num_samples):
"""Generates a neighborhood around a prediction.
For numerical features, perturb them by sampling from a Normal(0,1) and
doing the inverse operation of mean-centering and scaling, according to
... |
The predict_proba method will expect 3d arrays but we are reshaping them to 2D so that LIME works correctly. This wraps the function you give in explain_instance to first reshape the data to have the shape the the keras - style network expects. | def _make_predict_proba(self, func):
"""
The predict_proba method will expect 3d arrays, but we are reshaping
them to 2D so that LIME works correctly. This wraps the function
you give in explain_instance to first reshape the data to have
the shape the the keras-style network expe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.