INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
A function that uses the compare function to return a value from the list.
def findvalue(array, value, compare = lambda x, y: x == y): "A function that uses the compare function to return a value from the list." try: return next(x for x in array if compare(x, value)) except StopIteration: raise ValueError('%r not in array'%value)
Set the values and labels, and select the first option if we aren't initializing
def _propagate_options(self, change): "Set the values and labels, and select the first option if we aren't initializing" options = self._options_full self.set_trait('_options_labels', tuple(i[0] for i in options)) self._options_values = tuple(i[1] for i in options) if self._initi...
Propagate changes in index to the value and label properties
def _propagate_index(self, change): "Propagate changes in index to the value and label properties" label = self._options_labels[change.new] if change.new is not None else None value = self._options_values[change.new] if change.new is not None else None if self.label is not label: ...
Check the range of each proposed index.
def _validate_index(self, proposal): "Check the range of each proposed index." if all(0 <= i < len(self._options_labels) for i in proposal.value): return proposal.value else: raise TraitError('Invalid selection: index out of bounds')
Replace all values with the actual objects in the options list
def _validate_value(self, proposal): "Replace all values with the actual objects in the options list" try: return tuple(findvalue(self._options_values, i, self.equals) for i in proposal.value) except ValueError: raise TraitError('Invalid selection: value not found')
Adds a class to the top level element of the widget. Doesn't add the class if it already exists.
def add_class(self, className): """ Adds a class to the top level element of the widget. Doesn't add the class if it already exists. """ if className not in self._dom_classes: self._dom_classes = list(self._dom_classes) + [className] return self
Removes a class from the top level element of the widget. Doesn't remove the class if it doesn't exist.
def remove_class(self, className): """ Removes a class from the top level element of the widget. Doesn't remove the class if it doesn't exist. """ if className in self._dom_classes: self._dom_classes = [c for c in self._dom_classes if c != className] return s...
Register the jupyter.widget comm target
def register_comm_target(kernel=None): """Register the jupyter.widget comm target""" if kernel is None: kernel = get_ipython().kernel kernel.comm_manager.register_target('jupyter.widget', Widget.handle_comm_opened)
Substitute format strings in class or function docstring
def doc_subst(snippets): """ Substitute format strings in class or function docstring """ def decorator(cls): # Strip the snippets to avoid trailing new lines and whitespace stripped_snippets = { key: snippet.strip() for (key, snippet) in snippets.items() } cls.__doc_...
Get absolute path to resource, works for dev and for PyInstaller
def base_uri(relative_path=''): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: if 'pytest' in sys.modules: for arg in reversed(sys.arg...
:param file_type: file type string 'description (*.file_extension1;*.file_extension2)' as required by file filter in create_file_dialog :return: (description, file extensions) tuple
def parse_file_type(file_type): ''' :param file_type: file type string 'description (*.file_extension1;*.file_extension2)' as required by file filter in create_file_dialog :return: (description, file extensions) tuple ''' valid_file_filter = r'^([\w ]+)\((\*(?:\.(?:\w+|\*))*(?:;\*\.\w+)*)\)$' ma...
Python 2 and 3 compatibility function that converts a string to Unicode. In case of Unicode, the string is returned unchanged :param string: input string :return: Unicode string
def make_unicode(string): """ Python 2 and 3 compatibility function that converts a string to Unicode. In case of Unicode, the string is returned unchanged :param string: input string :return: Unicode string """ if sys.version < '3' and isinstance(string, str): return unicode(string....
Create a default Cocoa menu that shows 'Services', 'Hide', 'Hide Others', 'Show All', and 'Quit'. Will append the application name to some menu items if it's available.
def _add_app_menu(self): """ Create a default Cocoa menu that shows 'Services', 'Hide', 'Hide Others', 'Show All', and 'Quit'. Will append the application name to some menu items if it's available. """ # Set the main menu for the application mainMenu = AppKit.NSMe...
Create a default View menu that shows 'Enter Full Screen'.
def _add_view_menu(self): """ Create a default View menu that shows 'Enter Full Screen'. """ mainMenu = self.app.mainMenu() # Create an View menu and make it a submenu of the main menu viewMenu = AppKit.NSMenu.alloc().init() viewMenu.setTitle_(localization["cocoa...
Convert given hex color to NSColor. :hex_string: Hex code of the color as #RGB or #RRGGBB
def nscolor_from_hex(hex_string): """ Convert given hex color to NSColor. :hex_string: Hex code of the color as #RGB or #RRGGBB """ hex_string = hex_string[1:] # Remove leading hash if len(hex_string) == 3: hex_string = ''.join([c*2 for c in hex_string])...
Return a BrowserView instance by the :value of its given :attribute, and None if no match is found.
def get_instance(attr, value): """ Return a BrowserView instance by the :value of its given :attribute, and None if no match is found. """ for i in list(BrowserView.instances.values()): try: if getattr(i, attr) == value: return i ...
Return a PyObjCMethodSignature object for given signature string. :param signature_str: A byte string containing the type encoding for the method signature :return: A method signature object, assignable to attributes like __block_signature__ :rtype: <type objc._method_signature>
def pyobjc_method_signature(signature_str): """ Return a PyObjCMethodSignature object for given signature string. :param signature_str: A byte string containing the type encoding for the method signature :return: A method signature object, assignable to attributes like __block_signature...
Invoke a folder selection dialog here :return:
def choose_path(): """ Invoke a folder selection dialog here :return: """ dirs = webview.create_file_dialog(webview.FOLDER_DIALOG) if dirs and len(dirs) > 0: directory = dirs[0] if isinstance(directory, bytes): directory = directory.decode("utf-8") response =...
By default hosted IE control emulates IE7 regardless which version of IE is installed. To fix this, a proper value must be set for the executable. See http://msdn.microsoft.com/en-us/library/ee330730%28v=vs.85%29.aspx#browser_emulation for details on this behaviour.
def set_ie_mode(): """ By default hosted IE control emulates IE7 regardless which version of IE is installed. To fix this, a proper value must be set for the executable. See http://msdn.microsoft.com/en-us/library/ee330730%28v=vs.85%29.aspx#browser_emulation for details on this behaviour. """ ...
Decorator to call a pywebview API, checking for _webview_ready and raisings appropriate Exceptions on failure.
def _api_call(function): """ Decorator to call a pywebview API, checking for _webview_ready and raisings appropriate Exceptions on failure. """ @wraps(function) def wrapper(*args, **kwargs): try: if not _webview_ready.wait(15): raise Exception('Main window fai...
Create a web view window using a native GUI. The execution blocks after this function is invoked, so other program logic must be executed in a separate thread. :param title: Window title :param url: URL to load :param width: window width. Default is 800px :param height:window height. Default is 600p...
def create_window(title, url=None, js_api=None, width=800, height=600, resizable=True, fullscreen=False, min_size=(200, 100), strings={}, confirm_quit=False, background_color='#FFFFFF', text_select=False, frameless=False, debug=False): """ Create a web view window using a nat...
Create a file dialog :param dialog_type: Dialog type: open file (OPEN_DIALOG), save file (SAVE_DIALOG), open folder (OPEN_FOLDER). Default is open file. :param directory: Initial directory :param allow_multiple: Allow multiple selection. Default is false. :param save_filename: De...
def create_file_dialog(dialog_type=OPEN_DIALOG, directory='', allow_multiple=False, save_filename='', file_types=()): """ Create a file dialog :param dialog_type: Dialog type: open file (OPEN_DIALOG), save file (SAVE_DIALOG), open folder (OPEN_FOLDER). Default is open file. :para...
Load a new content into a previously created WebView window. This function must be invoked after WebView windows is created with create_window(). Otherwise an exception is thrown. :param content: Content to load. :param base_uri: Base URI for resolving links. Default is the directory of the application entr...
def load_html(content, base_uri=base_uri(), uid='master'): """ Load a new content into a previously created WebView window. This function must be invoked after WebView windows is created with create_window(). Otherwise an exception is thrown. :param content: Content to load. :param base_uri: Base UR...
Evaluate given JavaScript code and return the result :param script: The JavaScript code to be evaluated :param uid: uid of the target instance :return: Return value of the evaluated code
def evaluate_js(script, uid='master'): """ Evaluate given JavaScript code and return the result :param script: The JavaScript code to be evaluated :param uid: uid of the target instance :return: Return value of the evaluated code """ escaped_script = 'JSON.stringify(eval("{0}"))'.format(esca...
Setup data layer according to parameters: - nyud_dir: path to NYUDv2 dir - split: train / val / test - tops: list of tops to output from {color, depth, hha, label} - randomize: load in random order (default: True) - seed: seed for randomization (default: None / current time) ...
def setup(self, bottom, top): """ Setup data layer according to parameters: - nyud_dir: path to NYUDv2 dir - split: train / val / test - tops: list of tops to output from {color, depth, hha, label} - randomize: load in random order (default: True) - seed: seed fo...
Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order
def load_image(self, idx): """ Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order """ im = Image.open('{}/data/images/img_{}.png'.format(self.nyud_dir, idx))...
Load label image as 1 x height x width integer array of label indices. Shift labels so that classes are 0-39 and void is 255 (to ignore it). The leading singleton dimension is required by the loss.
def load_label(self, idx): """ Load label image as 1 x height x width integer array of label indices. Shift labels so that classes are 0-39 and void is 255 (to ignore it). The leading singleton dimension is required by the loss. """ label = scipy.io.loadmat('{}/segmentati...
Load pre-processed depth for NYUDv2 segmentation set.
def load_depth(self, idx): """ Load pre-processed depth for NYUDv2 segmentation set. """ im = Image.open('{}/data/depth/img_{}.png'.format(self.nyud_dir, idx)) d = np.array(im, dtype=np.float32) d = np.log(d) d -= self.mean_logd d = d[np.newaxis, ...] ...
Load HHA features from Gupta et al. ECCV14. See https://github.com/s-gupta/rcnn-depth/blob/master/rcnn/saveHHA.m
def load_hha(self, idx): """ Load HHA features from Gupta et al. ECCV14. See https://github.com/s-gupta/rcnn-depth/blob/master/rcnn/saveHHA.m """ im = Image.open('{}/data/hha/img_{}.png'.format(self.nyud_dir, idx)) hha = np.array(im, dtype=np.float32) hha -= self....
Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order
def load_image(self, idx): """ Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order """ im = Image.open('{}/Images/spatial_envelope_256x256_static_8outdoorcate...
Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss.
def load_label(self, idx, label_type=None): """ Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. """ if label_type == 'semantic': label = scipy.io.loadmat('{}/SemanticLabels/spatial_envelop...
Make a 2D bilinear kernel suitable for upsampling
def get_upsampling_weight(in_channels, out_channels, kernel_size): """Make a 2D bilinear kernel suitable for upsampling""" factor = (kernel_size + 1) // 2 if kernel_size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:kernel_size, :kernel_size] filt = (1 ...
Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc
def label_accuracy_score(label_trues, label_preds, n_class): """Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc """ hist = np.zeros((n_class, n_class)) for lt, lp in zip(label_trues, label_preds): hist += _fast_hist(lt.fla...
Transfer weights by copying matching parameters, coercing parameters of incompatible shape, and dropping unmatched parameters. The coercion is useful to convert fully connected layers to their equivalent convolutional layers, since the weights are the same and only the shapes are different. In particu...
def transplant(new_net, net, suffix=''): """ Transfer weights by copying matching parameters, coercing parameters of incompatible shape, and dropping unmatched parameters. The coercion is useful to convert fully connected layers to their equivalent convolutional layers, since the weights are the sa...
Set weights of each layer in layers to bilinear kernels for interpolation.
def interp(net, layers): """ Set weights of each layer in layers to bilinear kernels for interpolation. """ for l in layers: m, k, h, w = net.params[l][0].data.shape if m != k and k != 1: print 'input + output channels need to be the same or |output| == 1' raise ...
Transplant an old score layer's parameters, with k < k' classes, into a new score layer with k classes s.t. the first k' are the old classes.
def expand_score(new_net, new_layer, net, layer): """ Transplant an old score layer's parameters, with k < k' classes, into a new score layer with k classes s.t. the first k' are the old classes. """ old_cl = net.params[layer][0].num new_net.params[new_layer][0].data[:old_cl][...] = net.params[l...
Setup data layer according to parameters: - voc_dir: path to PASCAL VOC year dir - split: train / val / test - mean: tuple of mean values to subtract - randomize: load in random order (default: True) - seed: seed for randomization (default: None / current time) for PASC...
def setup(self, bottom, top): """ Setup data layer according to parameters: - voc_dir: path to PASCAL VOC year dir - split: train / val / test - mean: tuple of mean values to subtract - randomize: load in random order (default: True) - seed: seed for randomizatio...
Setup data layer according to parameters: - voc_dir: path to PASCAL VOC dir (must contain 2010) - context_dir: path to PASCAL-Context annotations - split: train / val / test - randomize: load in random order (default: True) - seed: seed for randomization (default: None / current...
def setup(self, bottom, top): """ Setup data layer according to parameters: - voc_dir: path to PASCAL VOC dir (must contain 2010) - context_dir: path to PASCAL-Context annotations - split: train / val / test - randomize: load in random order (default: True) - see...
Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. The full 400 labels are translated to the 59 class task labels.
def load_label(self, idx): """ Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. The full 400 labels are translated to the 59 class task labels. """ label_400 = scipy.io.loadmat('{}/trainval/{}....
Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss.
def load_label(self, idx): """ Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. """ label = Image.open('{}/SegmentationClass/{}.png'.format(self.dir, idx)) label = np.array(label, dtype=np.uint...
Transfer the VOC color palette to an output mask for visualization.
def palette(self, label_im): ''' Transfer the VOC color palette to an output mask for visualization. ''' if label_im.ndim == 3: label_im = label_im[0] label = Image.fromarray(label_im, mode='P') label.palette = copy.copy(self.palette) return label
Deterministically shuffle identically under both py2 + py3.
def _shuffled(seq): """Deterministically shuffle identically under both py2 + py3.""" fixed_random = random.Random() if six.PY2: # pragma: no cover (py2) fixed_random.seed(FIXED_RANDOM_SEED) else: # pragma: no cover (py3) fixed_random.seed(FIXED_RANDOM_SEED, version=1) seq = list(...
In this context, `os.environ` is modified according to `patch`. `patch` is an iterable of 2-tuples (key, value): `key`: string `value`: - string: `environ[key] == value` inside the context. - UNSET: `key not in environ` inside the context. - template: A template ...
def envcontext(patch, _env=None): """In this context, `os.environ` is modified according to `patch`. `patch` is an iterable of 2-tuples (key, value): `key`: string `value`: - string: `environ[key] == value` inside the context. - UNSET: `key not in environ` inside the con...
On windows there's a different directory for the virtualenv
def bin_dir(venv): """On windows there's a different directory for the virtualenv""" bin_part = 'Scripts' if os.name == 'nt' else 'bin' return os.path.join(venv, bin_part)
Install the pre-commit hooks.
def install( config_file, store, overwrite=False, hooks=False, hook_type='pre-commit', skip_on_missing_conf=False, ): """Install the pre-commit hooks.""" if cmd_output('git', 'config', 'core.hooksPath', retcode=None)[1].strip(): logger.error( 'Cowardly refusing to ins...
Uninstall the pre-commit hooks.
def uninstall(hook_type='pre-commit'): """Uninstall the pre-commit hooks.""" hook_path, legacy_path = _hook_paths(hook_type) # If our file doesn't exist or it isn't ours, gtfo. if not os.path.exists(hook_path) or not is_our_script(hook_path): return 0 os.remove(hook_path) output.write_...
Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine
def normalize_cmd(cmd): """Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine """ # Use PATH to determine the executable exe = normexe(cmd[0]) # Figure out the sheban...
Prints a message for running a hook. This currently supports three approaches: # Print `start` followed by dots, leaving 6 characters at the end >>> print_hook_message('start', end_len=6) start............................................................... # Print `start` followed by dots with th...
def get_hook_message( start, postfix='', end_msg=None, end_len=0, end_color=None, use_color=None, cols=80, ): """Prints a message for running a hook. This currently supports three approaches: # Print `start` followed by dots, leaving 6 characters at ...
See https://github.com/pre-commit/pre-commit/issues/354
def check_for_cygwin_mismatch(): """See https://github.com/pre-commit/pre-commit/issues/354""" if sys.platform in ('cygwin', 'win32'): # pragma: no cover (windows) is_cygwin_python = sys.platform == 'cygwin' toplevel = cmd_output('git', 'rev-parse', '--show-toplevel')[1] is_cygwin_git =...
A simplified implementation of xargs. negate: Make nonzero successful and zero a failure target_concurrency: Target number of partitions to run concurrently
def xargs(cmd, varargs, **kwargs): """A simplified implementation of xargs. negate: Make nonzero successful and zero a failure target_concurrency: Target number of partitions to run concurrently """ negate = kwargs.pop('negate', False) target_concurrency = kwargs.pop('target_concurrency', 1) ...
Makes an archive of a repository in the given destdir. :param text name: Name to give the archive. For instance foo. The file that is created will be called foo.tar.gz. :param text repo: Repository to clone. :param text ref: Tag/SHA/branch to check out. :param text destdir: Directory to place arc...
def make_archive(name, repo, ref, destdir): """Makes an archive of a repository in the given destdir. :param text name: Name to give the archive. For instance foo. The file that is created will be called foo.tar.gz. :param text repo: Repository to clone. :param text ref: Tag/SHA/branch to check o...
Compute the number of columns to display hook messages. The widest that will be displayed is in the no files skipped case: Hook name...(no files to check) Skipped or in the verbose case Hook name [hookid]...(no files to check) Skipped
def _compute_cols(hooks, verbose): """Compute the number of columns to display hook messages. The widest that will be displayed is in the no files skipped case: Hook name...(no files to check) Skipped or in the verbose case Hook name [hookid]...(no files to check) Skipped """ if ...
Actually run the hooks.
def _run_hooks(config, hooks, args, environ): """Actually run the hooks.""" skips = _get_skips(environ) cols = _compute_cols(hooks, args.verbose) filenames = _all_filenames(args) filenames = filter_by_include_exclude(filenames, '', config['exclude']) classifier = Classifier(filenames) retval...
On windows, rmtree fails for readonly dirs.
def rmtree(path): """On windows, rmtree fails for readonly dirs.""" def handle_remove_readonly(func, path, exc): # pragma: no cover (windows) excvalue = exc[1] if ( func in (os.rmdir, os.remove, os.unlink) and excvalue.errno == errno.EACCES ): ...
Updates a repository to the tip of `master`. If the repository cannot be updated because a hook that is configured does not exist in `master`, this raises a RepositoryCannotBeUpdatedError Args: repo_config - A config for a repository
def _update_repo(repo_config, store, tags_only): """Updates a repository to the tip of `master`. If the repository cannot be updated because a hook that is configured does not exist in `master`, this raises a RepositoryCannotBeUpdatedError Args: repo_config - A config for a repository """ ...
Auto-update the pre-commit config to the latest versions of repos.
def autoupdate(config_file, store, tags_only, repos=()): """Auto-update the pre-commit config to the latest versions of repos.""" migrate_config(config_file, quiet=True) retv = 0 output_repos = [] changed = False input_config = load_config(config_file) for repo_config in input_config['repo...
A -mvenv virtualenv made from a -mvirtualenv virtualenv installs packages to the incorrect location. Attempt to find the _original_ exe and invoke `-mvenv` from there. See: - https://github.com/pre-commit/pre-commit/issues/755 - https://github.com/pypa/virtualenv/issues/1095 - https://bugs.pyt...
def orig_py_exe(exe): # pragma: no cover (platform specific) """A -mvenv virtualenv made from a -mvirtualenv virtualenv installs packages to the incorrect location. Attempt to find the _original_ exe and invoke `-mvenv` from there. See: - https://github.com/pre-commit/pre-commit/issues/755 - ...
As of Windows 10, the Windows console supports (some) ANSI escape sequences, but it needs to be enabled using `SetConsoleMode` first. More info on the escape sequences supported: https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
def enable_virtual_terminal_processing(): """As of Windows 10, the Windows console supports (some) ANSI escape sequences, but it needs to be enabled using `SetConsoleMode` first. More info on the escape sequences supported: https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx...
Format text with color. Args: text - Text to be formatted with color if `use_color` color - The color start string use_color_setting - Whether or not to color
def format_color(text, color, use_color_setting): """Format text with color. Args: text - Text to be formatted with color if `use_color` color - The color start string use_color_setting - Whether or not to color """ if not use_color_setting: return text else: ...
Choose whether to use color based on the command argument. Args: setting - Either `auto`, `always`, or `never`
def use_color(setting): """Choose whether to use color based on the command argument. Args: setting - Either `auto`, `always`, or `never` """ if setting not in COLOR_CHOICES: raise InvalidColorSetting(setting) return ( setting == 'always' or (setting == 'auto' and s...
Returns the default directory for the Store. This is intentionally underscored to indicate that `Store.get_default_directory` is the intended way to get this information. This is also done so `Store.get_default_directory` can be mocked in tests and `_get_default_directory` can be tested.
def _get_default_directory(): """Returns the default directory for the Store. This is intentionally underscored to indicate that `Store.get_default_directory` is the intended way to get this information. This is also done so `Store.get_default_directory` can be mocked in tests and `_get_default_di...
Perform a shallow clone of a repository and its submodules
def _shallow_clone(self, ref, git_cmd): # pragma: windows no cover """Perform a shallow clone of a repository and its submodules """ git_config = 'protocol.version=2' git_cmd('-c', git_config, 'fetch', 'origin', ref, '--depth=1') git_cmd('checkout', ref) git_cmd( '-...
Clone the given url and checkout the specific ref.
def clone(self, repo, ref, deps=()): """Clone the given url and checkout the specific ref.""" if os.path.isdir(repo): repo = os.path.abspath(repo) def clone_strategy(directory): env = git.no_git_env() def _git_cmd(*args): cmd_output('git', *...
Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert nex...
def compounding(start, stop, compound, t=0.0): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. ...
Yield an infinite series of values according to Howard and Ruder's "slanted triangular learning rate" schedule.
def slanted_triangular(max_rate, num_steps, cut_frac=0.1, ratio=32, decay=1, t=0.0): """Yield an infinite series of values according to Howard and Ruder's "slanted triangular learning rate" schedule. """ cut = int(num_steps * cut_frac) while True: t += 1 if t < cut: p = t...
Check that arguments have the same length.
def equal_length(*args): """Check that arguments have the same length. """ for i, arg in enumerate(args): if not isinstance(arg, Sized): raise ExpectedTypeError(arg, ["Sized"]) if i >= 1 and len(arg) != len(args[0]): raise DifferentLengthError(args, arg)
Check that elements have the same dimension on specified axis.
def equal_axis(*args, **axis): """Check that elements have the same dimension on specified axis. """ axis = axis.get("axis", -1) for i, arg in enumerate(args): if not isinstance(arg, ndarray): raise ExpectedTypeError(arg, ["ndarray"]) if axis >= 0 and (axis + 1) < arg.shape[a...
Bind operators to specified functions for the scope of the context: Example ------- model = Model() other = Model() with Model.define_operators({"+": lambda self, other: "plus"}): print(model + other) # "plus" print(model ...
def define_operators(cls, operators): """Bind operators to specified functions for the scope of the context: Example ------- model = Model() other = Model() with Model.define_operators({"+": lambda self, other: "plus"}): print(model + other) ...
Check that a particular argument is an array with a given shape. The shape may contain string attributes, which will be fetched from arg0 to the function (usually self).
def has_shape(shape): """Check that a particular argument is an array with a given shape. The shape may contain string attributes, which will be fetched from arg0 to the function (usually self). """ def has_shape_inner(arg_id, args, kwargs): self = args[0] arg = args[arg_id] ...
Change the device to execute on for the scope of the block.
def use_device(cls, device): """Change the device to execute on for the scope of the block.""" if device == cls.ops.device: yield else: curr_Ops, curr_ops = (cls.Ops, cls.ops) cls.Ops = get_ops(device) cls.ops = cls.Ops() yield ...
x Must match expected type Must match expected shape y Must match expected type
def evaluate(self, X, y): """ x Must match expected type Must match expected shape y Must match expected type """ scores = self.ops.flatten(list(self.pipe(X))) if not hasattr(y, "shape"): y = self.ops.flatten(y) scor...
Check we can learn to output a zero vector
def check_learns_zero_output_rnn(model, sgd, X, Y, initial_hidden=None): """Check we can learn to output a zero vector""" outputs, get_dX = model.begin_update(X, initial_hidden) Yh, h_n = outputs tupleDy = (Yh - Y, h_n) dX = get_dX(tupleDy, sgd=sgd) prev = numpy.abs(Yh.sum()) print(prev) ...
Return the output of the wrapped PyTorch model for the given input, along with a callback to handle the backward pass.
def begin_update(self, x_data, drop=0.0): """Return the output of the wrapped PyTorch model for the given input, along with a callback to handle the backward pass. """ x_var = torch.autograd.Variable(xp2torch(x_data), requires_grad=True) # Make prediction y_var = self._m...
Return the output of the wrapped PyTorch model for the given input, along with a callback to handle the backward pass.
def begin_update(self, x_data, h_0=None, drop=0.0): """Return the output of the wrapped PyTorch model for the given input, along with a callback to handle the backward pass. """ x_var = torch.autograd.Variable(xp2torch(x_data), requires_grad=True) # Make prediction out, ...
Wrap a function into a layer
def layerize(begin_update=None, predict=None, *args, **kwargs): """Wrap a function into a layer""" if begin_update is not None: return FunctionLayer(begin_update, predict=predict, *args, **kwargs) def wrapper(begin_update): return FunctionLayer(begin_update, *args, **kwargs) return wra...
Wrap a function over a sequence of layers and an input into a layer.
def metalayerize(user_func): """Wrap a function over a sequence of layers and an input into a layer.""" def returned(layers, *args, **kwargs): def begin_update(X, *args, **kwargs): return user_func(layers, X, *args, **kwargs) return FunctionLayer(begin_update, *args, **kwargs) ...
Transform a sequences of layers into a null operation.
def noop(*layers): """Transform a sequences of layers into a null operation.""" def begin_update(X, drop=0.0): return X, lambda D, *a, **k: D return begin_update
Compose two models `f` and `g` such that they become layers of a single feed-forward model that computes `g(f(x))`. Raises exception if their dimensions don't match.
def chain(*layers): """Compose two models `f` and `g` such that they become layers of a single feed-forward model that computes `g(f(x))`. Raises exception if their dimensions don't match. """ if len(layers) == 0: return FeedForward([]) elif len(layers) == 1: return layers[0] ...
Construct `n` copies of a layer, with distinct weights. i.e. `clone(f, 3)(x)` computes `f(f'(f''(x)))`.
def clone(orig, n): """Construct `n` copies of a layer, with distinct weights. i.e. `clone(f, 3)(x)` computes `f(f'(f''(x)))`. """ if n == 0: return layerize(noop()) layers = [orig] for i in range(n - 1): layers.append(copy.deepcopy(orig)) layers[-1].set_id() return ...
Compose two or more models `f`, `g`, etc, such that their outputs are concatenated, i.e. `concatenate(f, g)(x)` computes `hstack(f(x), g(x))`
def concatenate(*layers): # pragma: no cover """Compose two or more models `f`, `g`, etc, such that their outputs are concatenated, i.e. `concatenate(f, g)(x)` computes `hstack(f(x), g(x))` """ if not layers: return noop() ops = layers[0].ops def begin_update(X, *a, **k): forwa...
Separate a sequence of layers' `begin_update` methods into two lists of functions: one that computes the forward values, and the other that completes the backward pass. The backward sequence is only populated after the forward functions have been applied.
def split_backward(layers): # pragma: no cover """Separate a sequence of layers' `begin_update` methods into two lists of functions: one that computes the forward values, and the other that completes the backward pass. The backward sequence is only populated after the forward functions have been applie...
Transform a function `func` that returns tuples into a function that returns single values. Call a function `sink` on the unused values.
def sink_return(func, sink, splitter=None): # pragma: no cover """Transform a function `func` that returns tuples into a function that returns single values. Call a function `sink` on the unused values. """ def wrap(*args, **kwargs): output = func(*args, **kwargs) if splitter is None: ...
Group inputs to a layer, so that the layer only has to compute for the unique values. The data is transformed back before output, and the same transformation is applied for the gradient. Effectively, this is a cache local to each minibatch. The uniqued wrapper is useful for word inputs, because common ...
def uniqued(layer, column=0): """Group inputs to a layer, so that the layer only has to compute for the unique values. The data is transformed back before output, and the same transformation is applied for the gradient. Effectively, this is a cache local to each minibatch. The uniqued wrapper is us...
Map a layer across list items
def foreach(layer, drop_factor=1.0): """Map a layer across list items""" def foreach_fwd(docs, drop=0.0): sents = [] lengths = [] for doc in docs: doc_sents = [sent for sent in doc if len(sent)] subset = [ s for s in doc_sents if numpy.random.rand...
Map a layer across sentences (assumes spaCy-esque .sents interface)
def foreach_sentence(layer, drop_factor=1.0): """Map a layer across sentences (assumes spaCy-esque .sents interface)""" def sentence_fwd(docs, drop=0.0): sents = [] lengths = [] for doc in docs: doc_sents = [sent for sent in doc.sents if len(sent)] subset = [ ...
Serialize user defined function.
def func_dump(func): '''Serialize user defined function.''' code = marshal.dumps(func.__code__).decode('raw_unicode_escape') defaults = func.__defaults__ if func.__closure__: closure = tuple(c.cell_contents for c in func.__closure__) else: closure = None return code, defaults, cl...
Deserialize user defined function.
def func_load(code, defaults=None, closure=None, globs=None): '''Deserialize user defined function.''' if isinstance(code, (tuple, list)): # unpack previous dump code, defaults, closure = code code = marshal.loads(code.encode('raw_unicode_escape')) if globs is None: globs = globals() ...
Parse the texts with spaCy. Make one-hot vectors for the labels.
def preprocess(ops, nlp, rows, get_ids): """Parse the texts with spaCy. Make one-hot vectors for the labels.""" Xs = [] ys = [] for (text1, text2), label in rows: Xs.append((get_ids([nlp(text1)])[0], get_ids([nlp(text2)])[0])) ys.append(label) return Xs, to_categorical(ys, nb_classes...
Create a bidirectional LSTM layer. Args: number out, number in
def BiLSTM(nO, nI): """Create a bidirectional LSTM layer. Args: number out, number in""" return Bidirectional(LSTM(nO // 2, nI), LSTM(nO // 2, nI))
Create an LSTM layer. Args: number out, number in
def LSTM(nO, nI): """Create an LSTM layer. Args: number out, number in""" weights = LSTM_weights(nO, nI) gates = LSTM_gates(weights.ops) return Recurrent(RNN_step(weights, gates))
Stitch two RNN models into a bidirectional layer.
def Bidirectional(l2r, r2l): """Stitch two RNN models into a bidirectional layer.""" nO = l2r.nO def birnn_fwd(Xs, drop=0.0): l2r_Zs, bp_l2r_Zs = l2r.begin_update(Xs, drop=drop) r2l_Zs, bp_r2l_Zs = r2l.begin_update( [l2r.ops.xp.ascontiguousarray(X[::-1]) for X in Xs] ) ...
Apply a stepwise model over a sequence, maintaining state. For RNNs
def Recurrent(step_model): """Apply a stepwise model over a sequence, maintaining state. For RNNs""" ops = step_model.ops def recurrent_fwd(seqs, drop=0.0): lengths = [len(X) for X in seqs] X, size_at_t, unpad = ops.square_sequences(seqs) Y = ops.allocate((X.shape[0], X.shape[1], st...
Create a step model for an RNN, given weights and gates functions.
def RNN_step(weights, gates): """Create a step model for an RNN, given weights and gates functions.""" def rnn_step_fwd(prevstate_inputs, drop=0.0): prevstate, inputs = prevstate_inputs cell_tm1, hidden_tm1 = prevstate acts, bp_acts = weights.begin_update((inputs, hidden_tm1), drop=dro...
Downloads a file from a URL if it not already in the cache. Passing the MD5 hash will verify the file after download as well as if it is already present in the cache. # Arguments fname: name of the file origin: original URL of the file untar: boolean, whether the file should be decompr...
def get_file(fname, origin, untar=False, unzip=False, md5_hash=None, cache_subdir='datasets'): '''Downloads a file from a URL if it not already in the cache. Passing the MD5 hash will verify the file after download as well as if it is already present in the cache. # Arguments fname: n...
Validates a file against a MD5 hash # Arguments fpath: path to the file being validated md5_hash: the MD5 hash being validated against # Returns Whether the file is valid
def validate_file(fpath, md5_hash): '''Validates a file against a MD5 hash # Arguments fpath: path to the file being validated md5_hash: the MD5 hash being validated against # Returns Whether the file is valid ''' hasher = hashlib.md5() with open(fpath, 'rb') as f: ...
Get word forms.
def Orth(docs, drop=0.0): """Get word forms.""" ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i") i = 0 for doc in docs: for token in doc: ids[i] = token.orth i += 1 return ids, None
Get word shapes.
def Shape(docs, drop=0.0): """Get word shapes.""" ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i") i = 0 for doc in docs: for token in doc: ids[i] = token.shape i += 1 return ids, None
Get prefixes.
def Prefix(docs, drop=0.0): """Get prefixes.""" ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i") i = 0 for doc in docs: for token in doc: ids[i] = token.prefix i += 1 return ids, None
Get suffixes.
def Suffix(docs, drop=0.0): """Get suffixes.""" ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i") i = 0 for doc in docs: for token in doc: ids[i] = token.suffix i += 1 return ids, None
Print training progress. Called after each epoch.
def track_progress(**context): """Print training progress. Called after each epoch.""" model = context["model"] train_X = context["train_X"] dev_X = context["dev_X"] dev_y = context["dev_y"] n_train = len(train_X) trainer = context["trainer"] def each_epoch(): global epoch_train...