text
stringlengths
81
112k
Record learning rate and momentum at beginning of batch. def on_batch_begin(self, train, **kwargs:Any)->None: "Record learning rate and momentum at beginning of batch." if train: self.lrs.append(self.opt.lr) self.moms.append(self.opt.mom)
Record the loss before any other callback has a chance to modify it. def on_backward_begin(self, smooth_loss:Tensor, **kwargs:Any)->None: "Record the loss before any other callback has a chance to modify it." self.losses.append(smooth_loss) if self.pbar is not None and hasattr(self.pbar,'child'...
Save epoch info: num_batch, smooth_loss, metrics. def on_epoch_end(self, epoch:int, num_batch:int, smooth_loss:Tensor, last_metrics=MetricsList, **kwargs:Any)->bool: "Save epoch info: num_batch, smooth_loss, metrics." self.nb_batches.append(num_batch) if last_metrics is not...
Format stats before printing. def format_stats(self, stats:TensorOrNumList)->None: "Format stats before printing." str_stats = [] for name,stat in zip(self.names,stats): str_stats.append('#na#' if stat is None else str(stat) if isinstance(stat, int) else f'{stat:.6f}') if se...
Add `names` to the inner metric names. def add_metric_names(self, names): "Add `names` to the inner metric names." if hasattr(self, '_added_met_names'): self._added_met_names += names else: self._added_met_names = names
Plot learning rate, `show_moms` to include momentum. def plot_lr(self, show_moms=False, skip_start:int=0, skip_end:int=0, return_fig:bool=None)->Optional[plt.Figure]: "Plot learning rate, `show_moms` to include momentum." lrs = self._split_list(self.lrs, skip_start, skip_end) iterations = self....
Plot learning rate and losses, trimmed between `skip_start` and `skip_end`. Optionally plot and return min gradient def plot(self, skip_start:int=10, skip_end:int=5, suggestion:bool=False, return_fig:bool=None, **kwargs)->Optional[plt.Figure]: "Plot learning rate and losses, trimmed between `skip_...
Plot training and validation losses. def plot_losses(self, skip_start:int=0, skip_end:int=0, return_fig:bool=None)->Optional[plt.Figure]: "Plot training and validation losses." fig, ax = plt.subplots(1,1) losses = self._split_list(self.losses, skip_start, skip_end) iterations = self._sp...
Plot metrics collected during training. def plot_metrics(self, skip_start:int=0, skip_end:int=0, return_fig:bool=None)->Optional[plt.Figure]: "Plot metrics collected during training." assert len(self.metrics) != 0, "There are no metrics to plot." fig, axes = plt.subplots(len(self.metrics[0]),1,...
Look at params (annotated with `Param`) in func and return an `ArgumentParser` def anno_parser(func): "Look at params (annotated with `Param`) in func and return an `ArgumentParser`" p = ArgumentParser(description=func.__doc__) for k,v in inspect.signature(func).parameters.items(): param = func.__a...
Decorator to create a simple CLI from `func` using `anno_parser` def call_parse(func): "Decorator to create a simple CLI from `func` using `anno_parser`" name = inspect.currentframe().f_back.f_globals['__name__'] if name == "__main__": args = anno_parser(func).parse_args() func(**args.__dic...
Decorator to create a simple CLI from `func` using `plac` def call_plac(f): "Decorator to create a simple CLI from `func` using `plac`" name = inspect.currentframe().f_back.f_globals['__name__'] if name == '__main__': import plac res = plac.call(f) if callable(res): res() else: ...
Takes in text tokens and returns int2tok and tok2int converters Arguments: tokens(list): List of tokens. Can be a list of strings, or a list of lists of strings. max_vocab(int): Number of tokens to return in the vocab (sorted by frequency) min_freq(int): Minimum number of instances a to...
If your convolutional window is greater than 1 and you save previous xs, you must reset at the beginning of each new sequence. def reset(self): "If your convolutional window is greater than 1 and you save previous xs, you must reset at the beginning of each new sequence." for layer in self.layers: ...
Start a new kernel, and return its Manager and Client def start_new_kernel(startup_timeout=60, kernel_name='python', **kwargs): """Start a new kernel, and return its Manager and Client""" logger.debug('Starting new kernel: "%s"' % kernel_name) km = KernelManager(kernel_name=kernel_name, ...
Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found. def get_kernel_spec(self, kernel_name): """Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name ...
Function is used to get a message from the iopub channel. Timeout is None by default When timeout is reached def get_message(self, stream, timeout=None): """ Function is used to get a message from the iopub channel. Timeout is None by default When timeout is reached ...
Executes a string of python code in cell input. We do not allow the kernel to make requests to the stdin this is the norm for notebooks Function returns a unique message id of the reply from the kernel. def execute_cell_input(self, cell_input, allow_stdin=None): """ ...
Continuously poll the kernel 'shell' stream for messages until: - It receives an 'execute_reply' status for the given message id - The timeout is reached awaiting a message, in which case a `Queue.Empty` exception will be raised. def await_reply(self, msg_id, timeout=None): """ ...
Poll the iopub stream until an idle message is received for the given parent ID def await_idle(self, parent_id, timeout): """Poll the iopub stream until an idle message is received for the given parent ID""" while True: # Get a message from the kernel iopub channel msg = self.ge...
Instructs the kernel process to stop channels and the kernel manager to then shutdown the process. def stop(self): """ Instructs the kernel process to stop channels and the kernel manager to then shutdown the process. """ logger.debug('Stopping kernel') self.kc.s...
Get a list of index values for Validation set from a dataset Arguments: n : int, Total number of elements in the data set. cv_idx : int, starting index [idx_start = cv_idx*int(val_pct*n)] val_pct : (int, float), validation set percentage seed : seed value for RandomState ...
Enlarge or shrink a single image to scale, such that the smaller of the height or width dimension is equal to targ. def resize_img(fname, targ, path, new_path, fn=None): """ Enlarge or shrink a single image to scale, such that the smaller of the height or width dimension is equal to targ. """ if fn is ...
Enlarge or shrink a set of images in the same directory to scale, such that the smaller of the height or width dimension is equal to targ. Note: -- This function is multithreaded for efficiency. -- When destination file or folder already exist, function exists without raising an error. def resize_imgs(fn...
Returns a list of relative file paths to `path` for all files within `folder` def read_dir(path, folder): """ Returns a list of relative file paths to `path` for all files within `folder` """ full_path = os.path.join(path, folder) fnames = glob(f"{full_path}/*.*") directories = glob(f"{full_path}/*/") ...
Fetches name of all files in path in long form, and labels associated by extrapolation of directory names. def read_dirs(path, folder): ''' Fetches name of all files in path in long form, and labels associated by extrapolation of directory names. ''' lbls, fnames, all_lbls = [], [], [] full_path =...
one hot encoding by index. Returns array of length c, where all entries are 0, except for the indecies in ids def n_hot(ids, c): ''' one hot encoding by index. Returns array of length c, where all entries are 0, except for the indecies in ids ''' res = np.zeros((c,), dtype=np.float32) res[ids] = 1 ...
Returns the filenames and labels for a folder within a path Returns: ------- fnames: a list of the filenames within `folder` all_lbls: a list of all of the labels in `folder`, where the # of labels is determined by the # of directories within `folder` lbl_arr: a numpy array of the label indices...
Parse filenames and label sets from a CSV file. This method expects that the csv file at path :fn: has two columns. If it has a header, :skip_header: should be set to True. The labels in the label set are expected to be space separated. Arguments: fn: Path to a CSV file. skip_header: A...
True if the fn points to a DICOM image def isdicom(fn): '''True if the fn points to a DICOM image''' fn = str(fn) if fn.endswith('.dcm'): return True # Dicom signature from the dicom spec. with open(fn,'rb') as fh: fh.seek(0x80) return fh.read(4)==b'DICM'
Opens an image using OpenCV given the file path. Arguments: fn: the file path of the image Returns: The image in RGB format as numpy array of floats normalized to range between 0.0 - 1.0 def open_image(fn): """ Opens an image using OpenCV given the file path. Arguments: fn: t...
Split each array passed as *a, to a pair of arrays like this (elements selected by idxs, the remaining elements) This can be used to split multiple arrays containing training data to validation and training set. :param idxs [int]: list of indexes selected :param a list: list of np.array, each array should...
resize all images in the dataset and save them to `new_path` Arguments: targ (int): the target size new_path (string): the new folder to save the images resume (bool): if true (default), allow resuming a partial resize operation by checking for the existence of individua...
Reverse the normalization done to a batch of images. Arguments: arr: of shape/size (N,3,sz,sz) def denorm(self,arr): """Reverse the normalization done to a batch of images. Arguments: arr: of shape/size (N,3,sz,sz) """ if type(arr) is not np.ndarray: ar...
Return a copy of this dataset resized def resized(self, dl, targ, new_path, resume = True, fn=None): """ Return a copy of this dataset resized """ return dl.dataset.resize_imgs(targ, new_path, resume=resume, fn=fn) if dl else None
Resizes all the images in the train, valid, test folders to a given size. Arguments: targ_sz (int): the target size new_path (str): the path to save the resized images (default tmp) resume (bool): if True, check for images in the DataSet that haven't been resized yet (useful if a previo...
Read in images and their labels given as numpy arrays Arguments: path: a root path of the data (used for storing trained models, precomputed values, etc) trn: a tuple of training data matrix and target label/classification array (e.g. `trn=(x,y)` where `x` has the shape ...
Read in images and their labels given as sub-folder names Arguments: path: a root path of the data (used for storing trained models, precomputed values, etc) bs: batch size tfms: transformations (for data augmentations). e.g. output of `tfms_from_model` trn_name:...
Read in images and their labels given as a CSV file. This method should be used when training image labels are given in an CSV file as opposed to sub-directories with label names. Arguments: path: a root path of the data (used for storing trained models, precomputed values, etc) ...
Read in images given a sub-folder and their labels given a numpy array Arguments: path: a root path of the data (used for storing trained models, precomputed values, etc) folder: a name of the folder in which training images are contained. y: numpy array which contains targe...
Is the code running in the ipython environment (jupyter including) def is_in_ipython(): "Is the code running in the ipython environment (jupyter including)" program_name = os.path.basename(os.getenv('_', '')) if ('jupyter-notebook' in program_name or # jupyter-notebook 'ipython' in progr...
Free traceback from references to locals() in each frame to avoid circular reference leading to gc.collect() unable to reclaim memory def get_ref_free_exc_info(): "Free traceback from references to locals() in each frame to avoid circular reference leading to gc.collect() unable to reclaim memory" type, val, t...
Reclaim GPU RAM if CUDA out of memory happened, or execution was interrupted def gpu_mem_restore(func): "Reclaim GPU RAM if CUDA out of memory happened, or execution was interrupted" @functools.wraps(func) def wrapper(*args, **kwargs): tb_clear_frames = os.environ.get('FASTAI_TB_CLEAR_FRAMES', None...
Fits a model Arguments: model (model): any pytorch module net = to_gpu(net) data (ModelData): see ModelData class and subclasses (can be a list) opts: an optimizer. Example: optim.Adam. If n_epochs is a list, it needs to be the layer_optimizer to get the optimizer as it chan...
Computes the loss on the next minibatch of the validation set. def validate_next(stepper, metrics, val_iter): """Computes the loss on the next minibatch of the validation set.""" stepper.reset(False) with no_grad_context(): (*x,y) = val_iter.next() preds,l = stepper.evaluate(VV(x), VV(y)) ...
Create link to documentation. def link_type(arg_type, arg_name=None, include_bt:bool=True): "Create link to documentation." arg_name = arg_name or fn_name(arg_type) if include_bt: arg_name = code_esc(arg_name) if belongs_to_module(arg_type, 'torch') and ('Tensor' not in arg_name): return f'[{arg_name}]...
Check if `t` belongs to `module_name`. def belongs_to_module(t, module_name): "Check if `t` belongs to `module_name`." if hasattr(t, '__func__'): return belongs_to_module(t.__func__, module_name) if not inspect.getmodule(t): return False return inspect.getmodule(t).__name__.startswith(module_name)
Formats function param to `param1:Type=val`. Font weights: param1=bold, val=bold+italic def format_param(p): "Formats function param to `param1:Type=val`. Font weights: param1=bold, val=bold+italic" arg_prefix = arg_prefixes.get(p.kind, '') # asterisk prefix for *args and **kwargs res = f"**{arg_prefix}{co...
Format and link `func` definition to show in documentation def format_ft_def(func, full_name:str=None)->str: "Format and link `func` definition to show in documentation" sig = inspect.signature(func) name = f'<code>{full_name or func.__name__}</code>' fmt_params = [format_param(param) for name,param ...
Formatted enum documentation. def get_enum_doc(elt, full_name:str)->str: "Formatted enum documentation." vals = ', '.join(elt.__members__.keys()) return f'{code_esc(full_name)}',f'<code>Enum</code> = [{vals}]'
Class definition. def get_cls_doc(elt, full_name:str)->str: "Class definition." parent_class = inspect.getclasstree([elt])[-1][0][1][0] name,args = format_ft_def(elt, full_name) if parent_class != object: args += f' :: {link_type(parent_class, include_bt=True)}' return name,args
Show documentation for element `elt`. Supported types: class, Callable, and enum. def show_doc(elt, doc_string:bool=True, full_name:str=None, arg_comments:dict=None, title_level=None, alt_doc_string:str='', ignore_warn:bool=False, markdown=True, show_tests=True): "Show documentation for element `elt`....
Show `show_doc` info in preview window along with link to full docs. def doc(elt): "Show `show_doc` info in preview window along with link to full docs." global use_relative_links use_relative_links = False elt = getattr(elt, '__func__', elt) md = show_doc(elt, markdown=False) if is_fastai_clas...
Merge and format the docstring definition with `arg_comments` and `alt_doc_string`. def format_docstring(elt, arg_comments:dict={}, alt_doc_string:str='', ignore_warn:bool=False)->str: "Merge and format the docstring definition with `arg_comments` and `alt_doc_string`." parsed = "" doc = parse_docstring(in...
Search `docstring` for backticks and attempt to link those functions to respective documentation. def link_docstring(modules, docstring:str, overwrite:bool=False)->str: "Search `docstring` for backticks and attempt to link those functions to respective documentation." mods = listify(modules) for mod in mod...
Attempt to resolve keywords such as Learner.lr_find. `match_last` starts matching from last component. def find_elt(modvars, keyword, match_last=False): "Attempt to resolve keywords such as Learner.lr_find. `match_last` starts matching from last component." keyword = strip_fastai(keyword) if keyword in mod...
Return module from `mod_name`. def import_mod(mod_name:str, ignore_errors=False): "Return module from `mod_name`." splits = str.split(mod_name, '.') try: if len(splits) > 1 : mod = importlib.import_module('.' + '.'.join(splits[1:]), splits[0]) else: mod = importlib.import_module(mod_name) ...
Show documentation for `ft_name`, see `show_doc`. def show_doc_from_name(mod_name, ft_name:str, doc_string:bool=True, arg_comments:dict={}, alt_doc_string:str=''): "Show documentation for `ft_name`, see `show_doc`." mod = import_mod(mod_name) splits = str.split(ft_name, '.') assert hasattr(mod, splits[...
Return all the functions of module `mod`. def get_ft_names(mod, include_inner=False)->List[str]: "Return all the functions of module `mod`." # If the module has an attribute __all__, it picks those. # Otherwise, it returns all the functions defined inside a module. fn_names = [] for elt_name in get...
List the inner functions of a class. def get_inner_fts(elt)->List[str]: "List the inner functions of a class." fts = [] for ft_name in elt.__dict__.keys(): if ft_name.startswith('_'): continue ft = getattr(elt, ft_name) if inspect.isfunction(ft): fts.append(f'{elt.__name__}.{ft_name...
Display table of contents for given `mod_name`. def get_module_toc(mod_name): "Display table of contents for given `mod_name`." mod = import_mod(mod_name) ft_names = mod.__all__ if hasattr(mod,'__all__') else get_ft_names(mod) ft_names.sort(key = str.lower) tabmat = '' for ft_name in ft_names: ...
Return function link to notebook documentation of `ft`. Private functions link to source code def get_fn_link(ft)->str: "Return function link to notebook documentation of `ft`. Private functions link to source code" ft = getattr(ft, '__func__', ft) anchor = strip_fastai(get_anchor(ft)) module_name = st...
Returns link to pytorch docs of `ft`. def get_pytorch_link(ft)->str: "Returns link to pytorch docs of `ft`." name = ft.__name__ ext = '.html' if name == 'device': return f'{PYTORCH_DOCS}tensor_attributes{ext}#torch-device' if name == 'Tensor': return f'{PYTORCH_DOCS}tensors{ext}#torch-tensor' i...
Returns github link for given file def get_source_link(file, line, display_text="[source]", **kwargs)->str: "Returns github link for given file" link = f"{SOURCE_URL}{file}#L{line}" if display_text is None: return link return f'<a href="{link}" class="source_link" style="float:right">{display_text}</a>...
Returns link to `ft` in source code. def get_function_source(ft, **kwargs)->str: "Returns link to `ft` in source code." try: line = inspect.getsourcelines(ft)[1] except Exception: return '' mod_path = get_module_name(ft).replace('.', '/') + '.py' return get_source_link(mod_path, line, **kwargs)
Look through the cell source for comments which affect nbval's behaviour Yield an iterable of ``(MARKER_TYPE, True)``. def find_comment_markers(cellsource): """Look through the cell source for comments which affect nbval's behaviour Yield an iterable of ``(MARKER_TYPE, True)``. """ found = {} ...
Merge all stream outputs with shared names into single streams to ensure deterministic outputs. Parameters ---------- outputs : iterable of NotebookNodes Outputs being processed def coalesce_streams(outputs): """ Merge all stream outputs with shared names into single streams to ens...
Makes failure output for streams better by having key be the stream name def transform_streams_for_comparison(outputs): """Makes failure output for streams better by having key be the stream name""" new_outputs = [] for output in outputs: if (output.output_type == 'stream'): # Transform...
Trim and hash base64 strings def _trim_base64(s): """Trim and hash base64 strings""" if len(s) > 64 and _base64.match(s.replace('\n', '')): h = hash_string(s) s = '%s...<snip base64, md5=%s...>' % (s[:8], h[:16]) return s
Intent each line with indent def _indent(s, indent=' '): """Intent each line with indent""" if isinstance(s, six.string_types): return '\n'.join(('%s%s' % (indent, line) for line in s.splitlines())) return s
Called by pytest to setup the collector cells in . Here we start a kernel and setup the sanitize patterns. def setup(self): """ Called by pytest to setup the collector cells in . Here we start a kernel and setup the sanitize patterns. """ if self.parent.config.option.cu...
For each of the sanitize files that were specified as command line options load the contents of the file into the sanitise patterns dictionary. def setup_sanitize_files(self): """ For each of the sanitize files that were specified as command line options load the contents of the file in...
Return list of all sanitize files provided by the user on the command line. N.B.: We only support one sanitize file at the moment, but this is likely to change in the future def get_sanitize_files(self): """ Return list of all sanitize files provided by the user on the command li...
Gets a message from the iopub channel of the notebook kernel. def get_kernel_message(self, timeout=None, stream='iopub'): """ Gets a message from the iopub channel of the notebook kernel. """ return self.kernel.get_message(stream, timeout=timeout)
The collect function is required by pytest and is used to yield pytest Item objects. We specify an Item for each code cell in the notebook. def collect(self): """ The collect function is required by pytest and is used to yield pytest Item objects. We specify an Item for each code cell i...
called when self.runtest() raises an exception. def repr_failure(self, excinfo): """ called when self.runtest() raises an exception. """ exc = excinfo.value cc = self.colors if isinstance(exc, NbCellError): msg_items = [ cc.FAIL + "Notebook cell execution fai...
Format an output for printing def format_output_compare(self, key, left, right): """Format an output for printing""" if isinstance(left, six.string_types): left = _trim_base64(left) if isinstance(right, six.string_types): right = _trim_base64(right) cc = self.co...
sanitize a string for comparison. def sanitize(self, s): """sanitize a string for comparison. """ if not isinstance(s, six.string_types): return s """ re.sub matches a regex and replaces it with another. The regex replacements are taken from a file if the op...
Computes the outputs for several augmented inputs for TTA def _tta_only(learn:Learner, ds_type:DatasetType=DatasetType.Valid, scale:float=1.35) -> Iterator[List[Tensor]]: "Computes the outputs for several augmented inputs for TTA" dl = learn.dl(ds_type) ds = dl.dataset old = ds.tfms augm_tfm = [o f...
Applies TTA to predict on `ds_type` dataset. def _TTA(learn:Learner, beta:float=0.4, scale:float=1.35, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False) -> Tensors: "Applies TTA to predict on `ds_type` dataset." preds,y = learn.get_preds(ds_type) all_preds = list(learn.tta_only(scale=scale, ds_t...
Computes the f_beta between `preds` and `targets` def fbeta(y_pred:Tensor, y_true:Tensor, thresh:float=0.2, beta:float=2, eps:float=1e-9, sigmoid:bool=True)->Rank0Tensor: "Computes the f_beta between `preds` and `targets`" beta2 = beta ** 2 if sigmoid: y_pred = y_pred.sigmoid() y_pred = (y_pred>thresh)...
Compute accuracy with `targs` when `input` is bs * n_classes. def accuracy(input:Tensor, targs:Tensor)->Rank0Tensor: "Compute accuracy with `targs` when `input` is bs * n_classes." n = targs.shape[0] input = input.argmax(dim=-1).view(n,-1) targs = targs.view(n,-1) return (input==targs).float().mean...
Compute accuracy when `y_pred` and `y_true` are the same size. def accuracy_thresh(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor: "Compute accuracy when `y_pred` and `y_true` are the same size." if sigmoid: y_pred = y_pred.sigmoid() return ((y_pred>thresh)==y_true.byte())....
Computes the Top-k accuracy (target is in the top k predictions). def top_k_accuracy(input:Tensor, targs:Tensor, k:int=5)->Rank0Tensor: "Computes the Top-k accuracy (target is in the top k predictions)." input = input.topk(k=k, dim=-1)[1] targs = targs.unsqueeze(dim=-1).expand_as(input) return (input =...
Dice coefficient metric for binary target. If iou=True, returns iou metric, classic for segmentation problems. def dice(input:Tensor, targs:Tensor, iou:bool=False)->Rank0Tensor: "Dice coefficient metric for binary target. If iou=True, returns iou metric, classic for segmentation problems." n = targs.shape[0] ...
Exp RMSE between `pred` and `targ`. def exp_rmspe(pred:Tensor, targ:Tensor)->Rank0Tensor: "Exp RMSE between `pred` and `targ`." pred,targ = flatten_check(pred,targ) pred, targ = torch.exp(pred), torch.exp(targ) pct_var = (targ - pred)/targ return torch.sqrt((pct_var**2).mean())
Mean absolute error between `pred` and `targ`. def mean_absolute_error(pred:Tensor, targ:Tensor)->Rank0Tensor: "Mean absolute error between `pred` and `targ`." pred,targ = flatten_check(pred,targ) return torch.abs(targ - pred).mean()
Mean squared error between `pred` and `targ`. def mean_squared_error(pred:Tensor, targ:Tensor)->Rank0Tensor: "Mean squared error between `pred` and `targ`." pred,targ = flatten_check(pred,targ) return F.mse_loss(pred, targ)
Root mean squared error between `pred` and `targ`. def root_mean_squared_error(pred:Tensor, targ:Tensor)->Rank0Tensor: "Root mean squared error between `pred` and `targ`." pred,targ = flatten_check(pred,targ) return torch.sqrt(F.mse_loss(pred, targ))
Mean squared logarithmic error between `pred` and `targ`. def mean_squared_logarithmic_error(pred:Tensor, targ:Tensor)->Rank0Tensor: "Mean squared logarithmic error between `pred` and `targ`." pred,targ = flatten_check(pred,targ) return F.mse_loss(torch.log(1 + pred), torch.log(1 + targ))
Explained variance between `pred` and `targ`. def explained_variance(pred:Tensor, targ:Tensor)->Rank0Tensor: "Explained variance between `pred` and `targ`." pred,targ = flatten_check(pred,targ) var_pct = torch.var(targ - pred) / torch.var(targ) return 1 - var_pct
R2 score (coefficient of determination) between `pred` and `targ`. def r2_score(pred:Tensor, targ:Tensor)->Rank0Tensor: "R2 score (coefficient of determination) between `pred` and `targ`." pred,targ = flatten_check(pred,targ) u = torch.sum((targ - pred) ** 2) d = torch.sum((targ - targ.mean()) ** 2) ...
Using trapezoid method to calculate the area under roc curve def auc_roc_score(input:Tensor, targ:Tensor): "Using trapezoid method to calculate the area under roc curve" fpr, tpr = roc_curve(input, targ) d = fpr[1:] - fpr[:-1] sl1, sl2 = [slice(None)], [slice(None)] sl1[-1], sl2[-1] = slice(1, None...
Returns the false positive and true positive rates def roc_curve(input:Tensor, targ:Tensor): "Returns the false positive and true positive rates" targ = (targ == 1) desc_score_indices = torch.flip(input.argsort(-1), [-1]) input = input[desc_score_indices] targ = targ[desc_score_indices] d = inp...
convert iterable object into numpy array def A(*a): """convert iterable object into numpy array""" return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]
Convert numpy array into a pytorch tensor. if Cuda is available and USE_GPU=True, store resulting tensor in GPU. def T(a, half=False, cuda=True): """ Convert numpy array into a pytorch tensor. if Cuda is available and USE_GPU=True, store resulting tensor in GPU. """ if not torch.is_tensor(a):...
equivalent to create_variable, which creates a pytorch tensor def V_(x, requires_grad=False, volatile=False): '''equivalent to create_variable, which creates a pytorch tensor''' return create_variable(x, volatile=volatile, requires_grad=requires_grad)
creates a single or a list of pytorch tensors, depending on input x. def V(x, requires_grad=False, volatile=False): '''creates a single or a list of pytorch tensors, depending on input x. ''' return map_over(x, lambda o: V_(o, requires_grad, volatile))
returns an np.array object given an input of np.array, list, tuple, torch variable or tensor. def to_np(v): '''returns an np.array object given an input of np.array, list, tuple, torch variable or tensor.''' if isinstance(v, float): return np.array(v) if isinstance(v, (np.ndarray, np.generic)): return v ...
puts pytorch variable to gpu, if cuda is available and USE_GPU is set to true. def to_gpu(x, *args, **kwargs): '''puts pytorch variable to gpu, if cuda is available and USE_GPU is set to true. ''' return x.cuda(*args, **kwargs) if USE_GPU else x