text
stringlengths
81
112k
Takes perturbed data, labels and distances, returns explanation. Args: neighborhood_data: perturbed data, 2d array. first element is assumed to be the original data point. neighborhood_labels: corresponding perturbed labels. should have as ...
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.di...
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: ...
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: keyword arguments, passed to domain_mapper ...
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 exception. Will be ignored for regression e...
Shows html explanation in ipython notebook. See as_html() for parameters. This will throw an error if you don't have IPython installed def show_in_notebook(self, labels=None, predict_proba=True, show_predicted_value=True, ...
Saves html explanation to file. . Params: file_path: file to save explanations to See as_html() for additional parameters. def save_to_file(self, file_path, labels=None, predict_proba=True, show_predicted_...
Returns the explanation as an html page. Args: labels: desired labels to show explanations for (as barcharts). If you ask for a label for which an explanation wasn't computed, will throw an exception. If None, will show explanations for all available ...
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 TypeError: if argument parameters is not...
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_param...
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, weight) if examples: ('bad', 1) or ('bad_3-6-12',...
Adds text with highlighted words to visualization. Args: exp: list of tuples [(id, weight), (id,weight)] label: label id (integer) div_name: name of div object to be used for rendering(in js) exp_object_name: name of js explanation object text: i...
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. 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 string with appropriate words removed. def inverse_removi...
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 no...
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. First, we generate neighborhood data by randomly hiding features from the instance (see __data_labels_distance_mapping). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way...
Generates a neighborhood around a prediction. Generates neighborhood data by randomly removing words from the instance, and predicting with the classifier. Uses cosine distance to compute distances between original and perturbed instances. Args: indexed_string: document (Ind...
Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] Returns: list of tuples (feature_name, weight) def map_exp_ids(self, exp): """Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] ...
Shows the current example in a table format. Args: exp: list of tuples [(id, weight), (id,weight)] label: label id (integer) div_name: name of div object to be used for rendering(in js) exp_object_name: name of js explanation object show_table: i...
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", "fe...
Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_b...
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 means and stds in the training data. For categorical features, perturb by sampling according ...
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): """ ...
Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_b...
Init function. Args: label: label to explain positive_only: if True, only take superpixels that contribute to the prediction of the label. Otherwise, use the top num_features superpixels, which can be positive or negative towards the label...
Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_b...
Generates images and predictions in the neighborhood of this image. Args: image: 3d numpy array, the image fudged_image: 3d numpy array, image to replace original image when superpixel is turned off segments: segmentation of the image classifier_f...
Checks if a callable accepts a given keyword argument. Args: fn: callable to inspect arg_name: string, keyword argument name to check Returns: bool, whether `fn` accepts a `arg_name` keyword argument. def has_arg(fn, arg_name): """Checks if a callable accepts a given keyword argum...
Discretizes the data. Args: data: numpy 2d or 1d array Returns: numpy array of same dimension, discretized. def discretize(self, data): """Discretizes the data. Args: data: numpy 2d or 1d array Returns: numpy array of same dimensio...
The config file is stored in a way that allows you to have a cache for each remote. This is needed when specifying external outputs (as they require you to have an external cache location). Imagine a config file like the following: ['remote "dvc-storage"'] ...
Build a DAG and draw it in ASCII. Args: vertexes (list): list of graph vertexes. edges (list): list of graph edges. def draw(vertexes, edges): """Build a DAG and draw it in ASCII. Args: vertexes (list): list of graph vertexes. edges (list): list of graph edges. """ ...
Draws ASCII canvas on the screen. def draw(self): """Draws ASCII canvas on the screen.""" if sys.stdout.isatty(): # pragma: no cover from asciimatics.screen import Screen Screen.wrapper(self._do_draw) else: for line in self.canvas: print(""....
Create a point on ASCII canvas. Args: x (int): x coordinate. Should be >= 0 and < number of columns in the canvas. y (int): y coordinate. Should be >= 0 an < number of lines in the canvas. char (str): character to place in the specified point ...
Create a line on ASCII canvas. Args: x0 (int): x coordinate where the line should start. y0 (int): y coordinate where the line should start. x1 (int): x coordinate where the line should end. y1 (int): y coordinate where the line should end. char (str)...
Print a text on ASCII canvas. Args: x (int): x coordinate where the text should start. y (int): y coordinate where the text should start. text (str): string that should be printed. def text(self, x, y, text): """Print a text on ASCII canvas. Args: ...
Create a box on ASCII canvas. Args: x0 (int): x coordinate of the box corner. y0 (int): y coordinate of the box corner. width (int): box width. height (int): box height. def box(self, x0, y0, width, height): """Create a box on ASCII canvas. Args...
Refreshes progress bar. def refresh(self, line=None): """Refreshes progress bar.""" # Just go away if it is locked. Will update next time if not self._lock.acquire(False): return if line is None: line = self._line if sys.stdout.isatty() and line is not ...
Updates progress bar for a specified target. def update_target(self, name, current, total): """Updates progress bar for a specified target.""" self.refresh(self._bar(name, current, total))
Finishes progress bar for a specified target. def finish_target(self, name): """Finishes progress bar for a specified target.""" # We have to write a msg about finished target with self._lock: pbar = self._bar(name, 100, 100) if sys.stdout.isatty(): self...
Make a progress bar out of info, which looks like: (1/2): [########################################] 100% master.zip def _bar(self, target_name, current, total): """ Make a progress bar out of info, which looks like: (1/2): [########################################] 100% master.zip ...
Extract the content of dvc tree file Args: self(object) - Repo class instance dir_not_exists(bool) - flag for directory existence output(object) - OutputLOCAL class instance Returns: dict - dictionary with keys - paths to file in .dvc/cache values -...
Gerenates diff message string output Args: target(str) - file/directory to check diff of a_ref(str) - first tag (optional) b_ref(str) - second git tag Returns: string: string of output message with diff info def diff(self, a_ref, target=None, b_ref=None): """Gerenates diff...
r"""Derive the evaluation of the given node for the given graph. When you _reproduce a stage_, you want to _evaluate the descendants_ to know if it make sense to _recompute_ it. A post-ordered search will give us an order list of the nodes we want. For example, let's say that we have the following pip...
Uses heuristics to guess whether the given file is text or binary, by reading a single block of bytes from the file. If more than 30% of the chars in the block are non-text, or there are NUL ('\x00') bytes in the block, assume this is a binary file. def istextfile(fname, blocksize=512): """...
csv.reader doesn't support Unicode input, so need to use some tricks to work around this. Source: https://docs.python.org/2/library/csv.html#csv-examples def csv_reader(unicode_csv_data, dialect=None, **kwargs): """csv.reader doesn't support Unicode input, so need to use some tricks to work around thi...
Source: https://github.com/ipython/ipython_genutils def cast_bytes(s, encoding=None): """Source: https://github.com/ipython/ipython_genutils""" if not isinstance(s, bytes): return encode(s, encoding) return s
Source: https://github.com/python/cpython/blob/ 3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226 def _makedirs(name, mode=0o777, exist_ok=False): """Source: https://github.com/python/cpython/blob/ 3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226 """ head, tail = os.p...
Install package. The command can be run only from DVC project root. E.g. Having: DVC package in https://github.com/dmpetrov/tag_classifier $ dvc pkg install https://github.com/dmpetrov/tag_classifier Result: tag_classifier package in dvc_mod/ directory def install(self, addres...
Whether the stage file was created with `dvc import`. def is_import(self): """Whether the stage file was created with `dvc import`.""" return not self.cmd and len(self.deps) == 1 and len(self.outs) == 1
Used mainly for `dvc remove --outs` and :func:`Stage.reproduce`. def remove_outs(self, ignore_remove=False, force=False): """Used mainly for `dvc remove --outs` and :func:`Stage.reproduce`.""" for out in self.outs: if out.persist and not force: out.unprotect() el...
Checks if this stage has been already ran and stored def is_cached(self): """ Checks if this stage has been already ran and stored """ from dvc.remote.local import RemoteLOCAL from dvc.remote.s3 import RemoteS3 old = Stage.load(self.repo, self.path) if old._chan...
Launch a `dvc daemon` command in a detached process. Args: args (list): list of arguments to append to `dvc daemon` command. def daemon(args): """Launch a `dvc daemon` command in a detached process. Args: args (list): list of arguments to append to `dvc daemon` command. """ if os....
We need to take into account two cases: - ['python code.py foo bar']: Used mainly with dvc as a library - ['echo', 'foo bar']: List of arguments received from the CLI The second case would need quoting, as it was passed through: dvc run echo "foo bar" def _parsed_cmd(self): ...
Setup parser for `dvc init`. def add_parser(subparsers, parent_parser): """Setup parser for `dvc init`.""" INIT_HELP = "Initialize DVC in the current directory." INIT_DESCRIPTION = ( "Initialize DVC in the current directory. Expects directory\n" "to be a Git repository unless --no-scm optio...
Format delimited text to have same column width. Args: content (str): The content of a metric. delimiter (str): Value separator Returns: str: Formatted content. Example: >>> content = ( "value_mse,deviation_mse,data_set\n" "0.421601,0.173461,train\...
Tabularize the content according to its type. Args: content (str): The content of a metric. typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv). Returns: str: Content in a raw or tabular format. def _format_output(content, typ): """Tabularize the content according to its...
Gather all the metric outputs. Args: path (str): Path to a metric file or a directory. recursive (bool): If path is a directory, do a recursive search for metrics on the given path. typ (str): The type of metric to search for, could be one of the following (raw|json|...
Read the content of each metric file and format it. Args: metrics (list): List of metric touples branch (str): Branch to look up for metrics. Returns: A dict mapping keys with metrics path name and content. For example: {'metric.csv': ("value_mse deviation_mse data_...
Generate a graph by using the given stages on the given directory The nodes of the graph are the stage's path relative to the root. Edges are created when the output of one stage is used as a dependency in other stage. The direction of the edges goes from the stage to its dependency: ...
Walks down the root directory looking for Dvcfiles, skipping the directories that are related with any SCM (e.g. `.git`), DVC itself (`.dvc`), or directories tracked by DVC (e.g. `dvc add data` would skip `data/`) NOTE: For large repos, this could be an expensive operation...
Add a new line if progress bar hasn't finished def _progress_aware(self): """Add a new line if progress bar hasn't finished""" from dvc.progress import progress if not progress.is_finished: progress._print() progress.clearln()
Open file and return a stream. def open(self, path, binary=False): """Open file and return a stream.""" if binary: return open(path, "rb") return open(path, encoding="utf-8")
Directory tree generator. See `os.walk` for the docs. Differences: - no support for symlinks - it could raise exceptions, there is no onerror argument def walk(self, top, topdown=True, ignore_file_handler=None): """Directory tree generator. See `os.walk` for the docs. Differen...
Read config for list object api, paginate through list objects. def _list_paths(self, bucket, prefix): """ Read config for list object api, paginate through list objects.""" s3 = self.s3 kwargs = {"Bucket": bucket, "Prefix": prefix} if self.list_objects: list_objects_api = "...
Resolve path relative to config file location. Args: path: Path to be resolved. config_file: Path to config file, which `path` is specified relative to. Returns: Path relative to the `config_file` location. If `path` is an absolute path t...
Method for getting two repo trees between two git tag commits returns the dvc hash names of changed file/directory Args: a_ref(str) - git reference b_ref(str) - optional second git reference, default None Returns: dict - dictionary with keys: (a_tree, b_tree...
Checks if data has changed. A file is considered changed if: - It doesn't exist on the working directory (was unlinked) - Checksum is not computed (saving a new file) - The checkusm stored in the State is different from the given one - There's no file in the cach...
Ask the user for confirmation about the specified statement. Args: statement (unicode): statement to ask the user confirmation about. Returns: bool: whether or not specified statement was confirmed. def confirm(statement): """Ask the user for confirmation about the specified statement. ...
Run dvc CLI command. Args: argv: optional list of arguments to parse. sys.argv is used by default. Returns: int: command's return code. def main(argv=None): """Run dvc CLI command. Args: argv: optional list of arguments to parse. sys.argv is used by default. Returns: ...
Checks if link type config option has a valid value. Args: types (list/string): type(s) of links that dvc should try out. def supported_cache_type(types): """Checks if link type config option has a valid value. Args: types (list/string): type(s) of links that dvc should try out. """ ...
Returns global config location. E.g. ~/.config/dvc/config. Returns: str: path to the global config directory. def get_global_config_dir(): """Returns global config location. E.g. ~/.config/dvc/config. Returns: str: path to the global config directory. """ ...
Returns system config location. E.g. /etc/dvc.conf. Returns: str: path to the system config directory. def get_system_config_dir(): """Returns system config location. E.g. /etc/dvc.conf. Returns: str: path to the system config directory. """ from appdir...
Initializes dvc config. Args: dvc_dir (str): path to .dvc directory. Returns: dvc.config.Config: config object. def init(dvc_dir): """Initializes dvc config. Args: dvc_dir (str): path to .dvc directory. Returns: dvc.config.Conf...
Loads config from all the config files. Args: validate (bool): optional flag to tell dvc if it should validate the config or just load it as is. 'True' by default. Raises: dvc.config.ConfigError: thrown if config has invalid format. def load(self, validate=Tru...
Saves config to config files. Args: config (configobj.ConfigObj): optional config object to save. Raises: dvc.config.ConfigError: thrown if failed to write config file. def save(self, config=None): """Saves config to config files. Args: config (con...
Args: name (str): The name of the remote that we want to retrieve Returns: dict: The content beneath the given remote name. Example: >>> config = {'remote "server"': {'url': 'ssh://localhost/'}} >>> get_remote_settings("server") {'url': 'ssh:...
Unsets specified option and/or section in the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): optional option name. def unset(config, section, opt=None): """Unsets specified option and/or section in the config. ...
Sets specified option in the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): option name. value: value to set option to. def set(config, section, opt, value): """Sets specified option in the config. ...
Prints option value from the config. Args: config (configobj.ConfigObj): config to work on. section (str): section name. opt (str): option name. def show(config, section, opt): """Prints option value from the config. Args: config (configobj.Conf...
Renames an output file and modifies the stage associated to reflect the change on the pipeline. If the output has the same name as its stage, it would also rename the corresponding stage file. E.g. Having: (hello, hello.dvc) $ dvc move hello greetings Result: (greeting,...
Creates an empty repo on the given directory -- basically a `.dvc` directory with subdirectories for configuration and cache. It should be tracked by a SCM or use the `--no-scm` flag. If the given directory is not empty, you must use the `--force` flag to override it. Args: root_dir: Path...
Generate a version with information about the git repository def _generate_version(base_version): """Generate a version with information about the git repository""" pkg_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) if not _is_git_repo(pkg_dir) or not _have_git(): return base_ve...
Check whether a git repository has uncommitted changes. def _is_dirty(dir_path): """Check whether a git repository has uncommitted changes.""" try: subprocess.check_call(["git", "diff", "--quiet"], cwd=dir_path) return False except subprocess.CalledProcessError: return True
get the (md5 hexdigest, md5 digest) of a file def file_md5(fname): """ get the (md5 hexdigest, md5 digest) of a file """ from dvc.progress import progress from dvc.istextfile import istextfile if os.path.exists(fname): hash_md5 = hashlib.md5() binary = not istextfile(fname) siz...
Exclude specified keys from a nested dict def dict_filter(d, exclude=[]): """ Exclude specified keys from a nested dict """ if isinstance(d, list): ret = [] for e in d: ret.append(dict_filter(e, exclude)) return ret elif isinstance(d, dict): ret = {} ...
Copy file with progress bar def copyfile(src, dest, no_progress_bar=False, name=None): """Copy file with progress bar""" from dvc.progress import progress copied = 0 name = name if name else os.path.basename(dest) total = os.stat(src).st_size if os.path.isdir(dest): dest = os.path.joi...
Proxy for `os.walk` directory tree generator. Utilizes DvcIgnoreFilter functionality. def dvc_walk( top, topdown=True, onerror=None, followlinks=False, ignore_file_handler=None, ): """ Proxy for `os.walk` directory tree generator. Utilizes DvcIgnoreFilter functionality. """ ...
Returns a message in a specified color. def colorize(message, color=None): """Returns a message in a specified color.""" if not color: return message colors = { "green": colorama.Fore.GREEN, "yellow": colorama.Fore.YELLOW, "blue": colorama.Fore.BLUE, "red": colorama...
Put a message inside a box. Args: message (unicode): message to decorate. border_color (unicode): name of the color to outline the box with. def boxify(message, border_color=None): """Put a message inside a box. Args: message (unicode): message to decorate. border_color (u...
Get the the number of columns required to display a string def _visual_width(line): """Get the the number of columns required to display a string""" return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, "", line))
Center align string according to it's visual width def _visual_center(line, width): """Center align string according to it's visual width""" spaces = max(width - _visual_width(line), 0) left_padding = int(spaces / 2) right_padding = spaces - left_padding return (left_padding * " ") + line + (righ...
Workaround for bug in Python 3. See more info at: https://bugs.python.org/issue16308 https://github.com/iterative/dvc/issues/769 Args: subparsers: subparsers to fix. def fix_subparsers(subparsers): """Workaround for bug in Python 3. See more info at: https://bugs.python...
Default targets for `dvc repro` and `dvc pipeline`. def default_targets(self): """Default targets for `dvc repro` and `dvc pipeline`.""" from dvc.stage import Stage msg = "assuming default target '{}'.".format(Stage.STAGE_FILE) logger.warning(msg) return [Stage.STAGE_FILE]
Returns SCM instance that corresponds to a repo at the specified path. Args: root_dir (str): path to a root directory of the repo. repo (dvc.repo.Repo): dvc repo instance that root_dir belongs to. Returns: dvc.scm.base.Base: SCM instance. def SCM(root_dir, repo=None): # pylint: d...
Create instances of a parser containing common arguments shared among all the commands. When overwritting `-q` or `-v`, you need to instantiate a new object in order to prevent some weird behavior. def get_parent_parser(): """Create instances of a parser containing common arguments shared among al...
Parses CLI arguments. Args: argv: optional list of arguments to parse. sys.argv is used by default. Raises: dvc.exceptions.DvcParserError: raised for argument parsing errors. def parse_args(argv=None): """Parses CLI arguments. Args: argv: optional list of arguments to parse. ...
Recursively apply changes from src to dest. Preserves dest type and hidden info in dest structure, like ruamel.yaml leaves when parses files. This includes comments, ordering and line foldings. Used in Stage load/dump cycle to preserve comments and custom formatting. def apply_diff(src, dest): ""...
Callback for updating target progress def percent_cb(name, complete, total): """ Callback for updating target progress """ logger.debug( "{}: {} transferred out of {}".format( name, sizeof_fmt(complete), sizeof_fmt(total) ) ) progress.update_target(name, complete, total)
Use different md5 commands depending on the OS: - Darwin's `md5` returns BSD-style checksums by default - Linux's `md5sum` needs the `--tag` flag for a similar output Example: MD5 (foo.txt) = f3d220a856b52aabbf294351e8a24300 def md5(self, path): """ Use differ...