partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | ItemList._label_from_list | Label `self.items` with `labels`. | fastai/data_block.py | 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`.")
... | 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`.")
... | [
"Label",
"self",
".",
"items",
"with",
"labels",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L257-L265 | [
"def",
"_label_from_list",
"(",
"self",
",",
"labels",
":",
"Iterator",
",",
"label_cls",
":",
"Callable",
"=",
"None",
",",
"from_item_lists",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"->",
"'LabelList'",
":",
"if",
"not",
"from_item_lists... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ItemList.label_from_df | Label `self.items` from the values in `cols` in `self.inner_df`. | fastai/data_block.py | 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... | 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... | [
"Label",
"self",
".",
"items",
"from",
"the",
"values",
"in",
"cols",
"in",
"self",
".",
"inner_df",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L267-L274 | [
"def",
"label_from_df",
"(",
"self",
",",
"cols",
":",
"IntsOrStrs",
"=",
"1",
",",
"label_cls",
":",
"Callable",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"labels",
"=",
"self",
".",
"inner_df",
".",
"iloc",
"[",
":",
",",
"df_names_to_idx",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ItemList.label_const | Label every item with `const`. | fastai/data_block.py | 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) | 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) | [
"Label",
"every",
"item",
"with",
"const",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L276-L278 | [
"def",
"label_const",
"(",
"self",
",",
"const",
":",
"Any",
"=",
"0",
",",
"label_cls",
":",
"Callable",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'LabelList'",
":",
"return",
"self",
".",
"label_from_func",
"(",
"func",
"=",
"lambda",
"o",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ItemList.label_empty | Label every item with an `EmptyLabel`. | fastai/data_block.py | 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) | 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) | [
"Label",
"every",
"item",
"with",
"an",
"EmptyLabel",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L280-L283 | [
"def",
"label_empty",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'label_cls'",
"]",
"=",
"EmptyLabelList",
"return",
"self",
".",
"label_from_func",
"(",
"func",
"=",
"lambda",
"o",
":",
"0.",
",",
"*",
"*",
"kwargs",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ItemList.label_from_func | Apply `func` to every input to get its label. | fastai/data_block.py | 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) | 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) | [
"Apply",
"func",
"to",
"every",
"input",
"to",
"get",
"its",
"label",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L285-L287 | [
"def",
"label_from_func",
"(",
"self",
",",
"func",
":",
"Callable",
",",
"label_cls",
":",
"Callable",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'LabelList'",
":",
"return",
"self",
".",
"_label_from_list",
"(",
"[",
"func",
"(",
"o",
")",
"fo... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ItemList.label_from_folder | Give a label to each filename depending on its folder. | fastai/data_block.py | 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... | 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... | [
"Give",
"a",
"label",
"to",
"each",
"filename",
"depending",
"on",
"its",
"folder",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L289-L292 | [
"def",
"label_from_folder",
"(",
"self",
",",
"label_cls",
":",
"Callable",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'LabelList'",
":",
"return",
"self",
".",
"label_from_func",
"(",
"func",
"=",
"lambda",
"o",
":",
"(",
"o",
".",
"parts",
"if... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ItemList.label_from_re | Apply the re in `pat` to determine the label of every filename. If `full_path`, search in the full name. | fastai/data_block.py | 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) ... | 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) ... | [
"Apply",
"the",
"re",
"in",
"pat",
"to",
"determine",
"the",
"label",
"of",
"every",
"filename",
".",
"If",
"full_path",
"search",
"in",
"the",
"full",
"name",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L294-L302 | [
"def",
"label_from_re",
"(",
"self",
",",
"pat",
":",
"str",
",",
"full_path",
":",
"bool",
"=",
"False",
",",
"label_cls",
":",
"Callable",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'LabelList'",
":",
"pat",
"=",
"re",
".",
"compile",
"(",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | MultiCategoryProcessor.generate_classes | Generate classes from `items` by taking the sorted unique values. | fastai/data_block.py | 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 | 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 | [
"Generate",
"classes",
"from",
"items",
"by",
"taking",
"the",
"sorted",
"unique",
"values",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L388-L394 | [
"def",
"generate_classes",
"(",
"self",
",",
"items",
")",
":",
"classes",
"=",
"set",
"(",
")",
"for",
"c",
"in",
"items",
":",
"classes",
"=",
"classes",
".",
"union",
"(",
"set",
"(",
"c",
")",
")",
"classes",
"=",
"list",
"(",
"classes",
")",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ItemLists.label_from_lists | Use the labels in `train_labels` and `valid_labels` to label the data. `label_cls` will overwrite the default. | fastai/data_block.py | 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)
... | 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)
... | [
"Use",
"the",
"labels",
"in",
"train_labels",
"and",
"valid_labels",
"to",
"label",
"the",
"data",
".",
"label_cls",
"will",
"overwrite",
"the",
"default",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L480-L487 | [
"def",
"label_from_lists",
"(",
"self",
",",
"train_labels",
":",
"Iterator",
",",
"valid_labels",
":",
"Iterator",
",",
"label_cls",
":",
"Callable",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'LabelList'",
":",
"label_cls",
"=",
"self",
".",
"trai... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ItemLists.transform | Set `tfms` to be applied to the xs of the train and validation set. | fastai/data_block.py | 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)."
... | 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)."
... | [
"Set",
"tfms",
"to",
"be",
"applied",
"to",
"the",
"xs",
"of",
"the",
"train",
"and",
"validation",
"set",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L489-L496 | [
"def",
"transform",
"(",
"self",
",",
"tfms",
":",
"Optional",
"[",
"Tuple",
"[",
"TfmList",
",",
"TfmList",
"]",
"]",
"=",
"(",
"None",
",",
"None",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"tfms",
":",
"tfms",
"=",
"(",
"None",
",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ItemLists.transform_y | Set `tfms` to be applied to the ys of the train and validation set. | fastai/data_block.py | 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... | 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... | [
"Set",
"tfms",
"to",
"be",
"applied",
"to",
"the",
"ys",
"of",
"the",
"train",
"and",
"validation",
"set",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L498-L504 | [
"def",
"transform_y",
"(",
"self",
",",
"tfms",
":",
"Optional",
"[",
"Tuple",
"[",
"TfmList",
",",
"TfmList",
"]",
"]",
"=",
"(",
"None",
",",
"None",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"tfms",
":",
"tfms",
"=",
"(",
"None",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelLists.get_processors | Read the default class processors if none have been set. | fastai/data_block.py | 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... | 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... | [
"Read",
"the",
"default",
"class",
"processors",
"if",
"none",
"have",
"been",
"set",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L512-L517 | [
"def",
"get_processors",
"(",
"self",
")",
":",
"procs_x",
",",
"procs_y",
"=",
"listify",
"(",
"self",
".",
"train",
".",
"x",
".",
"_processor",
")",
",",
"listify",
"(",
"self",
".",
"train",
".",
"y",
".",
"_processor",
")",
"xp",
"=",
"ifnone",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelLists.process | Process the inner datasets. | fastai/data_block.py | 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:
... | 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:
... | [
"Process",
"the",
"inner",
"datasets",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L519-L526 | [
"def",
"process",
"(",
"self",
")",
":",
"xp",
",",
"yp",
"=",
"self",
".",
"get_processors",
"(",
")",
"for",
"ds",
",",
"n",
"in",
"zip",
"(",
"self",
".",
"lists",
",",
"[",
"'train'",
",",
"'valid'",
",",
"'test'",
"]",
")",
":",
"ds",
".",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelLists.databunch | Create an `DataBunch` from self, `path` will override `self.path`, `kwargs` are passed to `DataBunch.create`. | fastai/data_block.py | 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... | 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... | [
"Create",
"an",
"DataBunch",
"from",
"self",
"path",
"will",
"override",
"self",
".",
"path",
"kwargs",
"are",
"passed",
"to",
"DataBunch",
".",
"create",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L532-L543 | [
"def",
"databunch",
"(",
"self",
",",
"path",
":",
"PathOrStr",
"=",
"None",
",",
"bs",
":",
"int",
"=",
"64",
",",
"val_bs",
":",
"int",
"=",
"None",
",",
"num_workers",
":",
"int",
"=",
"defaults",
".",
"cpus",
",",
"dl_tfms",
":",
"Optional",
"[... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelLists.load_state | Create a `LabelLists` with empty sets from the serialized `state`. | fastai/data_block.py | 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... | 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... | [
"Create",
"a",
"LabelLists",
"with",
"empty",
"sets",
"from",
"the",
"serialized",
"state",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L562-L567 | [
"def",
"load_state",
"(",
"cls",
",",
"path",
":",
"PathOrStr",
",",
"state",
":",
"dict",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"train_ds",
"=",
"LabelList",
".",
"load_state",
"(",
"path",
",",
"state",
")",
"valid_ds",
"=",
"LabelList",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelLists.load_empty | Create a `LabelLists` with empty sets from the serialized file in `path/fn`. | fastai/data_block.py | def load_empty(cls, path:PathOrStr, fn:PathOrStr='export.pkl'):
"Create a `LabelLists` with empty sets from the serialized file in `path/fn`."
path = Path(path)
state = torch.load(open(path/fn, 'rb'))
return LabelLists.load_state(path, state) | def load_empty(cls, path:PathOrStr, fn:PathOrStr='export.pkl'):
"Create a `LabelLists` with empty sets from the serialized file in `path/fn`."
path = Path(path)
state = torch.load(open(path/fn, 'rb'))
return LabelLists.load_state(path, state) | [
"Create",
"a",
"LabelLists",
"with",
"empty",
"sets",
"from",
"the",
"serialized",
"file",
"in",
"path",
"/",
"fn",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L570-L574 | [
"def",
"load_empty",
"(",
"cls",
",",
"path",
":",
"PathOrStr",
",",
"fn",
":",
"PathOrStr",
"=",
"'export.pkl'",
")",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"state",
"=",
"torch",
".",
"load",
"(",
"open",
"(",
"path",
"/",
"fn",
",",
"'rb'",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelList.set_item | For inference, will briefly replace the dataset with one that only contains `item`. | fastai/data_block.py | 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 | 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 | [
"For",
"inference",
"will",
"briefly",
"replace",
"the",
"dataset",
"with",
"one",
"that",
"only",
"contains",
"item",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L596-L600 | [
"def",
"set_item",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"item",
"=",
"self",
".",
"x",
".",
"process_one",
"(",
"item",
")",
"yield",
"None",
"self",
".",
"item",
"=",
"None"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelList.to_df | Create `pd.DataFrame` containing `items` from `self.x` and `self.y`. | fastai/data_block.py | 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])) | 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])) | [
"Create",
"pd",
".",
"DataFrame",
"containing",
"items",
"from",
"self",
".",
"x",
"and",
"self",
".",
"y",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L646-L648 | [
"def",
"to_df",
"(",
"self",
")",
"->",
"None",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"dict",
"(",
"x",
"=",
"self",
".",
"x",
".",
"_relative_item_paths",
"(",
")",
",",
"y",
"=",
"[",
"str",
"(",
"o",
")",
"for",
"o",
"in",
"self",
".",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelList.to_csv | Save `self.to_df()` to a CSV file in `self.path`/`dest`. | fastai/data_block.py | def to_csv(self, dest:str)->None:
"Save `self.to_df()` to a CSV file in `self.path`/`dest`."
self.to_df().to_csv(self.path/dest, index=False) | def to_csv(self, dest:str)->None:
"Save `self.to_df()` to a CSV file in `self.path`/`dest`."
self.to_df().to_csv(self.path/dest, index=False) | [
"Save",
"self",
".",
"to_df",
"()",
"to",
"a",
"CSV",
"file",
"in",
"self",
".",
"path",
"/",
"dest",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L650-L652 | [
"def",
"to_csv",
"(",
"self",
",",
"dest",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"to_df",
"(",
")",
".",
"to_csv",
"(",
"self",
".",
"path",
"/",
"dest",
",",
"index",
"=",
"False",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelList.get_state | Return the minimal state for export. | fastai/data_block.py | 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... | 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... | [
"Return",
"the",
"minimal",
"state",
"for",
"export",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L654-L661 | [
"def",
"get_state",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"state",
"=",
"{",
"'x_cls'",
":",
"self",
".",
"x",
".",
"__class__",
",",
"'x_proc'",
":",
"self",
".",
"x",
".",
"processor",
",",
"'y_cls'",
":",
"self",
".",
"y",
".",
"__cl... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelList.export | Export the minimal state and save it in `fn` to load an empty version for inference. | fastai/data_block.py | 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')) | 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')) | [
"Export",
"the",
"minimal",
"state",
"and",
"save",
"it",
"in",
"fn",
"to",
"load",
"an",
"empty",
"version",
"for",
"inference",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L663-L665 | [
"def",
"export",
"(",
"self",
",",
"fn",
":",
"PathOrStr",
",",
"*",
"*",
"kwargs",
")",
":",
"pickle",
".",
"dump",
"(",
"self",
".",
"get_state",
"(",
"*",
"*",
"kwargs",
")",
",",
"open",
"(",
"fn",
",",
"'wb'",
")",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelList.load_empty | Load the state in `fn` to create an empty `LabelList` for inference. | fastai/data_block.py | 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'))) | 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'))) | [
"Load",
"the",
"state",
"in",
"fn",
"to",
"create",
"an",
"empty",
"LabelList",
"for",
"inference",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L668-L670 | [
"def",
"load_empty",
"(",
"cls",
",",
"path",
":",
"PathOrStr",
",",
"fn",
":",
"PathOrStr",
")",
":",
"return",
"cls",
".",
"load_state",
"(",
"path",
",",
"pickle",
".",
"load",
"(",
"open",
"(",
"Path",
"(",
"path",
")",
"/",
"fn",
",",
"'rb'",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelList.load_state | Create a `LabelList` from `state`. | fastai/data_block.py | 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[... | 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[... | [
"Create",
"a",
"LabelList",
"from",
"state",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L673-L681 | [
"def",
"load_state",
"(",
"cls",
",",
"path",
":",
"PathOrStr",
",",
"state",
":",
"dict",
")",
"->",
"'LabelList'",
":",
"x",
"=",
"state",
"[",
"'x_cls'",
"]",
"(",
"[",
"]",
",",
"path",
"=",
"path",
",",
"processor",
"=",
"state",
"[",
"'x_proc... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelList.process | Launch the processing on `self.x` and `self.y` with `xp` and `yp`. | fastai/data_block.py | 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... | 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... | [
"Launch",
"the",
"processing",
"on",
"self",
".",
"x",
"and",
"self",
".",
"y",
"with",
"xp",
"and",
"yp",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L683-L700 | [
"def",
"process",
"(",
"self",
",",
"xp",
":",
"PreProcessor",
"=",
"None",
",",
"yp",
":",
"PreProcessor",
"=",
"None",
",",
"name",
":",
"str",
"=",
"None",
")",
":",
"self",
".",
"y",
".",
"process",
"(",
"yp",
")",
"if",
"getattr",
"(",
"self... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelList.transform | Set the `tfms` and `tfm_y` value to be applied to the inputs and targets. | fastai/data_block.py | 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... | 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... | [
"Set",
"the",
"tfms",
"and",
"tfm_y",
"value",
"to",
"be",
"applied",
"to",
"the",
"inputs",
"and",
"targets",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L707-L715 | [
"def",
"transform",
"(",
"self",
",",
"tfms",
":",
"TfmList",
",",
"tfm_y",
":",
"bool",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_check_kwargs",
"(",
"self",
".",
"x",
",",
"tfms",
",",
"*",
"*",
"kwargs",
")",
"if",
"tfm_y",
"is",
"None... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LabelList.transform_y | Set `tfms` to be applied to the targets only. | fastai/data_block.py | 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... | 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... | [
"Set",
"tfms",
"to",
"be",
"applied",
"to",
"the",
"targets",
"only",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L717-L727 | [
"def",
"transform_y",
"(",
"self",
",",
"tfms",
":",
"TfmList",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_check_kwargs",
"(",
"self",
".",
"y",
",",
"tfms",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"tfm_y",
"=",
"True",
"if",
"tfms",
"i... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | MixedItemList.new | Create a new `ItemList` from `items`, keeping the same attributes. | fastai/data_block.py | def new(self, item_lists, processor:PreProcessor=None, **kwargs)->'ItemList':
"Create a new `ItemList` from `items`, keeping the same attributes."
processor = ifnone(processor, self.processor)
copy_d = {o:getattr(self,o) for o in self.copy_new}
kwargs = {**copy_d, **kwargs}
retur... | def new(self, item_lists, processor:PreProcessor=None, **kwargs)->'ItemList':
"Create a new `ItemList` from `items`, keeping the same attributes."
processor = ifnone(processor, self.processor)
copy_d = {o:getattr(self,o) for o in self.copy_new}
kwargs = {**copy_d, **kwargs}
retur... | [
"Create",
"a",
"new",
"ItemList",
"from",
"items",
"keeping",
"the",
"same",
"attributes",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/data_block.py#L781-L786 | [
"def",
"new",
"(",
"self",
",",
"item_lists",
",",
"processor",
":",
"PreProcessor",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'ItemList'",
":",
"processor",
"=",
"ifnone",
"(",
"processor",
",",
"self",
".",
"processor",
")",
"copy_d",
"=",
"{... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | parse_docstring | Parse the docstring into its components.
:return: a dictionary of form
{
"short_description": ...,
"long_description": ...,
"params": [{"name": ..., "doc": ...}, ...],
"vals": [{"name": ..., "doc": ...}, ...],
"... | fastai/gen_doc/docstrings.py | def parse_docstring(docstring):
"""Parse the docstring into its components.
:return: a dictionary of form
{
"short_description": ...,
"long_description": ...,
"params": [{"name": ..., "doc": ...}, ...],
"vals": [{"name": ...,... | def parse_docstring(docstring):
"""Parse the docstring into its components.
:return: a dictionary of form
{
"short_description": ...,
"long_description": ...,
"params": [{"name": ..., "doc": ...}, ...],
"vals": [{"name": ...,... | [
"Parse",
"the",
"docstring",
"into",
"its",
"components",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/docstrings.py#L67-L115 | [
"def",
"parse_docstring",
"(",
"docstring",
")",
":",
"short_description",
"=",
"long_description",
"=",
"return_str",
"=",
"\"\"",
"args",
"=",
"[",
"]",
"if",
"docstring",
":",
"docstring",
"=",
"trim",
"(",
"docstring",
".",
"lstrip",
"(",
"\"\\n\"",
")",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | get_env | Return env var value if it's defined and not an empty string, or return Unknown | fastai/utils/collect_env.py | 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" | 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" | [
"Return",
"env",
"var",
"value",
"if",
"it",
"s",
"defined",
"and",
"not",
"an",
"empty",
"string",
"or",
"return",
"Unknown"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/utils/collect_env.py#L11-L14 | [
"def",
"get_env",
"(",
"name",
")",
":",
"res",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
",",
"''",
")",
"return",
"res",
"if",
"len",
"(",
"res",
")",
"else",
"\"Unknown\""
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | show_install | Print user's setup information | fastai/utils/collect_env.py | def show_install(show_nvidia_smi:bool=False):
"Print user's setup information"
import platform, fastai.version
rep = []
opt_mods = []
rep.append(["=== Software ===", None])
rep.append(["python", platform.python_version()])
rep.append(["fastai", fastai.__version__])
rep.append(["fastpr... | def show_install(show_nvidia_smi:bool=False):
"Print user's setup information"
import platform, fastai.version
rep = []
opt_mods = []
rep.append(["=== Software ===", None])
rep.append(["python", platform.python_version()])
rep.append(["fastai", fastai.__version__])
rep.append(["fastpr... | [
"Print",
"user",
"s",
"setup",
"information"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/utils/collect_env.py#L16-L127 | [
"def",
"show_install",
"(",
"show_nvidia_smi",
":",
"bool",
"=",
"False",
")",
":",
"import",
"platform",
",",
"fastai",
".",
"version",
"rep",
"=",
"[",
"]",
"opt_mods",
"=",
"[",
"]",
"rep",
".",
"append",
"(",
"[",
"\"=== Software ===\"",
",",
"None",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | pypi_module_version_is_available | Check whether module==version is available on pypi | fastai/utils/collect_env.py | 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... | 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... | [
"Check",
"whether",
"module",
"==",
"version",
"is",
"available",
"on",
"pypi"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/utils/collect_env.py#L129-L148 | [
"def",
"pypi_module_version_is_available",
"(",
"module",
",",
"version",
")",
":",
"# 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",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | check_perf | Suggest how to improve the setup to speed things up | fastai/utils/collect_env.py | def check_perf():
"Suggest how to improve the setup to speed things up"
from PIL import features, Image
from packaging import version
print("Running performance checks.")
# libjpeg_turbo check
print("\n*** libjpeg-turbo status")
if version.parse(Image.PILLOW_VERSION) >= version.parse("5.3... | def check_perf():
"Suggest how to improve the setup to speed things up"
from PIL import features, Image
from packaging import version
print("Running performance checks.")
# libjpeg_turbo check
print("\n*** libjpeg-turbo status")
if version.parse(Image.PILLOW_VERSION) >= version.parse("5.3... | [
"Suggest",
"how",
"to",
"improve",
"the",
"setup",
"to",
"speed",
"things",
"up"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/utils/collect_env.py#L150-L204 | [
"def",
"check_perf",
"(",
")",
":",
"from",
"PIL",
"import",
"features",
",",
"Image",
"from",
"packaging",
"import",
"version",
"print",
"(",
"\"Running performance checks.\"",
")",
"# libjpeg_turbo check",
"print",
"(",
"\"\\n*** libjpeg-turbo status\"",
")",
"if",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | annealing_linear | Linearly anneal from `start` to `end` as pct goes from 0.0 to 1.0. | fastai/callback.py | 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) | 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) | [
"Linearly",
"anneal",
"from",
"start",
"to",
"end",
"as",
"pct",
"goes",
"from",
"0",
".",
"0",
"to",
"1",
".",
"0",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L358-L360 | [
"def",
"annealing_linear",
"(",
"start",
":",
"Number",
",",
"end",
":",
"Number",
",",
"pct",
":",
"float",
")",
"->",
"Number",
":",
"return",
"start",
"+",
"pct",
"*",
"(",
"end",
"-",
"start",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | annealing_exp | Exponentially anneal from `start` to `end` as pct goes from 0.0 to 1.0. | fastai/callback.py | 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 | 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 | [
"Exponentially",
"anneal",
"from",
"start",
"to",
"end",
"as",
"pct",
"goes",
"from",
"0",
".",
"0",
"to",
"1",
".",
"0",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L361-L363 | [
"def",
"annealing_exp",
"(",
"start",
":",
"Number",
",",
"end",
":",
"Number",
",",
"pct",
":",
"float",
")",
"->",
"Number",
":",
"return",
"start",
"*",
"(",
"end",
"/",
"start",
")",
"**",
"pct"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | annealing_cos | Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0. | fastai/callback.py | 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 | 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 | [
"Cosine",
"anneal",
"from",
"start",
"to",
"end",
"as",
"pct",
"goes",
"from",
"0",
".",
"0",
"to",
"1",
".",
"0",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L364-L367 | [
"def",
"annealing_cos",
"(",
"start",
":",
"Number",
",",
"end",
":",
"Number",
",",
"pct",
":",
"float",
")",
"->",
"Number",
":",
"cos_out",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"pi",
"*",
"pct",
")",
"+",
"1",
"return",
"end",
"+",
"(",
"s... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | do_annealing_poly | Helper function for `anneal_poly`. | fastai/callback.py | 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 | 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 | [
"Helper",
"function",
"for",
"anneal_poly",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L369-L371 | [
"def",
"do_annealing_poly",
"(",
"start",
":",
"Number",
",",
"end",
":",
"Number",
",",
"pct",
":",
"float",
",",
"degree",
":",
"Number",
")",
"->",
"Number",
":",
"return",
"end",
"+",
"(",
"start",
"-",
"end",
")",
"*",
"(",
"1",
"-",
"pct",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OptimWrapper.create | Create an `optim.Optimizer` from `opt_func` with `lr`. Set lr on `layer_groups`. | fastai/callback.py | 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... | 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... | [
"Create",
"an",
"optim",
".",
"Optimizer",
"from",
"opt_func",
"with",
"lr",
".",
"Set",
"lr",
"on",
"layer_groups",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L20-L27 | [
"def",
"create",
"(",
"cls",
",",
"opt_func",
":",
"Union",
"[",
"type",
",",
"Callable",
"]",
",",
"lr",
":",
"Union",
"[",
"float",
",",
"Tuple",
",",
"List",
"]",
",",
"layer_groups",
":",
"ModuleList",
",",
"wd",
":",
"Floats",
"=",
"0.",
",",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OptimWrapper.new | Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters. | fastai/callback.py | def new(self, layer_groups:Collection[nn.Module], split_no_wd:bool=True):
"Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters."
opt_func = getattr(self, 'opt_func', self.opt.__class__)
res = self.create(opt_func, self.lr, layer_groups, wd=self.wd, t... | def new(self, layer_groups:Collection[nn.Module], split_no_wd:bool=True):
"Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters."
opt_func = getattr(self, 'opt_func', self.opt.__class__)
res = self.create(opt_func, self.lr, layer_groups, wd=self.wd, t... | [
"Create",
"a",
"new",
"OptimWrapper",
"from",
"self",
"with",
"another",
"layer_groups",
"but",
"the",
"same",
"hyper",
"-",
"parameters",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L29-L34 | [
"def",
"new",
"(",
"self",
",",
"layer_groups",
":",
"Collection",
"[",
"nn",
".",
"Module",
"]",
",",
"split_no_wd",
":",
"bool",
"=",
"True",
")",
":",
"opt_func",
"=",
"getattr",
"(",
"self",
",",
"'opt_func'",
",",
"self",
".",
"opt",
".",
"__cla... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OptimWrapper.new_with_params | Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters. | fastai/callback.py | def new_with_params(self, param_groups:Collection[Collection[nn.Parameter]]):
"Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters."
opt_func = getattr(self, 'opt_func', self.opt.__class__)
opt = opt_func([{'params': p, 'lr':0} for p in param_groups]... | def new_with_params(self, param_groups:Collection[Collection[nn.Parameter]]):
"Create a new `OptimWrapper` from `self` with another `layer_groups` but the same hyper-parameters."
opt_func = getattr(self, 'opt_func', self.opt.__class__)
opt = opt_func([{'params': p, 'lr':0} for p in param_groups]... | [
"Create",
"a",
"new",
"OptimWrapper",
"from",
"self",
"with",
"another",
"layer_groups",
"but",
"the",
"same",
"hyper",
"-",
"parameters",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L36-L42 | [
"def",
"new_with_params",
"(",
"self",
",",
"param_groups",
":",
"Collection",
"[",
"Collection",
"[",
"nn",
".",
"Parameter",
"]",
"]",
")",
":",
"opt_func",
"=",
"getattr",
"(",
"self",
",",
"'opt_func'",
",",
"self",
".",
"opt",
".",
"__class__",
")",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OptimWrapper.step | Set weight decay and step optimizer. | fastai/callback.py | 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... | 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... | [
"Set",
"weight",
"decay",
"and",
"step",
"optimizer",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L48-L57 | [
"def",
"step",
"(",
"self",
")",
"->",
"None",
":",
"# weight decay outside of optimizer step (AdamW)",
"if",
"self",
".",
"true_wd",
":",
"for",
"lr",
",",
"wd",
",",
"pg1",
",",
"pg2",
"in",
"zip",
"(",
"self",
".",
"_lr",
",",
"self",
".",
"_wd",
",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OptimWrapper.beta | Set beta (or alpha as makes sense for given optimizer). | fastai/callback.py | def beta(self, val:float)->None:
"Set beta (or alpha as makes sense for given optimizer)."
if val is None: return
if 'betas' in self.opt_keys: self.set_val('betas', (self._mom, listify(val, self._beta)))
elif 'alpha' in self.opt_keys: self.set_val('alpha', listify(val, self._beta))
... | def beta(self, val:float)->None:
"Set beta (or alpha as makes sense for given optimizer)."
if val is None: return
if 'betas' in self.opt_keys: self.set_val('betas', (self._mom, listify(val, self._beta)))
elif 'alpha' in self.opt_keys: self.set_val('alpha', listify(val, self._beta))
... | [
"Set",
"beta",
"(",
"or",
"alpha",
"as",
"makes",
"sense",
"for",
"given",
"optimizer",
")",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L94-L99 | [
"def",
"beta",
"(",
"self",
",",
"val",
":",
"float",
")",
"->",
"None",
":",
"if",
"val",
"is",
"None",
":",
"return",
"if",
"'betas'",
"in",
"self",
".",
"opt_keys",
":",
"self",
".",
"set_val",
"(",
"'betas'",
",",
"(",
"self",
".",
"_mom",
",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OptimWrapper.wd | Set weight decay. | fastai/callback.py | 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) | 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) | [
"Set",
"weight",
"decay",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L104-L107 | [
"def",
"wd",
"(",
"self",
",",
"val",
":",
"float",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"true_wd",
":",
"self",
".",
"set_val",
"(",
"'weight_decay'",
",",
"listify",
"(",
"val",
",",
"self",
".",
"_wd",
")",
",",
"bn_groups",
"=",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OptimWrapper.read_defaults | Read the values inside the optimizer for the hyper-parameters. | fastai/callback.py | 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... | 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... | [
"Read",
"the",
"values",
"inside",
"the",
"optimizer",
"for",
"the",
"hyper",
"-",
"parameters",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L110-L120 | [
"def",
"read_defaults",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_beta",
"=",
"None",
"if",
"'lr'",
"in",
"self",
".",
"opt_keys",
":",
"self",
".",
"_lr",
"=",
"self",
".",
"read_val",
"(",
"'lr'",
")",
"if",
"'momentum'",
"in",
"self",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OptimWrapper.set_val | Set `val` inside the optimizer dictionary at `key`. | fastai/callback.py | 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 ... | 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 ... | [
"Set",
"val",
"inside",
"the",
"optimizer",
"dictionary",
"at",
"key",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L132-L138 | [
"def",
"set_val",
"(",
"self",
",",
"key",
":",
"str",
",",
"val",
":",
"Any",
",",
"bn_groups",
":",
"bool",
"=",
"True",
")",
"->",
"Any",
":",
"if",
"is_tuple",
"(",
"val",
")",
":",
"val",
"=",
"[",
"(",
"v1",
",",
"v2",
")",
"for",
"v1",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OptimWrapper.read_val | Read a hyperparameter `key` in the optimizer dictionary. | fastai/callback.py | 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 | 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 | [
"Read",
"a",
"hyperparameter",
"key",
"in",
"the",
"optimizer",
"dictionary",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L140-L144 | [
"def",
"read_val",
"(",
"self",
",",
"key",
":",
"str",
")",
"->",
"Union",
"[",
"List",
"[",
"float",
"]",
",",
"Tuple",
"[",
"List",
"[",
"float",
"]",
",",
"List",
"[",
"float",
"]",
"]",
"]",
":",
"val",
"=",
"[",
"pg",
"[",
"key",
"]",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OptimWrapper.get_state | Return the inner state minus the layer groups. | fastai/callback.py | 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} | 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} | [
"Return",
"the",
"inner",
"state",
"minus",
"the",
"layer",
"groups",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L146-L149 | [
"def",
"get_state",
"(",
"self",
")",
":",
"return",
"{",
"'opt_state'",
":",
"self",
".",
"opt",
".",
"state_dict",
"(",
")",
",",
"'lr'",
":",
"self",
".",
"_lr",
",",
"'wd'",
":",
"self",
".",
"_wd",
",",
"'beta'",
":",
"self",
".",
"_beta",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | Callback.get_state | Return the inner state of the `Callback`, `minimal` or not. | fastai/callback.py | 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... | 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... | [
"Return",
"the",
"inner",
"state",
"of",
"the",
"Callback",
"minimal",
"or",
"not",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L196-L200 | [
"def",
"get_state",
"(",
"self",
",",
"minimal",
":",
"bool",
"=",
"True",
")",
":",
"to_remove",
"=",
"[",
"'exclude'",
",",
"'not_min'",
"]",
"+",
"getattr",
"(",
"self",
",",
"'exclude'",
",",
"[",
"]",
")",
".",
"copy",
"(",
")",
"if",
"minimal... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | SmoothenValue.add_value | Add `val` to calculate updated smoothed value. | fastai/callback.py | 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) | 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) | [
"Add",
"val",
"to",
"calculate",
"updated",
"smoothed",
"value",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L213-L217 | [
"def",
"add_value",
"(",
"self",
",",
"val",
":",
"float",
")",
"->",
"None",
":",
"self",
".",
"n",
"+=",
"1",
"self",
".",
"mov_avg",
"=",
"self",
".",
"beta",
"*",
"self",
".",
"mov_avg",
"+",
"(",
"1",
"-",
"self",
".",
"beta",
")",
"*",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | AverageMetric.on_batch_end | Update metric computation with `last_output` and `last_target`. | fastai/callback.py | 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:
... | 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:
... | [
"Update",
"metric",
"computation",
"with",
"last_output",
"and",
"last_target",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L340-L349 | [
"def",
"on_batch_end",
"(",
"self",
",",
"last_output",
",",
"last_target",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"is_listy",
"(",
"last_target",
")",
":",
"last_target",
"=",
"[",
"last_target",
"]",
"self",
".",
"count",
"+=",
"last_target",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | AverageMetric.on_epoch_end | Set the final result in `last_metrics`. | fastai/callback.py | def on_epoch_end(self, last_metrics, **kwargs):
"Set the final result in `last_metrics`."
return add_metrics(last_metrics, self.val/self.count) | def on_epoch_end(self, last_metrics, **kwargs):
"Set the final result in `last_metrics`."
return add_metrics(last_metrics, self.val/self.count) | [
"Set",
"the",
"final",
"result",
"in",
"last_metrics",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L351-L353 | [
"def",
"on_epoch_end",
"(",
"self",
",",
"last_metrics",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"add_metrics",
"(",
"last_metrics",
",",
"self",
".",
"val",
"/",
"self",
".",
"count",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | Scheduler.step | Return next value along annealed schedule. | fastai/callback.py | 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) | 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) | [
"Return",
"next",
"value",
"along",
"annealed",
"schedule",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callback.py#L387-L390 | [
"def",
"step",
"(",
"self",
")",
"->",
"Number",
":",
"self",
".",
"n",
"+=",
"1",
"return",
"self",
".",
"func",
"(",
"self",
".",
"start",
",",
"self",
".",
"end",
",",
"self",
".",
"n",
"/",
"self",
".",
"n_iter",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OneCycleScheduler.steps | Build anneal schedule for all of the parameters. | fastai/callbacks/one_cycle.py | 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)] | 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)] | [
"Build",
"anneal",
"schedule",
"for",
"all",
"of",
"the",
"parameters",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/one_cycle.py#L19-L22 | [
"def",
"steps",
"(",
"self",
",",
"*",
"steps_cfg",
":",
"StartOptEnd",
")",
":",
"return",
"[",
"Scheduler",
"(",
"step",
",",
"n_iter",
",",
"func",
"=",
"func",
")",
"for",
"(",
"step",
",",
"(",
"n_iter",
",",
"func",
")",
")",
"in",
"zip",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OneCycleScheduler.on_train_begin | Initialize our optimization params based on our annealing schedule. | fastai/callbacks/one_cycle.py | 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... | 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... | [
"Initialize",
"our",
"optimization",
"params",
"based",
"on",
"our",
"annealing",
"schedule",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/one_cycle.py#L24-L39 | [
"def",
"on_train_begin",
"(",
"self",
",",
"n_epochs",
":",
"int",
",",
"epoch",
":",
"int",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"res",
"=",
"{",
"'epoch'",
":",
"self",
".",
"start_epoch",
"}",
"if",
"self",
".",
"start_ep... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | OneCycleScheduler.on_batch_end | Take one step forward on the annealing schedule for the optim params. | fastai/callbacks/one_cycle.py | 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()
... | 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()
... | [
"Take",
"one",
"step",
"forward",
"on",
"the",
"annealing",
"schedule",
"for",
"the",
"optim",
"params",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/one_cycle.py#L45-L54 | [
"def",
"on_batch_end",
"(",
"self",
",",
"train",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"if",
"train",
":",
"if",
"self",
".",
"idx_s",
">=",
"len",
"(",
"self",
".",
"lr_scheds",
")",
":",
"return",
"{",
"'stop_training'",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | main | Distributed training of Imagenette.
Fastest multi-gpu speed is if you run with: python -m fastai.launch | examples/train_imagenette_adv.py | def main(
gpu:Param("GPU to run on", str)=None,
lr: Param("Learning rate", float)=1e-3,
size: Param("Size (px: 128,192,224)", int)=128,
debias_mom: Param("Debias statistics", bool)=False,
debias_sqr: Param("Debias statistics", bool)=False,
opt: Param("Optimizer: 'adam','g... | def main(
gpu:Param("GPU to run on", str)=None,
lr: Param("Learning rate", float)=1e-3,
size: Param("Size (px: 128,192,224)", int)=128,
debias_mom: Param("Debias statistics", bool)=False,
debias_sqr: Param("Debias statistics", bool)=False,
opt: Param("Optimizer: 'adam','g... | [
"Distributed",
"training",
"of",
"Imagenette",
".",
"Fastest",
"multi",
"-",
"gpu",
"speed",
"is",
"if",
"you",
"run",
"with",
":",
"python",
"-",
"m",
"fastai",
".",
"launch"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/examples/train_imagenette_adv.py#L75-L115 | [
"def",
"main",
"(",
"gpu",
":",
"Param",
"(",
"\"GPU to run on\"",
",",
"str",
")",
"=",
"None",
",",
"lr",
":",
"Param",
"(",
"\"Learning rate\"",
",",
"float",
")",
"=",
"1e-3",
",",
"size",
":",
"Param",
"(",
"\"Size (px: 128,192,224)\"",
",",
"int",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | basic_critic | A basic critic for images `n_channels` x `in_size` x `in_size`. | fastai/vision/gan.py | 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... | 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... | [
"A",
"basic",
"critic",
"for",
"images",
"n_channels",
"x",
"in_size",
"x",
"in_size",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L17-L26 | [
"def",
"basic_critic",
"(",
"in_size",
":",
"int",
",",
"n_channels",
":",
"int",
",",
"n_features",
":",
"int",
"=",
"64",
",",
"n_extra_layers",
":",
"int",
"=",
"0",
",",
"*",
"*",
"conv_kwargs",
")",
":",
"layers",
"=",
"[",
"conv_layer",
"(",
"n... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | basic_generator | A basic generator from `noise_sz` to images `n_channels` x `in_size` x `in_size`. | fastai/vision/gan.py | 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... | 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... | [
"A",
"basic",
"generator",
"from",
"noise_sz",
"to",
"images",
"n_channels",
"x",
"in_size",
"x",
"in_size",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L28-L39 | [
"def",
"basic_generator",
"(",
"in_size",
":",
"int",
",",
"n_channels",
":",
"int",
",",
"noise_sz",
":",
"int",
"=",
"100",
",",
"n_features",
":",
"int",
"=",
"64",
",",
"n_extra_layers",
"=",
"0",
",",
"*",
"*",
"conv_kwargs",
")",
":",
"cur_size",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | gan_loss_from_func | Define loss functions for a GAN from `loss_gen` and `loss_crit`. | fastai/vision/gan.py | 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... | 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... | [
"Define",
"loss",
"functions",
"for",
"a",
"GAN",
"from",
"loss_gen",
"and",
"loss_crit",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L191-L203 | [
"def",
"gan_loss_from_func",
"(",
"loss_gen",
",",
"loss_crit",
",",
"weights_gen",
":",
"Tuple",
"[",
"float",
",",
"float",
"]",
"=",
"None",
")",
":",
"def",
"_loss_G",
"(",
"fake_pred",
",",
"output",
",",
"target",
",",
"weights_gen",
"=",
"weights_ge... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | gan_critic | Critic to train a `GAN`. | fastai/vision/gan.py | 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 +... | 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 +... | [
"Critic",
"to",
"train",
"a",
"GAN",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L261-L276 | [
"def",
"gan_critic",
"(",
"n_channels",
":",
"int",
"=",
"3",
",",
"nf",
":",
"int",
"=",
"128",
",",
"n_blocks",
":",
"int",
"=",
"3",
",",
"p",
":",
"int",
"=",
"0.15",
")",
":",
"layers",
"=",
"[",
"_conv",
"(",
"n_channels",
",",
"nf",
",",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | accuracy_thresh_expand | Compute accuracy after expanding `y_true` to the size of `y_pred`. | fastai/vision/gan.py | 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() | 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() | [
"Compute",
"accuracy",
"after",
"expanding",
"y_true",
"to",
"the",
"size",
"of",
"y_pred",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L301-L304 | [
"def",
"accuracy_thresh_expand",
"(",
"y_pred",
":",
"Tensor",
",",
"y_true",
":",
"Tensor",
",",
"thresh",
":",
"float",
"=",
"0.5",
",",
"sigmoid",
":",
"bool",
"=",
"True",
")",
"->",
"Rank0Tensor",
":",
"if",
"sigmoid",
":",
"y_pred",
"=",
"y_pred",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANModule.switch | Put the model in generator mode if `gen_mode`, in critic mode otherwise. | fastai/vision/gan.py | 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 | 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 | [
"Put",
"the",
"model",
"in",
"generator",
"mode",
"if",
"gen_mode",
"in",
"critic",
"mode",
"otherwise",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L51-L53 | [
"def",
"switch",
"(",
"self",
",",
"gen_mode",
":",
"bool",
"=",
"None",
")",
":",
"self",
".",
"gen_mode",
"=",
"(",
"not",
"self",
".",
"gen_mode",
")",
"if",
"gen_mode",
"is",
"None",
"else",
"gen_mode"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANLoss.generator | Evaluate the `output` with the critic then uses `self.loss_funcG` to combine it with `target`. | fastai/vision/gan.py | 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) | 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) | [
"Evaluate",
"the",
"output",
"with",
"the",
"critic",
"then",
"uses",
"self",
".",
"loss_funcG",
"to",
"combine",
"it",
"with",
"target",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L61-L64 | [
"def",
"generator",
"(",
"self",
",",
"output",
",",
"target",
")",
":",
"fake_pred",
"=",
"self",
".",
"gan_model",
".",
"critic",
"(",
"output",
")",
"return",
"self",
".",
"loss_funcG",
"(",
"fake_pred",
",",
"target",
",",
"output",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANLoss.critic | Create some `fake_pred` with the generator from `input` and compare them to `real_pred` in `self.loss_funcD`. | fastai/vision/gan.py | 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... | 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... | [
"Create",
"some",
"fake_pred",
"with",
"the",
"generator",
"from",
"input",
"and",
"compare",
"them",
"to",
"real_pred",
"in",
"self",
".",
"loss_funcD",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L66-L70 | [
"def",
"critic",
"(",
"self",
",",
"real_pred",
",",
"input",
")",
":",
"fake",
"=",
"self",
".",
"gan_model",
".",
"generator",
"(",
"input",
".",
"requires_grad_",
"(",
"False",
")",
")",
".",
"requires_grad_",
"(",
"True",
")",
"fake_pred",
"=",
"se... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANTrainer.on_train_begin | Create the optimizers for the generator and critic if necessary, initialize smootheners. | fastai/vision/gan.py | 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... | 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... | [
"Create",
"the",
"optimizers",
"for",
"the",
"generator",
"and",
"critic",
"if",
"necessary",
"initialize",
"smootheners",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L90-L104 | [
"def",
"on_train_begin",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"'opt_gen'",
",",
"None",
")",
":",
"self",
".",
"opt_gen",
"=",
"self",
".",
"opt",
".",
"new",
"(",
"[",
"nn",
".",
"Sequential",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANTrainer.on_batch_begin | Clamp the weights with `self.clip` if it's not None, return the correct input. | fastai/vision/gan.py | 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... | 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... | [
"Clamp",
"the",
"weights",
"with",
"self",
".",
"clip",
"if",
"it",
"s",
"not",
"None",
"return",
"the",
"correct",
"input",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L110-L114 | [
"def",
"on_batch_begin",
"(",
"self",
",",
"last_input",
",",
"last_target",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"clip",
"is",
"not",
"None",
":",
"for",
"p",
"in",
"self",
".",
"critic",
".",
"parameters",
"(",
")",
":",
"p",
"."... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANTrainer.on_backward_begin | Record `last_loss` in the proper list. | fastai/vision/gan.py | 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... | 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... | [
"Record",
"last_loss",
"in",
"the",
"proper",
"list",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L116-L125 | [
"def",
"on_backward_begin",
"(",
"self",
",",
"last_loss",
",",
"last_output",
",",
"*",
"*",
"kwargs",
")",
":",
"last_loss",
"=",
"last_loss",
".",
"detach",
"(",
")",
".",
"cpu",
"(",
")",
"if",
"self",
".",
"gen_mode",
":",
"self",
".",
"smoothener... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANTrainer.on_epoch_end | Put the various losses in the recorder and show a sample image. | fastai/vision/gan.py | 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 ... | 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 ... | [
"Put",
"the",
"various",
"losses",
"in",
"the",
"recorder",
"and",
"show",
"a",
"sample",
"image",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L131-L142 | [
"def",
"on_epoch_end",
"(",
"self",
",",
"pbar",
",",
"epoch",
",",
"last_metrics",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'last_gen'",
")",
"or",
"not",
"self",
".",
"show_img",
":",
"return",
"data",
"=",
"sel... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANTrainer.switch | Switch the model, if `gen_mode` is provided, in the desired mode. | fastai/vision/gan.py | 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... | 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... | [
"Switch",
"the",
"model",
"if",
"gen_mode",
"is",
"provided",
"in",
"the",
"desired",
"mode",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L144-L150 | [
"def",
"switch",
"(",
"self",
",",
"gen_mode",
":",
"bool",
"=",
"None",
")",
":",
"self",
".",
"gen_mode",
"=",
"(",
"not",
"self",
".",
"gen_mode",
")",
"if",
"gen_mode",
"is",
"None",
"else",
"gen_mode",
"self",
".",
"opt",
".",
"opt",
"=",
"sel... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | FixedGANSwitcher.on_batch_end | Switch the model if necessary. | fastai/vision/gan.py | 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
... | 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
... | [
"Switch",
"the",
"model",
"if",
"necessary",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L162-L173 | [
"def",
"on_batch_end",
"(",
"self",
",",
"iteration",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"learn",
".",
"gan_trainer",
".",
"gen_mode",
":",
"self",
".",
"n_g",
"+=",
"1",
"n_iter",
",",
"n_in",
",",
"n_out",
"=",
"self",
".",
"n_... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANLearner.from_learners | Create a GAN from `learn_gen` and `learn_crit`. | fastai/vision/gan.py | 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... | 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... | [
"Create",
"a",
"GAN",
"from",
"learn_gen",
"and",
"learn_crit",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L219-L223 | [
"def",
"from_learners",
"(",
"cls",
",",
"learn_gen",
":",
"Learner",
",",
"learn_crit",
":",
"Learner",
",",
"switcher",
":",
"Callback",
"=",
"None",
",",
"weights_gen",
":",
"Tuple",
"[",
"float",
",",
"float",
"]",
"=",
"None",
",",
"*",
"*",
"lear... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANLearner.wgan | Create a WGAN from `data`, `generator` and `critic`. | fastai/vision/gan.py | 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) | 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) | [
"Create",
"a",
"WGAN",
"from",
"data",
"generator",
"and",
"critic",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L226-L228 | [
"def",
"wgan",
"(",
"cls",
",",
"data",
":",
"DataBunch",
",",
"generator",
":",
"nn",
".",
"Module",
",",
"critic",
":",
"nn",
".",
"Module",
",",
"switcher",
":",
"Callback",
"=",
"None",
",",
"clip",
":",
"float",
"=",
"0.01",
",",
"*",
"*",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANItemList.show_xys | Shows `ys` (target images) on a figure of `figsize`. | fastai/vision/gan.py | def show_xys(self, xs, ys, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs):
"Shows `ys` (target images) on a figure of `figsize`."
super().show_xys(ys, xs, imgsize=imgsize, figsize=figsize, **kwargs) | def show_xys(self, xs, ys, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs):
"Shows `ys` (target images) on a figure of `figsize`."
super().show_xys(ys, xs, imgsize=imgsize, figsize=figsize, **kwargs) | [
"Shows",
"ys",
"(",
"target",
"images",
")",
"on",
"a",
"figure",
"of",
"figsize",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L248-L250 | [
"def",
"show_xys",
"(",
"self",
",",
"xs",
",",
"ys",
",",
"imgsize",
":",
"int",
"=",
"4",
",",
"figsize",
":",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANDiscriminativeLR.on_batch_begin | Multiply the current lr if necessary. | fastai/vision/gan.py | 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 | 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 | [
"Multiply",
"the",
"current",
"lr",
"if",
"necessary",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L284-L286 | [
"def",
"on_batch_begin",
"(",
"self",
",",
"train",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"learn",
".",
"gan_trainer",
".",
"gen_mode",
"and",
"train",
":",
"self",
".",
"learn",
".",
"opt",
".",
"lr",
"*=",
"self",
".",
"mul... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | GANDiscriminativeLR.on_step_end | Put the LR back to its value if necessary. | fastai/vision/gan.py | 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 | 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 | [
"Put",
"the",
"LR",
"back",
"to",
"its",
"value",
"if",
"necessary",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L288-L290 | [
"def",
"on_step_end",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"learn",
".",
"gan_trainer",
".",
"gen_mode",
":",
"self",
".",
"learn",
".",
"opt",
".",
"lr",
"/=",
"self",
".",
"mult_lr"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _get_sfs_idxs | Get the indexes of the layers where the size of the activation changes. | fastai/vision/models/unet.py | 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... | 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... | [
"Get",
"the",
"indexes",
"of",
"the",
"layers",
"where",
"the",
"size",
"of",
"the",
"activation",
"changes",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/models/unet.py#L7-L12 | [
"def",
"_get_sfs_idxs",
"(",
"sizes",
":",
"Sizes",
")",
"->",
"List",
"[",
"int",
"]",
":",
"feature_szs",
"=",
"[",
"size",
"[",
"-",
"1",
"]",
"for",
"size",
"in",
"sizes",
"]",
"sfs_idxs",
"=",
"list",
"(",
"np",
".",
"where",
"(",
"np",
".",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | download_google_images | Search for `n_images` images on Google, matching `search_term` and `size` requirements,
download them into `path`/`search_term` and verify them, using `max_workers` threads. | fastai/widgets/image_downloader.py | def download_google_images(path:PathOrStr, search_term:str, size:str='>400*300', n_images:int=10, format:str='jpg',
max_workers:int=defaults.cpus, timeout:int=4) -> FilePathList:
"""
Search for `n_images` images on Google, matching `search_term` and `size` requirements,
download ... | def download_google_images(path:PathOrStr, search_term:str, size:str='>400*300', n_images:int=10, format:str='jpg',
max_workers:int=defaults.cpus, timeout:int=4) -> FilePathList:
"""
Search for `n_images` images on Google, matching `search_term` and `size` requirements,
download ... | [
"Search",
"for",
"n_images",
"images",
"on",
"Google",
"matching",
"search_term",
"and",
"size",
"requirements",
"download",
"them",
"into",
"path",
"/",
"search_term",
"and",
"verify",
"them",
"using",
"max_workers",
"threads",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L78-L91 | [
"def",
"download_google_images",
"(",
"path",
":",
"PathOrStr",
",",
"search_term",
":",
"str",
",",
"size",
":",
"str",
"=",
"'>400*300'",
",",
"n_images",
":",
"int",
"=",
"10",
",",
"format",
":",
"str",
"=",
"'jpg'",
",",
"max_workers",
":",
"int",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _url_params | Build Google Images Search Url params and return them as a string. | fastai/widgets/image_downloader.py | 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':'ift:gif','png':'ift:png','bmp':'ift:bmp', 'svg':'ift:svg','webp':'webp','ico':'ift:ico'}
if size not in _img_sizes:
raise RuntimeError(... | 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':'ift:gif','png':'ift:png','bmp':'ift:bmp', 'svg':'ift:svg','webp':'webp','ico':'ift:ico'}
if size not in _img_sizes:
raise RuntimeError(... | [
"Build",
"Google",
"Images",
"Search",
"Url",
"params",
"and",
"return",
"them",
"as",
"a",
"string",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L93-L101 | [
"def",
"_url_params",
"(",
"size",
":",
"str",
"=",
"'>400*300'",
",",
"format",
":",
"str",
"=",
"'jpg'",
")",
"->",
"str",
":",
"_fmts",
"=",
"{",
"'jpg'",
":",
"'ift:jpg'",
",",
"'gif'",
":",
"'ift:gif'",
",",
"'png'",
":",
"'ift:png'",
",",
"'bmp... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _search_url | Return a Google Images Search URL for a given search term. | fastai/widgets/image_downloader.py | def _search_url(search_term:str, size:str='>400*300', format:str='jpg') -> str:
"Return a Google Images Search URL for a given search term."
return ('https://www.google.com/search?q=' + quote(search_term) +
'&espv=2&biw=1366&bih=667&site=webhp&source=lnms&tbm=isch' +
_url_params(size, fo... | def _search_url(search_term:str, size:str='>400*300', format:str='jpg') -> str:
"Return a Google Images Search URL for a given search term."
return ('https://www.google.com/search?q=' + quote(search_term) +
'&espv=2&biw=1366&bih=667&site=webhp&source=lnms&tbm=isch' +
_url_params(size, fo... | [
"Return",
"a",
"Google",
"Images",
"Search",
"URL",
"for",
"a",
"given",
"search",
"term",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L103-L107 | [
"def",
"_search_url",
"(",
"search_term",
":",
"str",
",",
"size",
":",
"str",
"=",
"'>400*300'",
",",
"format",
":",
"str",
"=",
"'jpg'",
")",
"->",
"str",
":",
"return",
"(",
"'https://www.google.com/search?q='",
"+",
"quote",
"(",
"search_term",
")",
"+... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _fetch_img_tuples | Parse the Google Images Search for urls and return the image metadata as tuples (fname, url). | fastai/widgets/image_downloader.py | def _fetch_img_tuples(url:str, format:str='jpg', n_images:int=10) -> list:
"Parse the Google Images Search for urls and return the image metadata as tuples (fname, url)."
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
html = r... | def _fetch_img_tuples(url:str, format:str='jpg', n_images:int=10) -> list:
"Parse the Google Images Search for urls and return the image metadata as tuples (fname, url)."
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
html = r... | [
"Parse",
"the",
"Google",
"Images",
"Search",
"for",
"urls",
"and",
"return",
"the",
"image",
"metadata",
"as",
"tuples",
"(",
"fname",
"url",
")",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L113-L117 | [
"def",
"_fetch_img_tuples",
"(",
"url",
":",
"str",
",",
"format",
":",
"str",
"=",
"'jpg'",
",",
"n_images",
":",
"int",
"=",
"10",
")",
"->",
"list",
":",
"headers",
"=",
"{",
"'User-Agent'",
":",
"'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like ... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _html_to_img_tuples | Parse the google images html to img tuples containining `(fname, url)` | fastai/widgets/image_downloader.py | def _html_to_img_tuples(html:str, format:str='jpg', n_images:int=10) -> list:
"Parse the google images html to img tuples containining `(fname, url)`"
bs = BeautifulSoup(html, 'html.parser')
img_tags = bs.find_all('div', {'class': 'rg_meta'})
metadata_dicts = (json.loads(e.text) for e in img_tags)
... | def _html_to_img_tuples(html:str, format:str='jpg', n_images:int=10) -> list:
"Parse the google images html to img tuples containining `(fname, url)`"
bs = BeautifulSoup(html, 'html.parser')
img_tags = bs.find_all('div', {'class': 'rg_meta'})
metadata_dicts = (json.loads(e.text) for e in img_tags)
... | [
"Parse",
"the",
"google",
"images",
"html",
"to",
"img",
"tuples",
"containining",
"(",
"fname",
"url",
")"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L119-L125 | [
"def",
"_html_to_img_tuples",
"(",
"html",
":",
"str",
",",
"format",
":",
"str",
"=",
"'jpg'",
",",
"n_images",
":",
"int",
"=",
"10",
")",
"->",
"list",
":",
"bs",
"=",
"BeautifulSoup",
"(",
"html",
",",
"'html.parser'",
")",
"img_tags",
"=",
"bs",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _fetch_img_tuples_webdriver | Parse the Google Images Search for urls and return the image metadata as tuples (fname, url).
Use this for downloads of >100 images. Requires `selenium`. | fastai/widgets/image_downloader.py | def _fetch_img_tuples_webdriver(url:str, format:str='jpg', n_images:int=150) -> list:
"""
Parse the Google Images Search for urls and return the image metadata as tuples (fname, url).
Use this for downloads of >100 images. Requires `selenium`.
"""
try:
from selenium import webdriver
... | def _fetch_img_tuples_webdriver(url:str, format:str='jpg', n_images:int=150) -> list:
"""
Parse the Google Images Search for urls and return the image metadata as tuples (fname, url).
Use this for downloads of >100 images. Requires `selenium`.
"""
try:
from selenium import webdriver
... | [
"Parse",
"the",
"Google",
"Images",
"Search",
"for",
"urls",
"and",
"return",
"the",
"image",
"metadata",
"as",
"tuples",
"(",
"fname",
"url",
")",
".",
"Use",
"this",
"for",
"downloads",
"of",
">",
"100",
"images",
".",
"Requires",
"selenium",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L127-L157 | [
"def",
"_fetch_img_tuples_webdriver",
"(",
"url",
":",
"str",
",",
"format",
":",
"str",
"=",
"'jpg'",
",",
"n_images",
":",
"int",
"=",
"150",
")",
"->",
"list",
":",
"try",
":",
"from",
"selenium",
"import",
"webdriver",
"from",
"selenium",
".",
"webdr... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _download_images | Downloads images in `img_tuples` to `label_path`.
If the directory doesn't exist, it'll be created automatically.
Uses `parallel` to speed things up in `max_workers` when the system has enough CPU cores.
If something doesn't work, try setting up `max_workers=0` to debug. | fastai/widgets/image_downloader.py | def _download_images(label_path:PathOrStr, img_tuples:list, max_workers:int=defaults.cpus, timeout:int=4) -> FilePathList:
"""
Downloads images in `img_tuples` to `label_path`.
If the directory doesn't exist, it'll be created automatically.
Uses `parallel` to speed things up in `max_workers` when the s... | def _download_images(label_path:PathOrStr, img_tuples:list, max_workers:int=defaults.cpus, timeout:int=4) -> FilePathList:
"""
Downloads images in `img_tuples` to `label_path`.
If the directory doesn't exist, it'll be created automatically.
Uses `parallel` to speed things up in `max_workers` when the s... | [
"Downloads",
"images",
"in",
"img_tuples",
"to",
"label_path",
".",
"If",
"the",
"directory",
"doesn",
"t",
"exist",
"it",
"ll",
"be",
"created",
"automatically",
".",
"Uses",
"parallel",
"to",
"speed",
"things",
"up",
"in",
"max_workers",
"when",
"the",
"sy... | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L159-L168 | [
"def",
"_download_images",
"(",
"label_path",
":",
"PathOrStr",
",",
"img_tuples",
":",
"list",
",",
"max_workers",
":",
"int",
"=",
"defaults",
".",
"cpus",
",",
"timeout",
":",
"int",
"=",
"4",
")",
"->",
"FilePathList",
":",
"os",
".",
"makedirs",
"("... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _download_single_image | Downloads a single image from Google Search results to `label_path`
given an `img_tuple` that contains `(fname, url)` of an image to download.
`i` is just an iteration number `int`. | fastai/widgets/image_downloader.py | def _download_single_image(label_path:Path, img_tuple:tuple, i:int, timeout:int=4) -> None:
"""
Downloads a single image from Google Search results to `label_path`
given an `img_tuple` that contains `(fname, url)` of an image to download.
`i` is just an iteration number `int`.
"""
suffix = re.f... | def _download_single_image(label_path:Path, img_tuple:tuple, i:int, timeout:int=4) -> None:
"""
Downloads a single image from Google Search results to `label_path`
given an `img_tuple` that contains `(fname, url)` of an image to download.
`i` is just an iteration number `int`.
"""
suffix = re.f... | [
"Downloads",
"a",
"single",
"image",
"from",
"Google",
"Search",
"results",
"to",
"label_path",
"given",
"an",
"img_tuple",
"that",
"contains",
"(",
"fname",
"url",
")",
"of",
"an",
"image",
"to",
"download",
".",
"i",
"is",
"just",
"an",
"iteration",
"num... | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L170-L179 | [
"def",
"_download_single_image",
"(",
"label_path",
":",
"Path",
",",
"img_tuple",
":",
"tuple",
",",
"i",
":",
"int",
",",
"timeout",
":",
"int",
"=",
"4",
")",
"->",
"None",
":",
"suffix",
"=",
"re",
".",
"findall",
"(",
"r'\\.\\w+?(?=(?:\\?|$))'",
","... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ImageDownloader._init_ui | Initialize the widget UI and return the UI. | fastai/widgets/image_downloader.py | def _init_ui(self) -> VBox:
"Initialize the widget UI and return the UI."
self._search_input = Text(placeholder="What images to search for?")
self._count_input = BoundedIntText(placeholder="How many pics?", value=10, min=1, max=5000, step=1,
layout=Layo... | def _init_ui(self) -> VBox:
"Initialize the widget UI and return the UI."
self._search_input = Text(placeholder="What images to search for?")
self._count_input = BoundedIntText(placeholder="How many pics?", value=10, min=1, max=5000, step=1,
layout=Layo... | [
"Initialize",
"the",
"widget",
"UI",
"and",
"return",
"the",
"UI",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L27-L42 | [
"def",
"_init_ui",
"(",
"self",
")",
"->",
"VBox",
":",
"self",
".",
"_search_input",
"=",
"Text",
"(",
"placeholder",
"=",
"\"What images to search for?\"",
")",
"self",
".",
"_count_input",
"=",
"BoundedIntText",
"(",
"placeholder",
"=",
"\"How many pics?\"",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ImageDownloader.clear_imgs | Clear the widget's images preview pane. | fastai/widgets/image_downloader.py | def clear_imgs(self) -> None:
"Clear the widget's images preview pane."
self._preview_header.value = self._heading
self._img_pane.children = tuple() | def clear_imgs(self) -> None:
"Clear the widget's images preview pane."
self._preview_header.value = self._heading
self._img_pane.children = tuple() | [
"Clear",
"the",
"widget",
"s",
"images",
"preview",
"pane",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L48-L51 | [
"def",
"clear_imgs",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_preview_header",
".",
"value",
"=",
"self",
".",
"_heading",
"self",
".",
"_img_pane",
".",
"children",
"=",
"tuple",
"(",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ImageDownloader.validate_search_input | Check if input value is empty. | fastai/widgets/image_downloader.py | def validate_search_input(self) -> bool:
"Check if input value is empty."
input = self._search_input
if input.value == str(): input.layout = Layout(border="solid 2px red", height='auto')
else: self._search_input.layout = Layout()
return input.value != str() | def validate_search_input(self) -> bool:
"Check if input value is empty."
input = self._search_input
if input.value == str(): input.layout = Layout(border="solid 2px red", height='auto')
else: self._search_input.layout = Layout()
return input.value != str() | [
"Check",
"if",
"input",
"value",
"is",
"empty",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L53-L58 | [
"def",
"validate_search_input",
"(",
"self",
")",
"->",
"bool",
":",
"input",
"=",
"self",
".",
"_search_input",
"if",
"input",
".",
"value",
"==",
"str",
"(",
")",
":",
"input",
".",
"layout",
"=",
"Layout",
"(",
"border",
"=",
"\"solid 2px red\"",
",",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ImageDownloader.on_download_button_click | Download button click handler: validate search term and download images. | fastai/widgets/image_downloader.py | def on_download_button_click(self, btn) -> None:
"Download button click handler: validate search term and download images."
term = self._search_input.value
limit = int(self._count_input.value)
size = self._size_input.value
if not self.validate_search_input(): return
self.... | def on_download_button_click(self, btn) -> None:
"Download button click handler: validate search term and download images."
term = self._search_input.value
limit = int(self._count_input.value)
size = self._size_input.value
if not self.validate_search_input(): return
self.... | [
"Download",
"button",
"click",
"handler",
":",
"validate",
"search",
"term",
"and",
"download",
"images",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L60-L70 | [
"def",
"on_download_button_click",
"(",
"self",
",",
"btn",
")",
"->",
"None",
":",
"term",
"=",
"self",
".",
"_search_input",
".",
"value",
"limit",
"=",
"int",
"(",
"self",
".",
"_count_input",
".",
"value",
")",
"size",
"=",
"self",
".",
"_size_input"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ImageDownloader.display_images_widgets | Display a few preview images in the notebook | fastai/widgets/image_downloader.py | def display_images_widgets(self, fnames:list) -> None:
"Display a few preview images in the notebook"
imgs = [widgets.Image(value=open(f, 'rb').read(), width='200px') for f in fnames]
self._img_pane.children = tuple(imgs) | def display_images_widgets(self, fnames:list) -> None:
"Display a few preview images in the notebook"
imgs = [widgets.Image(value=open(f, 'rb').read(), width='200px') for f in fnames]
self._img_pane.children = tuple(imgs) | [
"Display",
"a",
"few",
"preview",
"images",
"in",
"the",
"notebook"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L72-L75 | [
"def",
"display_images_widgets",
"(",
"self",
",",
"fnames",
":",
"list",
")",
"->",
"None",
":",
"imgs",
"=",
"[",
"widgets",
".",
"Image",
"(",
"value",
"=",
"open",
"(",
"f",
",",
"'rb'",
")",
".",
"read",
"(",
")",
",",
"width",
"=",
"'200px'",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LRFinder.on_train_begin | Initialize optimizer and learner hyperparameters. | fastai/callbacks/lr_finder.py | def on_train_begin(self, pbar, **kwargs:Any)->None:
"Initialize optimizer and learner hyperparameters."
setattr(pbar, 'clean_on_interrupt', True)
self.learn.save('tmp')
self.opt = self.learn.opt
self.opt.lr = self.sched.start
self.stop,self.best_loss = False,0.
re... | def on_train_begin(self, pbar, **kwargs:Any)->None:
"Initialize optimizer and learner hyperparameters."
setattr(pbar, 'clean_on_interrupt', True)
self.learn.save('tmp')
self.opt = self.learn.opt
self.opt.lr = self.sched.start
self.stop,self.best_loss = False,0.
re... | [
"Initialize",
"optimizer",
"and",
"learner",
"hyperparameters",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/lr_finder.py#L16-L23 | [
"def",
"on_train_begin",
"(",
"self",
",",
"pbar",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"setattr",
"(",
"pbar",
",",
"'clean_on_interrupt'",
",",
"True",
")",
"self",
".",
"learn",
".",
"save",
"(",
"'tmp'",
")",
"self",
".",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LRFinder.on_batch_end | Determine if loss has runaway and we should stop. | fastai/callbacks/lr_finder.py | def on_batch_end(self, iteration:int, smooth_loss:TensorOrNumber, **kwargs:Any)->None:
"Determine if loss has runaway and we should stop."
if iteration==0 or smooth_loss < self.best_loss: self.best_loss = smooth_loss
self.opt.lr = self.sched.step()
if self.sched.is_done or (self.stop_div... | def on_batch_end(self, iteration:int, smooth_loss:TensorOrNumber, **kwargs:Any)->None:
"Determine if loss has runaway and we should stop."
if iteration==0 or smooth_loss < self.best_loss: self.best_loss = smooth_loss
self.opt.lr = self.sched.step()
if self.sched.is_done or (self.stop_div... | [
"Determine",
"if",
"loss",
"has",
"runaway",
"and",
"we",
"should",
"stop",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/lr_finder.py#L25-L31 | [
"def",
"on_batch_end",
"(",
"self",
",",
"iteration",
":",
"int",
",",
"smooth_loss",
":",
"TensorOrNumber",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"if",
"iteration",
"==",
"0",
"or",
"smooth_loss",
"<",
"self",
".",
"best_loss",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | LRFinder.on_train_end | Cleanup learn model weights disturbed during LRFinder exploration. | fastai/callbacks/lr_finder.py | def on_train_end(self, **kwargs:Any)->None:
"Cleanup learn model weights disturbed during LRFinder exploration."
self.learn.load('tmp', purge=False)
if hasattr(self.learn.model, 'reset'): self.learn.model.reset()
for cb in self.callbacks:
if hasattr(cb, 'reset'): cb.reset()
... | def on_train_end(self, **kwargs:Any)->None:
"Cleanup learn model weights disturbed during LRFinder exploration."
self.learn.load('tmp', purge=False)
if hasattr(self.learn.model, 'reset'): self.learn.model.reset()
for cb in self.callbacks:
if hasattr(cb, 'reset'): cb.reset()
... | [
"Cleanup",
"learn",
"model",
"weights",
"disturbed",
"during",
"LRFinder",
"exploration",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/lr_finder.py#L33-L39 | [
"def",
"on_train_end",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"learn",
".",
"load",
"(",
"'tmp'",
",",
"purge",
"=",
"False",
")",
"if",
"hasattr",
"(",
"self",
".",
"learn",
".",
"model",
",",
"'re... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | dropout_mask | Applies a dropout mask whose size is determined by passed argument 'sz'.
Args:
x (nn.Variable): A torch Variable object
sz (tuple(int, int, int)): The expected size of the new tensor
dropout (float): The dropout fraction to apply
This method uses the bernoulli distribution to decide whi... | old/fastai/rnn_reg.py | def dropout_mask(x, sz, dropout):
""" Applies a dropout mask whose size is determined by passed argument 'sz'.
Args:
x (nn.Variable): A torch Variable object
sz (tuple(int, int, int)): The expected size of the new tensor
dropout (float): The dropout fraction to apply
This method use... | def dropout_mask(x, sz, dropout):
""" Applies a dropout mask whose size is determined by passed argument 'sz'.
Args:
x (nn.Variable): A torch Variable object
sz (tuple(int, int, int)): The expected size of the new tensor
dropout (float): The dropout fraction to apply
This method use... | [
"Applies",
"a",
"dropout",
"mask",
"whose",
"size",
"is",
"determined",
"by",
"passed",
"argument",
"sz",
".",
"Args",
":",
"x",
"(",
"nn",
".",
"Variable",
")",
":",
"A",
"torch",
"Variable",
"object",
"sz",
"(",
"tuple",
"(",
"int",
"int",
"int",
"... | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/rnn_reg.py#L9-L47 | [
"def",
"dropout_mask",
"(",
"x",
",",
"sz",
",",
"dropout",
")",
":",
"return",
"x",
".",
"new",
"(",
"*",
"sz",
")",
".",
"bernoulli_",
"(",
"1",
"-",
"dropout",
")",
"/",
"(",
"1",
"-",
"dropout",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | WeightDrop._setup | for each string defined in self.weights, the corresponding
attribute in the wrapped module is referenced, then deleted, and subsequently
registered as a new parameter with a slightly modified name.
Args:
None
Returns:
None | old/fastai/rnn_reg.py | def _setup(self):
""" for each string defined in self.weights, the corresponding
attribute in the wrapped module is referenced, then deleted, and subsequently
registered as a new parameter with a slightly modified name.
Args:
None
Returns:
None
... | def _setup(self):
""" for each string defined in self.weights, the corresponding
attribute in the wrapped module is referenced, then deleted, and subsequently
registered as a new parameter with a slightly modified name.
Args:
None
Returns:
None
... | [
"for",
"each",
"string",
"defined",
"in",
"self",
".",
"weights",
"the",
"corresponding",
"attribute",
"in",
"the",
"wrapped",
"module",
"is",
"referenced",
"then",
"deleted",
"and",
"subsequently",
"registered",
"as",
"a",
"new",
"parameter",
"with",
"a",
"sl... | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/rnn_reg.py#L79-L94 | [
"def",
"_setup",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"module",
",",
"torch",
".",
"nn",
".",
"RNNBase",
")",
":",
"self",
".",
"module",
".",
"flatten_parameters",
"=",
"noop",
"for",
"name_w",
"in",
"self",
".",
"weights",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | WeightDrop._setweights | Uses pytorch's built-in dropout function to apply dropout to the parameters of
the wrapped module.
Args:
None
Returns:
None | old/fastai/rnn_reg.py | def _setweights(self):
""" Uses pytorch's built-in dropout function to apply dropout to the parameters of
the wrapped module.
Args:
None
Returns:
None
"""
for name_w in self.weights:
raw_w = getattr(self.module, name_w + '_raw')
... | def _setweights(self):
""" Uses pytorch's built-in dropout function to apply dropout to the parameters of
the wrapped module.
Args:
None
Returns:
None
"""
for name_w in self.weights:
raw_w = getattr(self.module, name_w + '_raw')
... | [
"Uses",
"pytorch",
"s",
"built",
"-",
"in",
"dropout",
"function",
"to",
"apply",
"dropout",
"to",
"the",
"parameters",
"of",
"the",
"wrapped",
"module",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/rnn_reg.py#L97-L111 | [
"def",
"_setweights",
"(",
"self",
")",
":",
"for",
"name_w",
"in",
"self",
".",
"weights",
":",
"raw_w",
"=",
"getattr",
"(",
"self",
".",
"module",
",",
"name_w",
"+",
"'_raw'",
")",
"w",
"=",
"torch",
".",
"nn",
".",
"functional",
".",
"dropout",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | load_data | Load a saved `DataBunch` from `path/file`. `file` can be file-like (file or buffer) | fastai/basic_data.py | def load_data(path:PathOrStr, file:PathLikeOrBinaryStream='data_save.pkl', 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:
"Load ... | def load_data(path:PathOrStr, file:PathLikeOrBinaryStream='data_save.pkl', 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:
"Load ... | [
"Load",
"a",
"saved",
"DataBunch",
"from",
"path",
"/",
"file",
".",
"file",
"can",
"be",
"file",
"-",
"like",
"(",
"file",
"or",
"buffer",
")"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L272-L279 | [
"def",
"load_data",
"(",
"path",
":",
"PathOrStr",
",",
"file",
":",
"PathLikeOrBinaryStream",
"=",
"'data_save.pkl'",
",",
"bs",
":",
"int",
"=",
"64",
",",
"val_bs",
":",
"int",
"=",
"None",
",",
"num_workers",
":",
"int",
"=",
"defaults",
".",
"cpus",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | DataBunch.create | Create a `DataBunch` from `train_ds`, `valid_ds` and maybe `test_ds` with a batch size of `bs`. Passes `**dl_kwargs` to `DataLoader()` | fastai/basic_data.py | def create(cls, train_ds:Dataset, valid_ds:Dataset, test_ds:Optional[Dataset]=None, path:PathOrStr='.', 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, *... | def create(cls, train_ds:Dataset, valid_ds:Dataset, test_ds:Optional[Dataset]=None, path:PathOrStr='.', 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, *... | [
"Create",
"a",
"DataBunch",
"from",
"train_ds",
"valid_ds",
"and",
"maybe",
"test_ds",
"with",
"a",
"batch",
"size",
"of",
"bs",
".",
"Passes",
"**",
"dl_kwargs",
"to",
"DataLoader",
"()"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L112-L120 | [
"def",
"create",
"(",
"cls",
",",
"train_ds",
":",
"Dataset",
",",
"valid_ds",
":",
"Dataset",
",",
"test_ds",
":",
"Optional",
"[",
"Dataset",
"]",
"=",
"None",
",",
"path",
":",
"PathOrStr",
"=",
"'.'",
",",
"bs",
":",
"int",
"=",
"64",
",",
"val... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | DataBunch.dl | Returns appropriate `Dataset` for validation, training, or test (`ds_type`). | fastai/basic_data.py | def dl(self, ds_type:DatasetType=DatasetType.Valid)->DeviceDataLoader:
"Returns appropriate `Dataset` for validation, training, or test (`ds_type`)."
#TODO: refactor
return (self.train_dl if ds_type == DatasetType.Train else
self.test_dl if ds_type == DatasetType.Test else
... | def dl(self, ds_type:DatasetType=DatasetType.Valid)->DeviceDataLoader:
"Returns appropriate `Dataset` for validation, training, or test (`ds_type`)."
#TODO: refactor
return (self.train_dl if ds_type == DatasetType.Train else
self.test_dl if ds_type == DatasetType.Test else
... | [
"Returns",
"appropriate",
"Dataset",
"for",
"validation",
"training",
"or",
"test",
"(",
"ds_type",
")",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L125-L132 | [
"def",
"dl",
"(",
"self",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Valid",
")",
"->",
"DeviceDataLoader",
":",
"#TODO: refactor",
"return",
"(",
"self",
".",
"train_dl",
"if",
"ds_type",
"==",
"DatasetType",
".",
"Train",
"else",
"self",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | DataBunch.dls | Returns a list of all DeviceDataLoaders. If you need a specific DeviceDataLoader, access via the relevant property (`train_dl`, `valid_dl`, etc) as the index of DLs in this list is not guaranteed to remain constant. | fastai/basic_data.py | def dls(self)->List[DeviceDataLoader]:
"Returns a list of all DeviceDataLoaders. If you need a specific DeviceDataLoader, access via the relevant property (`train_dl`, `valid_dl`, etc) as the index of DLs in this list is not guaranteed to remain constant."
res = [self.train_dl, self.fix_dl, self.single_... | def dls(self)->List[DeviceDataLoader]:
"Returns a list of all DeviceDataLoaders. If you need a specific DeviceDataLoader, access via the relevant property (`train_dl`, `valid_dl`, etc) as the index of DLs in this list is not guaranteed to remain constant."
res = [self.train_dl, self.fix_dl, self.single_... | [
"Returns",
"a",
"list",
"of",
"all",
"DeviceDataLoaders",
".",
"If",
"you",
"need",
"a",
"specific",
"DeviceDataLoader",
"access",
"via",
"the",
"relevant",
"property",
"(",
"train_dl",
"valid_dl",
"etc",
")",
"as",
"the",
"index",
"of",
"DLs",
"in",
"this",... | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L135-L141 | [
"def",
"dls",
"(",
"self",
")",
"->",
"List",
"[",
"DeviceDataLoader",
"]",
":",
"res",
"=",
"[",
"self",
".",
"train_dl",
",",
"self",
".",
"fix_dl",
",",
"self",
".",
"single_dl",
"]",
"# Preserve the original ordering of Train, Valid, Fix, Single, Test Data Loa... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | DataBunch.save | Save the `DataBunch` in `self.path/file`. `file` can be file-like (file or buffer) | fastai/basic_data.py | def save(self, file:PathLikeOrBinaryStream= 'data_save.pkl')->None:
"Save the `DataBunch` in `self.path/file`. `file` can be file-like (file or buffer)"
if not getattr(self, 'label_list', False):
warn("Serializing the `DataBunch` only works when you created it using the data block API.")
... | def save(self, file:PathLikeOrBinaryStream= 'data_save.pkl')->None:
"Save the `DataBunch` in `self.path/file`. `file` can be file-like (file or buffer)"
if not getattr(self, 'label_list', False):
warn("Serializing the `DataBunch` only works when you created it using the data block API.")
... | [
"Save",
"the",
"DataBunch",
"in",
"self",
".",
"path",
"/",
"file",
".",
"file",
"can",
"be",
"file",
"-",
"like",
"(",
"file",
"or",
"buffer",
")"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L149-L154 | [
"def",
"save",
"(",
"self",
",",
"file",
":",
"PathLikeOrBinaryStream",
"=",
"'data_save.pkl'",
")",
"->",
"None",
":",
"if",
"not",
"getattr",
"(",
"self",
",",
"'label_list'",
",",
"False",
")",
":",
"warn",
"(",
"\"Serializing the `DataBunch` only works when ... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | DataBunch.one_batch | Get one batch from the data loader of `ds_type`. Optionally `detach` and `denorm`. | fastai/basic_data.py | def one_batch(self, ds_type:DatasetType=DatasetType.Train, detach:bool=True, denorm:bool=True, cpu:bool=True)->Collection[Tensor]:
"Get one batch from the data loader of `ds_type`. Optionally `detach` and `denorm`."
dl = self.dl(ds_type)
w = self.num_workers
self.num_workers = 0
... | def one_batch(self, ds_type:DatasetType=DatasetType.Train, detach:bool=True, denorm:bool=True, cpu:bool=True)->Collection[Tensor]:
"Get one batch from the data loader of `ds_type`. Optionally `detach` and `denorm`."
dl = self.dl(ds_type)
w = self.num_workers
self.num_workers = 0
... | [
"Get",
"one",
"batch",
"from",
"the",
"data",
"loader",
"of",
"ds_type",
".",
"Optionally",
"detach",
"and",
"denorm",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L163-L175 | [
"def",
"one_batch",
"(",
"self",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Train",
",",
"detach",
":",
"bool",
"=",
"True",
",",
"denorm",
":",
"bool",
"=",
"True",
",",
"cpu",
":",
"bool",
"=",
"True",
")",
"->",
"Collection",
"[... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.