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 str_slice(arr, start=None, stop=None, step=None): """ Slice substrings from each element in the Series or Index. Parameters start : int, optional Start posit...
obj = slice(start, stop, step) f = lambda x: x[obj] return _na_map(f, arr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def str_slice_replace(arr, start=None, stop=None, repl=None): """ Replace a positional slice of a string with another value. Parameters start : int, optional Lef...
if repl is None: repl = '' def f(x): if x[start:stop] == '': local_stop = start else: local_stop = stop y = '' if start is not None: y += x[:start] y += repl if stop is not None: y += x[local_stop:] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def str_get(arr, i): """ Extract element from each component at specified position. Extract element from lists, tuples, or strings in each element in the Series/...
def f(x): if isinstance(x, dict): return x.get(i) elif len(x) > i >= -len(x): return x[i] return np.nan return _na_map(f, arr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dispatch(name, *args, **kwargs): """ Dispatch to apply. """
def outer(self, *args, **kwargs): def f(x): x = self._shallow_copy(x, groupby=self._groupby) return getattr(x, name)(*args, **kwargs) return self._groupby.apply(f) outer.__name__ = name return outer
<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_str(s): """ Convert bytes and non-string into Python 3 str """
if isinstance(s, bytes): s = s.decode('utf-8') elif not isinstance(s, str): s = str(s) 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 frame_apply(obj, func, axis=0, broadcast=None, raw=False, reduce=None, result_type=None, ignore_failures=False, args=None, kwds=None): """ construct and retu...
axis = obj._get_axis_number(axis) if axis == 0: klass = FrameRowApply elif axis == 1: klass = FrameColumnApply return klass(obj, func, broadcast=broadcast, raw=raw, reduce=reduce, result_type=result_type, ignore_failures=ignore_failures, ...
<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_result(self): """ compute the results """
# dispatch to agg if is_list_like(self.f) or is_dict_like(self.f): return self.obj.aggregate(self.f, axis=self.axis, *self.args, **self.kwds) # all empty if len(self.columns) == 0 and len(self.index) == 0: return self.apply...
<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_empty_result(self): """ we have an empty result; at least 1 axis is 0 we will try to apply the function to an empty series in order to see if this is a...
# we are not asked to reduce or infer reduction # so just return a copy of the existing object if self.result_type not in ['reduce', None]: return self.obj.copy() # we may need to infer reduce = self.result_type == 'reduce' from pandas import Series ...
<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_raw(self): """ apply to the values as a numpy array """
try: result = reduction.reduce(self.values, self.f, axis=self.axis) except Exception: result = np.apply_along_axis(self.f, self.axis, self.values) # TODO: mixed type case if result.ndim == 2: return self.obj._constructor(result, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_results_for_axis(self): """ return the results for the rows """
results = self.results result = self.obj._constructor(data=results) if not isinstance(results[0], ABCSeries): try: result.index = self.res_columns except ValueError: pass try: result.columns = self.res_index ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_results_for_axis(self): """ return the results for the columns """
results = self.results # we have requested to expand if self.result_type == 'expand': result = self.infer_to_same_shape() # we have a non-series and don't want inference elif not isinstance(results[0], ABCSeries): from pandas import Series 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 infer_to_same_shape(self): """ infer the results to the same shape as the input object """
results = self.results result = self.obj._constructor(data=results) result = result.T # set the index result.index = self.res_index # infer dtypes result = result.infer_objects() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def xception(c, k=8, n_middle=8): "Preview version of Xception network. Not tested yet - use at own risk. No pretrained model yet." layers = [ conv(3, k*4, 3, 2), conv(k*4, k*8, 3), ConvSkip(k*8, k*16, act=False), ConvSkip(k*16, k*32), ConvSkip(k*32, k*91), ] for ...
<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_model(self, opt_fn, emb_sz, n_hid, n_layers, **kwargs): """ Method returns a RNN_Learner object, that wraps an instance of the RNN_Encoder module. Args: ...
m = get_language_model(self.nt, emb_sz, n_hid, n_layers, self.pad_idx, **kwargs) model = SingleModel(to_gpu(m)) return RNN_Learner(self, model, opt_fn=opt_fn)
<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_text_files(cls, path, field, train, validation, test=None, bs=64, bptt=70, **kwargs): """ Method used to instantiate a LanguageModelData object that can...
trn_ds, val_ds, test_ds = ConcatTextDataset.splits( path, text_field=field, train=train, validation=validation, test=test) return cls(path, field, trn_ds, val_ds, test_ds, bs, bptt, **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 get_files(path:PathOrStr, extensions:Collection[str]=None, recurse:bool=False, include:Optional[Collection[str]]=None)->FilePathList: "Return list of files in `path` that have a suffix in `extensions`; optionally `recurse`." if recurse: res = [] for i,(p,d,f) in enumerate(os.wa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def process(self, processor:PreProcessors=None): "Apply `processor` or `self.processor` to `self`." if processor is not None: self.processor = processor self.processor = listify(self.processor) for p in self.processor: p.process(self) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def process_one(self, item:ItemBase, processor:PreProcessors=None): "Apply `processor` or `self.processor` to `item`." if processor is not None: self.processor = processor self.processor = listify(self.processor) for p in self.processor: item = p.process_one(item) return item
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reconstruct(self, t:Tensor, x:Tensor=None): "Reconstruct one of the underlying item for its data `t`." return self[0].reconstruct(t,x) if has_arg(self[0].reconstruct, 'x') else self[0].reconstruct(t)
<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_folder(cls, path:PathOrStr, extensions:Collection[str]=None, recurse:bool=True, include:Optional[Collection[str]]=None, processor:PreProcessors=None, **k...
path = Path(path) return cls(get_files(path, extensions, recurse=recurse, include=include), path=path, processor=processor, **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 from_df(cls, df:DataFrame, path:PathOrStr='.', cols:IntsOrStrs=0, processor:PreProcessors=None, **kwargs)->'ItemList': "Create an `ItemList` in `path` from the inputs in the `cols` of `df`." inputs = df.iloc[:,df_names_to_idx(cols, df)] assert inputs.isna().sum().sum() == 0, f"You have NaN v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def use_partial_data(self, sample_pct:float=0.01, seed:int=None)->'ItemList': "Use only a sample of `sample_pct`of the full dataset and an optional `seed`." if seed is not None: np.random.seed(seed) rand_idx = np.random.permutation(range_of(self)) cut = int(sample_pct * len(self)) ...
<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_text(self, fn:str): "Save `self.items` to `fn` in `self.path`." with open(self.path/fn, 'w') as f: f.writelines([f'{o}\n' for o in self._relative_item_paths()])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def filter_by_func(self, func:Callable)->'ItemList': "Only keep elements for which `func` returns `True`." self.items = array([o for o in self.items if func(o)]) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def filter_by_folder(self, include=None, exclude=None): "Only keep filenames in `include` folder or reject the ones in `exclude`." include,exclude = listify(include),listify(exclude) def _inner(o): if isinstance(o, Path): n = o.relative_to(self.path).parts[0] else: n = o....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def filter_by_rand(self, p:float, seed:int=None): "Keep random sample of `items` with probability `p` and an optional `seed`." if seed is not None: np.random.seed(seed) return self.filter_by_func(lambda o: rand_bool(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 split_none(self): "Don't split the data and create an empty validation set." val = self[[]] val.ignore_empty = True return self._split(self.path, self, val)
<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_list(self, train, valid): "Split the data between `train` and `valid`." return self._split(self.path, train, valid)
<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(self, train_idx, valid_idx): "Split the data between `train_idx` and `valid_idx`." return self.split_by_list(self[train_idx], self[valid_idx])
<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_idx(self, valid_idx:Collection[int])->'ItemLists': "Split the data according to the indexes in `valid_idx`." #train_idx = [i for i in range_of(self.items) if i not in valid_idx] train_idx = np.setdiff1d(arange_of(self.items), valid_idx) return self.split_by_idxs(train_idx, v...
<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_rand_pct(self, valid_pct:float=0.2, seed:int=None)->'ItemLists': "Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed." if valid_pct==0.: return self.split_none() if seed is not None: np.random.seed(seed) rand_idx = np.random....
<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_files(self, valid_names:'ItemList')->'ItemLists': "Split the data by using the names in `valid_names` for validation." if isinstance(self.items[0], Path): return self.split_by_valid_func(lambda o: o.name in valid_names) else: return self.split_by_valid_func(lambda o: os.path.basenam...
<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_fname_file(self, fname:PathOrStr, path:PathOrStr=None)->'ItemLists': "Split the data by using the names in `fname` for the validation set. `path` will override `self.path`." path = Path(ifnone(path, self.path)) valid_names = loadtxt_str(path/fname) return self.split_by_files...
<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_from_df(self, col:IntsOrStrs=2): "Split the data from the `col` in the dataframe in `self.inner_df`." valid_idx = np.where(self.inner_df.iloc[:,df_names_to_idx(col, self.inner_df)])[0] return self.split_by_idx(valid_idx)
<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_label_cls(self, labels, label_cls:Callable=None, label_delim:str=None, **kwargs): "Return `label_cls` or guess one from the first element of `labels`." if label_cls is not None: return label_cls if self.label_cls is not None: return self.label_cls if label_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _label_from_list(self, labels:Iterator, label_cls:Callable=None, from_item_lists:bool=False, **kwargs)->'LabelList': "Label `self.items` with `labels`." if not from_item_lists: raise Exception("Your data isn't split, if you don't want a validation set, please use `split_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 label_from_df(self, cols:IntsOrStrs=1, label_cls:Callable=None, **kwargs): "Label `self.items` from the values in `cols` in `self.inner_df`." labels = self.inner_df.iloc[:,df_names_to_idx(cols, self.inner_df)] assert labels.isna().sum().sum() == 0, f"You have NaN values in column(s) {cols} o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def label_const(self, const:Any=0, label_cls:Callable=None, **kwargs)->'LabelList': "Label every item with `const`." return self.label_from_func(func=lambda o: const, label_cls=label_cls, **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 label_empty(self, **kwargs): "Label every item with an `EmptyLabel`." kwargs['label_cls'] = EmptyLabelList return self.label_from_func(func=lambda o: 0., **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 label_from_func(self, func:Callable, label_cls:Callable=None, **kwargs)->'LabelList': "Apply `func` to every input to get its label." return self._label_from_list([func(o) for o in self.items], label_cls=label_cls, **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 label_from_folder(self, label_cls:Callable=None, **kwargs)->'LabelList': "Give a label to each filename depending on its folder." return self.label_from_func(func=lambda o: (o.parts if isinstance(o, Path) else o.split(os.path.sep))[-2], label_cls=label_cls, **kwar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def label_from_re(self, pat:str, full_path:bool=False, label_cls:Callable=None, **kwargs)->'LabelList': "Apply the re in `pat` to determine the label of every filename. If `full_path`, search in the full name." pat = re.compile(pat) def _inner(o): s = str((os.path.join(self.path,o) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generate_classes(self, items): "Generate classes from `items` by taking the sorted unique values." classes = set() for c in items: classes = classes.union(set(c)) classes = list(classes) classes.sort() return 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 label_from_lists(self, train_labels:Iterator, valid_labels:Iterator, label_cls:Callable=None, **kwargs)->'LabelList': "Use the labels in `train_labels` and `valid_labels` to label the data. `label_cls` will overwrite the default." label_cls = self.train.get_label_cls(train_labels, label_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 transform(self, tfms:Optional[Tuple[TfmList,TfmList]]=(None,None), **kwargs): "Set `tfms` to be applied to the xs of the train and validation set." if not tfms: tfms=(None,None) assert is_listy(tfms) and len(tfms) == 2, "Please pass a list of two lists of transforms (train and valid)." ...
<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_y(self, tfms:Optional[Tuple[TfmList,TfmList]]=(None,None), **kwargs): "Set `tfms` to be applied to the ys of the train and validation set." if not tfms: tfms=(None,None) self.train.transform_y(tfms[0], **kwargs) self.valid.transform_y(tfms[1], **kwargs) if self.test...
<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_processors(self): "Read the default class processors if none have been set." procs_x,procs_y = listify(self.train.x._processor),listify(self.train.y._processor) xp = ifnone(self.train.x.processor, [p(ds=self.train.x) for p in procs_x]) yp = ifnone(self.train.y.processor, [p(ds=se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def process(self): "Process the inner datasets." xp,yp = self.get_processors() for ds,n in zip(self.lists, ['train','valid','test']): ds.process(xp, yp, name=n) #progress_bar clear the outputs so in some case warnings issued during processing disappear. for ds in self.lists: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def databunch(self, path:PathOrStr=None, bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None, device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False, **kwargs)->'DataBunch': "Create an `DataBunch` fro...
<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_state(cls, path:PathOrStr, state:dict): "Create a `LabelLists` with empty sets from the serialized `state`." path = Path(path) train_ds = LabelList.load_state(path, state) valid_ds = LabelList.load_state(path, state) return LabelLists(path, train=train_ds, valid=valid_ds...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_item(self,item): "For inference, will briefly replace the dataset with one that only contains `item`." self.item = self.x.process_one(item) yield None self.item = 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 to_df(self)->None: "Create `pd.DataFrame` containing `items` from `self.x` and `self.y`." return pd.DataFrame(dict(x=self.x._relative_item_paths(), y=[str(o) for o in self.y]))
<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_state(self, **kwargs): "Return the minimal state for export." state = {'x_cls':self.x.__class__, 'x_proc':self.x.processor, 'y_cls':self.y.__class__, 'y_proc':self.y.processor, 'tfms':self.tfms, 'tfm_y':self.tfm_y, 'tfmargs':self.tfmargs} if hasattr(self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def export(self, fn:PathOrStr, **kwargs): "Export the minimal state and save it in `fn` to load an empty version for inference." pickle.dump(self.get_state(**kwargs), open(fn, 'wb'))
<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_empty(cls, path:PathOrStr, fn:PathOrStr): "Load the state in `fn` to create an empty `LabelList` for inference." return cls.load_state(path, pickle.load(open(Path(path)/fn, 'rb')))
<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_state(cls, path:PathOrStr, state:dict) -> 'LabelList': "Create a `LabelList` from `state`." x = state['x_cls']([], path=path, processor=state['x_proc'], ignore_empty=True) y = state['y_cls']([], path=path, processor=state['y_proc'], ignore_empty=True) res = cls(x, y, tfms=state[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def process(self, xp:PreProcessor=None, yp:PreProcessor=None, name:str=None): "Launch the processing on `self.x` and `self.y` with `xp` and `yp`." self.y.process(yp) if getattr(self.y, 'filter_missing_y', False): filt = array([o is None for o in self.y.items]) if filt.sum...
<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(self, tfms:TfmList, tfm_y:bool=None, **kwargs): "Set the `tfms` and `tfm_y` value to be applied to the inputs and targets." _check_kwargs(self.x, tfms, **kwargs) if tfm_y is None: tfm_y = self.tfm_y if tfm_y: _check_kwargs(self.y, tfms, **kwargs) self.tfms, self.tf...
<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_y(self, tfms:TfmList=None, **kwargs): "Set `tfms` to be applied to the targets only." _check_kwargs(self.y, tfms, **kwargs) self.tfm_y=True if tfms is None: self.tfms_y = list(filter(lambda t: t.use_on_y, listify(self.tfms))) self.tfmargs_y = {**self...
<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_env(name): "Return env var value if it's defined and not an empty string, or return Unknown" res = os.environ.get(name,'') return res if len(res) else "Unknown"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pypi_module_version_is_available(module, version): "Check whether module==version is available on pypi" # returns True/False (or None if failed to execute the check) # using a hack that when passing "module==" w/ no version number to pip # it "fails" and returns all the available versions in stderr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def annealing_linear(start:Number, end:Number, pct:float)->Number: "Linearly anneal from `start` to `end` as pct goes from 0.0 to 1.0." return start + pct * (end-start)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def annealing_exp(start:Number, end:Number, pct:float)->Number: "Exponentially anneal from `start` to `end` as pct goes from 0.0 to 1.0." return start * (end/start) ** 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 annealing_cos(start:Number, end:Number, pct:float)->Number: "Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0." cos_out = np.cos(np.pi * pct) + 1 return end + (start-end)/2 * cos_out
<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_annealing_poly(start:Number, end:Number, pct:float, degree:Number)->Number: "Helper function for `anneal_poly`." return end + (start-end) * (1-pct)**degree
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create(cls, opt_func:Union[type,Callable], lr:Union[float,Tuple,List], layer_groups:ModuleList, wd:Floats=0., true_wd:bool=False, bn_wd:bool=True)->optim.Optimizer: "Create an `optim.Optimizer` from `opt_func` with `lr`. Set lr on `layer_groups`." split_params = split_no_wd_params(la...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def step(self)->None: "Set weight decay and step optimizer." # weight decay outside of optimizer step (AdamW) if self.true_wd: for lr,wd,pg1,pg2 in zip(self._lr,self._wd,self.opt.param_groups[::2],self.opt.param_groups[1::2]): for p in pg1['params']: p.data.mul_(1 - w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wd(self, val:float)->None: "Set weight decay." if not self.true_wd: self.set_val('weight_decay', listify(val, self._wd), bn_groups=self.bn_wd) self._wd = listify(val, self._wd)
<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_defaults(self)->None: "Read the values inside the optimizer for the hyper-parameters." self._beta = None if 'lr' in self.opt_keys: self._lr = self.read_val('lr') if 'momentum' in self.opt_keys: self._mom = self.read_val('momentum') if 'alpha' in self.opt_keys: self._beta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_val(self, key:str, val:Any, bn_groups:bool=True)->Any: "Set `val` inside the optimizer dictionary at `key`." if is_tuple(val): val = [(v1,v2) for v1,v2 in zip(*val)] for v,pg1,pg2 in zip(val,self.opt.param_groups[::2],self.opt.param_groups[1::2]): pg1[key] = v 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 read_val(self, key:str) -> Union[List[float],Tuple[List[float],List[float]]]: "Read a hyperparameter `key` in the optimizer dictionary." val = [pg[key] for pg in self.opt.param_groups[::2]] if is_tuple(val[0]): val = [o[0] for o in val], [o[1] for o in val] return val
<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_state(self): "Return the inner state minus the layer groups." return {'opt_state':self.opt.state_dict(), 'lr':self._lr, 'wd':self._wd, 'beta':self._beta, 'mom':self._mom, 'opt_func':self.opt_func, 'true_wd':self.true_wd, 'bn_wd':self.bn_wd}
<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_state(self, minimal:bool=True): "Return the inner state of the `Callback`, `minimal` or not." to_remove = ['exclude', 'not_min'] + getattr(self, 'exclude', []).copy() if minimal: to_remove += getattr(self, 'not_min', []).copy() return {k:v for k,v in self.__dict__.items() if k no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_value(self, val:float)->None: "Add `val` to calculate updated smoothed value." self.n += 1 self.mov_avg = self.beta * self.mov_avg + (1 - self.beta) * val self.smooth = self.mov_avg / (1 - self.beta ** self.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 on_batch_end(self, last_output, last_target, **kwargs): "Update metric computation with `last_output` and `last_target`." if not is_listy(last_target): last_target=[last_target] self.count += last_target[0].size(0) val = self.func(last_output, *last_target) if self.world: ...
<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_epoch_end(self, last_metrics, **kwargs): "Set the final result in `last_metrics`." return add_metrics(last_metrics, self.val/self.count)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def step(self)->Number: "Return next value along annealed schedule." self.n += 1 return self.func(self.start, self.end, self.n/self.n_iter)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def steps(self, *steps_cfg:StartOptEnd): "Build anneal schedule for all of the parameters." return [Scheduler(step, n_iter, func=func) for (step,(n_iter,func)) in zip(steps_cfg, self.phases)]
<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_train_begin(self, n_epochs:int, epoch:int, **kwargs:Any)->None: "Initialize our optimization params based on our annealing schedule." res = {'epoch':self.start_epoch} if self.start_epoch is not None else None self.start_epoch = ifnone(self.start_epoch, epoch) self.tot_epochs = ifn...
<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_batch_end(self, train, **kwargs:Any)->None: "Take one step forward on the annealing schedule for the optim params." if train: if self.idx_s >= len(self.lr_scheds): return {'stop_training': True, 'stop_epoch': True} self.opt.lr = self.lr_scheds[self.idx_s].step() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def basic_critic(in_size:int, n_channels:int, n_features:int=64, n_extra_layers:int=0, **conv_kwargs): "A basic critic for images `n_channels` x `in_size` x `in_size`." layers = [conv_layer(n_channels, n_features, 4, 2, 1, leaky=0.2, norm_type=None, **conv_kwargs)]#norm_type=None? cur_size, cur_ftrs = in_si...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def basic_generator(in_size:int, n_channels:int, noise_sz:int=100, n_features:int=64, n_extra_layers=0, **conv_kwargs): "A basic generator from `noise_sz` to images `n_channels` x `in_size` x `in_size`." cur_size, cur_ftrs = 4, n_features//2 while cur_size < in_size: cur_size *= 2; cur_ftrs *= 2 layers...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def gan_loss_from_func(loss_gen, loss_crit, weights_gen:Tuple[float,float]=None): "Define loss functions for a GAN from `loss_gen` and `loss_crit`." def _loss_G(fake_pred, output, target, weights_gen=weights_gen): ones = fake_pred.new_ones(fake_pred.shape[0]) weights_gen = ifnone(weights_gen, (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 gan_critic(n_channels:int=3, nf:int=128, n_blocks:int=3, p:int=0.15): "Critic to train a `GAN`." layers = [ _conv(n_channels, nf, ks=4, stride=2), nn.Dropout2d(p/2), res_block(nf, dense=True,**_conv_args)] nf *= 2 # after dense block for i in range(n_blocks): layers +...
<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_expand(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor: "Compute accuracy after expanding `y_true` to the size of `y_pred`." if sigmoid: y_pred = y_pred.sigmoid() return ((y_pred>thresh)==y_true[:,None].expand_as(y_pred).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 switch(self, gen_mode:bool=None): "Put the model in generator mode if `gen_mode`, in critic mode otherwise." self.gen_mode = (not self.gen_mode) if gen_mode is None else gen_mode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generator(self, output, target): "Evaluate the `output` with the critic then uses `self.loss_funcG` to combine it with `target`." fake_pred = self.gan_model.critic(output) return self.loss_funcG(fake_pred, target, 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 critic(self, real_pred, input): "Create some `fake_pred` with the generator from `input` and compare them to `real_pred` in `self.loss_funcD`." fake = self.gan_model.generator(input.requires_grad_(False)).requires_grad_(True) fake_pred = self.gan_model.critic(fake) return self.loss_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 on_train_begin(self, **kwargs): "Create the optimizers for the generator and critic if necessary, initialize smootheners." if not getattr(self,'opt_gen',None): self.opt_gen = self.opt.new([nn.Sequential(*flatten_model(self.generator))]) else: self.opt_gen.lr,self.opt_gen.wd = sel...
<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_batch_begin(self, last_input, last_target, **kwargs): "Clamp the weights with `self.clip` if it's not None, return the correct input." if self.clip is not None: for p in self.critic.parameters(): p.data.clamp_(-self.clip, self.clip) return {'last_input':last_input,'last_target...
<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, last_output, **kwargs): "Record `last_loss` in the proper list." last_loss = last_loss.detach().cpu() if self.gen_mode: self.smoothenerG.add_value(last_loss) self.glosses.append(self.smoothenerG.smooth) self.last_gen = la...
<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_epoch_end(self, pbar, epoch, last_metrics, **kwargs): "Put the various losses in the recorder and show a sample image." if not hasattr(self, 'last_gen') or not self.show_img: return data = self.learn.data img = self.last_gen[0] norm = getattr(data,'norm',False) 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 switch(self, gen_mode:bool=None): "Switch the model, if `gen_mode` is provided, in the desired mode." self.gen_mode = (not self.gen_mode) if gen_mode is None else gen_mode self.opt.opt = self.opt_gen.opt if self.gen_mode else self.opt_critic.opt self._set_trainable() self.mod...
<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_batch_end(self, iteration, **kwargs): "Switch the model if necessary." if self.learn.gan_trainer.gen_mode: self.n_g += 1 n_iter,n_in,n_out = self.n_gen,self.n_c,self.n_g else: self.n_c += 1 n_iter,n_in,n_out = self.n_crit,self.n_g,self.n_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 from_learners(cls, learn_gen:Learner, learn_crit:Learner, switcher:Callback=None, weights_gen:Tuple[float,float]=None, **learn_kwargs): "Create a GAN from `learn_gen` and `learn_crit`." losses = gan_loss_from_func(learn_gen.loss_func, learn_crit.loss_func, weights_gen=weights_g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wgan(cls, data:DataBunch, generator:nn.Module, critic:nn.Module, switcher:Callback=None, clip:float=0.01, **learn_kwargs): "Create a WGAN from `data`, `generator` and `critic`." return cls(data, generator, critic, NoopLoss(), WassersteinLoss(), switcher=switcher, clip=clip, **learn_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 on_batch_begin(self, train, **kwargs): "Multiply the current lr if necessary." if not self.learn.gan_trainer.gen_mode and train: self.learn.opt.lr *= self.mult_lr
<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_step_end(self, **kwargs): "Put the LR back to its value if necessary." if not self.learn.gan_trainer.gen_mode: self.learn.opt.lr /= self.mult_lr
<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_sfs_idxs(sizes:Sizes) -> List[int]: "Get the indexes of the layers where the size of the activation changes." feature_szs = [size[-1] for size in sizes] sfs_idxs = list(np.where(np.array(feature_szs[:-1]) != np.array(feature_szs[1:]))[0]) if feature_szs[0] != feature_szs[1]: sfs_idxs = [0] + sf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _url_params(size:str='>400*300', format:str='jpg') -> str: "Build Google Images Search Url params and return them as a string." _fmts = {'jpg':'ift:jpg','gif'...
) if format not in _fmts: raise RuntimeError(f"Unexpected image file format: {format}. Use jpg, gif, png, bmp, svg, webp, or ico.") return "&tbs=" + _img_sizes[size] + "," + _fmts[format]