text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 eq...
if fn is None: fn = resize_fn(targ) dest = os.path.join(path_for(path, new_path, targ), fname) if os.path.exists(dest): return im = Image.open(os.path.join(path, fname)).convert('RGB') os.makedirs(os.path.split(dest)[0], exist_ok=True) fn(im).save(dest)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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}/*/") if any(fnames): return [os.path.relpath(f,path) for f in fnames] elif any(directories): raise FileNotFoundError("{} has subdirectories but contains no files. Is your direct...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 = os.path.join(path, folder) for lbl in sorted(os.listdir(full_path)): if lbl not in ('.ipynb_che...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_csv_labels(fn, skip_header=True, cat_separator = ' '): """Parse filenames and label sets from a CSV file. This method expects that the csv file at path...
df = pd.read_csv(fn, index_col=0, header=0 if skip_header else None, dtype=str) fnames = df.index.values df.iloc[:,0] = df.iloc[:,0].str.split(cat_separator) return fnames, list(df.to_dict().values())[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_image(fn): """ 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 arra...
flags = cv2.IMREAD_UNCHANGED+cv2.IMREAD_ANYDEPTH+cv2.IMREAD_ANYCOLOR if not os.path.exists(fn) and not str(fn).startswith("http"): raise OSError('No such file or directory: {}'.format(fn)) elif os.path.isdir(fn) and not str(fn).startswith("http"): raise OSError('Is a directory: {}'.format(f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: arr = to_np(arr) if len(arr.shape)==3: arr = arr[None] return self.transform.denorm(np.rollaxis(arr,1,4))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resize(self, targ_sz, new_path='tmp', resume=True, fn=None): """ Resizes all the images in the train, valid, test folders to a given size. Arguments: targ_sz...
new_ds = [] dls = [self.trn_dl,self.val_dl,self.fix_dl,self.aug_dl] if self.test_dl: dls += [self.test_dl, self.test_aug_dl] else: dls += [None,None] t = tqdm_notebook(dls) for dl in t: new_ds.append(self.resized(dl, targ_sz, new_path, resume, fn)) t.close() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_arrays(cls, path, trn, val, bs=64, tfms=(None,None), classes=None, num_workers=4, test=None, continuous=False): """ Read in images and their labels give...
f = ArraysIndexRegressionDataset if continuous else ArraysIndexDataset datasets = cls.get_ds(f, trn, val, tfms, test=test) return cls(path, datasets, bs, num_workers, classes=classes)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_paths(cls, path, bs=64, tfms=(None,None), trn_name='train', val_name='valid', test_name=None, test_with_labels=False, num_workers=8): """ Read in images...
assert not(tfms[0] is None or tfms[1] is None), "please provide transformations for your train and validation sets" trn,val = [folder_source(path, o) for o in (trn_name, val_name)] if test_name: test = folder_source(path, test_name) if test_with_labels else read_dir(path, test_name)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_csv(cls, path, folder, csv_fname, bs=64, tfms=(None,None), val_idxs=None, suffix='', test_name=None, continuous=False, skip_header=True, num_workers=8, c...
assert not (tfms[0] is None or tfms[1] is None), "please provide transformations for your train and validation sets" assert not (os.path.isabs(folder)), "folder needs to be a relative path" fnames,y,classes = csv_source(folder, csv_fname, skip_header, suffix, continuous=continuous, cat_separato...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_path_and_array(cls, path, folder, y, classes=None, val_idxs=None, test_name=None, num_workers=8, tfms=(None,None), bs=64): """ Read in images given a su...
assert not (tfms[0] is None or tfms[1] is None), "please provide transformations for your train and validation sets" assert not (os.path.isabs(folder)), "folder needs to be a relative path" fnames = np.core.defchararray.add(f'{folder}/', sorted(os.listdir(f'{path}{folder}'))) return cls...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): t...
) raise type(val).with_traceback(tb) from None else: raise # re-raises the exact last exception return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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}]({get_pytorch_link(arg_type)})'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 in sig.parameters.items() if name not in ('s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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}]'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_class(elt): md += f'\n\n<a href="{get_fn_link(elt)}" target="_blan...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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(inspect.getdoc(elt)) description = alt_doc_string or f"{doc['short_description']} {...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 mods: _modvars.update(mod.__dict__) # concat all module definitions return re.sub(BT_REGEX, replac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 modvars: return modvars[keyword] comps = keyword.split('.') comp_elt = modvars.get(comps[0]) if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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) return mod except: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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[0]), print(f"Module {mod_name} doesn't have a funct...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_exports(mod): elt = getattr(mod,el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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}') if inspect.ismethod(ft): f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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: tabmat += f'- [{ft_name}](#{ft_name})\n' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 = strip_fastai(get_module_name(ft)) base = '' if use_relative_links else FASTAI_DOCS return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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' if name.startswith('torchvision'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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>'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = {} for line in cellsource.splitlines(): line = line.strip() if line.startswith('#'): # print("Found comment in '{}'".format(line)) comment = line.lstrip('#').strip() if comment in comment_markers: # print("Found marker {}".format(comme...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coalesce_streams(outputs): """ Merge all stream outputs with shared names into single streams to ensure deterministic outputs. Parameters outputs : iterable ...
if not outputs: return outputs new_outputs = [] streams = {} for output in outputs: if (output.output_type == 'stream'): if output.name in streams: streams[output.name].text += output.text else: new_outputs.append(output) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 output new_outputs.append({ 'output_type': 'stream', output.name: output.text, }) else: new_outputs.append(output) return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.current_env: kernel_name = CURRENT_ENV_KERNEL_NAME else: kernel_name = self.nb.metadata.get( 'kernelspec', {}).get('name', 'python') self.kernel = RunningKernel(kernel_name, str(self.fspath.dirname)) self.setup_saniti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_sanitize_files(self): """ For each of the sanitize files that were specified as command line options load the contents of the file into the sanitise pa...
for fname in self.get_sanitize_files(): with open(fname, 'r') as f: self.sanitize_patterns.update(get_sanitize_patterns(f.read()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_sanitize_files(self): """ Return list of all sanitize files provided by the user on the command line. N.B.: We only support one sanitize file at the mome...
if self.parent.config.option.sanitize_with is not None: return [self.parent.config.option.sanitize_with] else: return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 in the notebook...
self.nb = nbformat.read(str(self.fspath), as_version=4) # Start the cell count cell_num = 0 # Iterate over the cells in the notebook for cell in self.nb.cells: # Skip the cells that have text, headings or related stuff # Only test code cells ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.colors self.comparison_traceback.append( cc.OKBLUE + " mismatch '%s'" % key + cc.F...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 option is passed when py.test is called. Otherwise, the strings are not processed """ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 for o in learn.data.train_ds.tfms if o.tfm not in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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_type=ds_type)) avg_preds = torch.stack(all_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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).float() y_true = y_true.float() TP = (y_pr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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()).float().mean()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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] input = input.argmax(dim=1).view(n,-1) targs = targs.view(n,-1) intersect = (input * targs).sum().flo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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), slice(None, -1) return (d * (tpr[tuple(sl1)] + tpr[tupl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 = input[1:] - input[:-1] distinct_value_indices = tor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): a = np.array(np.ascontiguousarray(a)) if a.dtype in (np.int8, np.int16, np.int32, np.int64): a = torch.LongTensor(a.astype(np.int64)) elif a.dtype in (np.float32, np.float64): a = to_half(a) if half else torch.FloatTensor(a) else: r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 if isinstance(v, (list,tuple)): return [to_np(o) for o in v] if isinstance(v, Variable): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def split_by_idxs(seq, idxs): '''A generator that returns sequence pieces, seperated by indexes specified in idxs. ''' last = 0 for idx in idxs: if not (-len(seq) <= idx < len(seq)): raise KeyError(f'Idx {idx} is out-of-bounds') yield seq[last:idx] last = idx yield seq[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def partition(a, sz): """splits iterables a in equal parts of size sz"""
return [a[i:i+sz] for i in range(0, len(a), sz)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def chunk_iter(iterable, chunk_size): '''A generator that yields chunks of iterable, chunk_size at a time. ''' while True: chunk = [] try: for _ in range(chunk_size): chunk.append(next(iterable)) yield chunk except StopIteration: if chunk: yield chunk ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _brightness(x, change:uniform): "Apply `change` in brightness of image `x`." return x.add_(scipy.special.logit(change))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _rotate(degrees:uniform): "Rotate image by `degrees`." angle = degrees * math.pi / 180 return [[cos(angle), -sin(angle), 0.], [sin(angle), cos(angle), 0.], [0. , 0. , 1.]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_zoom_mat(sw:float, sh:float, c:float, r:float)->AffineMatrix: "`sw`,`sh` scale width,height - `c`,`r` focus col,row." return [[sw, 0, c], [0, sh, r], [0, 0, 1.]]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _zoom(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5): "Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom." s = 1-1/scale col_c = s * (2*col_pct - 1) row_c = s * (2*row_pct - 1) return _get_zoom_mat(1/scale, 1/scale, col_c, row_c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _squish(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5): "Squish image by `scale`. `row_pct`,`col_pct` select focal point of zoom." if scale <= 1: col_c = (1-scale) * (2*col_pct - 1) return _get_zoom_mat(scale, 1, col_c, 0.) else: row_c = (1-1/scale) * (2*row_pct - 1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _jitter(c, magnitude:uniform): "Replace pixels by random neighbors at `magnitude`." c.flow.add_((torch.rand_like(c.flow)-0.5)*magnitude*2) return c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _flip_lr(x): "Flip `x` horizontally." #return x.flip(2) if isinstance(x, ImagePoints): x.flow.flow[...,0] *= -1 return x return tensor(np.ascontiguousarray(np.array(x)[...,::-1]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _cutout(x, n_holes:uniform_int=1, length:uniform_int=40): "Cut out `n_holes` number of square holes of size `length` in image at random locations." h,w = x.shape[1:] for n in range(n_holes): h_y = np.random.randint(0, h) h_x = np.random.randint(0, w) y1 = int(np.clip(h_y - length...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _rgb_randomize(x, channel:int=None, thresh:float=0.3): "Randomize one of the channels of the input image" if channel is None: channel = np.random.randint(0, x.shape[0] - 1) x[channel] = torch.rand(x.shape[1:]) * np.random.uniform(0, thresh) return x
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _crop_default(x, size, row_pct:uniform=0.5, col_pct:uniform=0.5): "Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop." rows,cols = tis2hw(size) row_pct,col_pct = _minus_epsilon(row_pct,col_pct) row = int((x.size(1)-rows+1) * row_pct) col = int((x.size(2)-cols+1) * col_pct...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _crop_pad_default(x, size, padding_mode='reflection', row_pct:uniform = 0.5, col_pct:uniform = 0.5): "Crop and pad tfm - `row_pct`,`col_pct` sets focal point." padding_mode = _pad_mode_convert[padding_mode] size = tis2hw(size) if x.shape[1:] == torch.Size(size): return x rows,cols = size row...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rand_pad(padding:int, size:int, mode:str='reflection'): "Fixed `mode` `padding` and random crop of `size`" return [pad(padding=padding,mode=mode), crop(size=size, **rand_pos)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rand_zoom(scale:uniform=1.0, p:float=1.): "Randomized version of `zoom`." return zoom(scale=scale, **rand_pos, p=p)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rand_crop(*args, padding_mode='reflection', p:float=1.): "Randomized version of `crop_pad`." return crop_pad(*args, **rand_pos, padding_mode=padding_mode, p=p)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _apply_perspective(coords:FlowField, coeffs:Points)->FlowField: "Transform `coords` with `coeffs`." size = coords.flow.size() #compress all the dims expect the last one ang adds ones, coords become N * 3 coords.flow = coords.flow.view(-1,2) #Transform the coeffs in a 3*3 matrix with a 1 at the b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _do_perspective_warp(c:FlowField, targ_pts:Points, invert=False): "Apply warp to `targ_pts` from `_orig_pts` to `c` `FlowField`." if invert: return _apply_perspective(c, _find_coeffs(targ_pts, _orig_pts)) return _apply_perspective(c, _find_coeffs(_orig_pts, targ_pts))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _perspective_warp(c, magnitude:partial(uniform,size=8)=0, invert=False): "Apply warp of `magnitude` to `c`." magnitude = magnitude.view(4,2) targ_pts = [[x+m for x,m in zip(xs, ms)] for xs, ms in zip(_orig_pts, magnitude)] return _do_perspective_warp(c, targ_pts, invert)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _symmetric_warp(c, magnitude:partial(uniform,size=4)=0, invert=False): "Apply symmetric warp of `magnitude` to `c`." m = listify(magnitude, 4) targ_pts = [[-1-m[3],-1-m[1]], [-1-m[2],1+m[1]], [1+m[3],-1-m[0]], [1+m[2],1+m[0]]] return _do_perspective_warp(c, targ_pts, invert)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _tilt(c, direction:uniform_int, magnitude:uniform=0, invert=False): "Tilt `c` field with random `direction` and `magnitude`." orig_pts = [[-1,-1], [-1,1], [1,-1], [1,1]] if direction == 0: targ_pts = [[-1,-1], [-1,1], [1,-1-magnitude], [1,1+magnitude]] elif direction == 1: targ_pts = [[-1,-1-magni...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_transforms(do_flip:bool=True, flip_vert:bool=False, max_rotate:float=10., max_zoom:float=1.1, max_lighting:float=0.2, max_warp:float=0.2, p_affine:float=0.75, p_lighting:float=0.75, xtra_tfms:Optional[Collection[Transform]]=None)->Collection[Transform]: "Utility func to...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_layer_opt(self, lrs, wds): """Method returns an instance of the LayerOptimizer class, which allows for setting differential learning rates for different ...
return LayerOptimizer(self.opt_fn, self.get_layer_groups(), lrs, wds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lr_find(self, start_lr=1e-5, end_lr=10, wds=None, linear=False, **kwargs): """Helps you find an optimal learning rate for a model. It uses the technique deve...
self.save('tmp') layer_opt = self.get_layer_opt(start_lr, wds) self.sched = LR_Finder(layer_opt, len(self.data.trn_dl), end_lr, linear=linear) self.fit_gen(self.model, self.data, layer_opt, 1, **kwargs) self.load('tmp')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def on_loss_begin(self, last_output:Tuple[Tensor,Tensor,Tensor], **kwargs): "Save the extra outputs for later and only returns the true output." self.raw_out,self.out = last_output[1],last_output[2] return {'last_output': last_output[0]}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def on_backward_begin(self, last_loss:Rank0Tensor, last_input:Tensor, **kwargs): "Apply AR and TAR to `last_loss`." #AR and TAR if self.alpha != 0.: last_loss += self.alpha * self.out[-1].float().pow(2).mean() if self.beta != 0.: h = self.raw_out[-1] if len(h)>1:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def convert_weights(wgts:Weights, stoi_wgts:Dict[str,int], itos_new:Collection[str]) -> Weights: "Convert the model `wgts` to go with a new vocabulary." dec_bias, enc_wgts = wgts.get('1.decoder.bias', None), wgts['0.encoder.weight'] wgts_m = enc_wgts.mean(0) if dec_bias is not None: bias_m = dec_bias.me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_language_model(arch:Callable, vocab_sz:int, config:dict=None, drop_mult:float=1.): "Create a language model from `arch` and its `config`, maybe `pretrained`." meta = _model_meta[arch] config = ifnone(config, meta['config_lm'].copy()) for k in config.keys(): if k.endswith('_p'): config[k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def language_model_learner(data:DataBunch, arch, config:dict=None, drop_mult:float=1., pretrained:bool=True, pretrained_fnames:OptStrTuple=None, **learn_kwargs) -> 'LanguageLearner': "Create a `Learner` with a language model from `data` and `arch`." model = get_language_model(arch, le...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None, drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None, pad_idx:int=1) -> nn.Module: "Create a text classifier from `arch` and it...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def text_classifier_learner(data:DataBunch, arch:Callable, bptt:int=70, max_len:int=70*20, config:dict=None, pretrained:bool=True, drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None, **learn_kwargs) -> 'TextClassifierLearner': "Crea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def save_encoder(self, name:str): "Save the encoder to `name` inside the model directory." encoder = get_model(self.model)[0] if hasattr(encoder, 'module'): encoder = encoder.module torch.save(encoder.state_dict(), self.path/self.model_dir/f'{name}.pth')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_encoder(self, name:str, device:torch.device=None): "Load the encoder `name` from the model directory." encoder = get_model(self.model)[0] if device is None: device = self.data.device if hasattr(encoder, 'module'): encoder = encoder.module encoder.load_state_dict(torch.lo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_pretrained(self, wgts_fname:str, itos_fname:str, strict:bool=True): "Load a pretrained model and adapts it to the data vocabulary." old_itos = pickle.load(open(itos_fname, 'rb')) old_stoi = {v:k for k,v in enumerate(old_itos)} wgts = torch.load(wgts_fname, map_location=lambda st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_preds(self, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False, n_batch:Optional[int]=None, pbar:Optional[PBar]=None, ordered:bool=False) -> List[Tensor]: "Return predictions and targets on the valid, train, or test set, depending on `ds_type`." self.model.reset() ...