id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
20,600
|
fastai/fastai
|
fastai/vision/gan.py
|
FixedGANSwitcher.on_batch_end
|
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
target = n_iter if isinstance(n_iter, int) else n_iter(n_in)
if target == n_out:
self.learn.gan_trainer.switch()
self.n_c,self.n_g = 0,0
|
python
|
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
target = n_iter if isinstance(n_iter, int) else n_iter(n_in)
if target == n_out:
self.learn.gan_trainer.switch()
self.n_c,self.n_g = 0,0
|
[
"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_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",
"target",
"=",
"n_iter",
"if",
"isinstance",
"(",
"n_iter",
",",
"int",
")",
"else",
"n_iter",
"(",
"n_in",
")",
"if",
"target",
"==",
"n_out",
":",
"self",
".",
"learn",
".",
"gan_trainer",
".",
"switch",
"(",
")",
"self",
".",
"n_c",
",",
"self",
".",
"n_g",
"=",
"0",
",",
"0"
] |
Switch the model if necessary.
|
[
"Switch",
"the",
"model",
"if",
"necessary",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L162-L173
|
20,601
|
fastai/fastai
|
fastai/vision/gan.py
|
GANLearner.from_learners
|
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_gen)
return cls(learn_gen.data, learn_gen.model, learn_crit.model, *losses, switcher=switcher, **learn_kwargs)
|
python
|
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_gen)
return cls(learn_gen.data, learn_gen.model, learn_crit.model, *losses, switcher=switcher, **learn_kwargs)
|
[
"def",
"from_learners",
"(",
"cls",
",",
"learn_gen",
":",
"Learner",
",",
"learn_crit",
":",
"Learner",
",",
"switcher",
":",
"Callback",
"=",
"None",
",",
"weights_gen",
":",
"Tuple",
"[",
"float",
",",
"float",
"]",
"=",
"None",
",",
"*",
"*",
"learn_kwargs",
")",
":",
"losses",
"=",
"gan_loss_from_func",
"(",
"learn_gen",
".",
"loss_func",
",",
"learn_crit",
".",
"loss_func",
",",
"weights_gen",
"=",
"weights_gen",
")",
"return",
"cls",
"(",
"learn_gen",
".",
"data",
",",
"learn_gen",
".",
"model",
",",
"learn_crit",
".",
"model",
",",
"*",
"losses",
",",
"switcher",
"=",
"switcher",
",",
"*",
"*",
"learn_kwargs",
")"
] |
Create a GAN from `learn_gen` and `learn_crit`.
|
[
"Create",
"a",
"GAN",
"from",
"learn_gen",
"and",
"learn_crit",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L219-L223
|
20,602
|
fastai/fastai
|
fastai/vision/gan.py
|
GANLearner.wgan
|
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)
|
python
|
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",
")",
":",
"return",
"cls",
"(",
"data",
",",
"generator",
",",
"critic",
",",
"NoopLoss",
"(",
")",
",",
"WassersteinLoss",
"(",
")",
",",
"switcher",
"=",
"switcher",
",",
"clip",
"=",
"clip",
",",
"*",
"*",
"learn_kwargs",
")"
] |
Create a WGAN from `data`, `generator` and `critic`.
|
[
"Create",
"a",
"WGAN",
"from",
"data",
"generator",
"and",
"critic",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L226-L228
|
20,603
|
fastai/fastai
|
fastai/vision/gan.py
|
GANDiscriminativeLR.on_batch_begin
|
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
|
python
|
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",
")",
":",
"if",
"not",
"self",
".",
"learn",
".",
"gan_trainer",
".",
"gen_mode",
"and",
"train",
":",
"self",
".",
"learn",
".",
"opt",
".",
"lr",
"*=",
"self",
".",
"mult_lr"
] |
Multiply the current lr if necessary.
|
[
"Multiply",
"the",
"current",
"lr",
"if",
"necessary",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L284-L286
|
20,604
|
fastai/fastai
|
fastai/vision/gan.py
|
GANDiscriminativeLR.on_step_end
|
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
|
python
|
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",
")",
":",
"if",
"not",
"self",
".",
"learn",
".",
"gan_trainer",
".",
"gen_mode",
":",
"self",
".",
"learn",
".",
"opt",
".",
"lr",
"/=",
"self",
".",
"mult_lr"
] |
Put the LR back to its value if necessary.
|
[
"Put",
"the",
"LR",
"back",
"to",
"its",
"value",
"if",
"necessary",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/gan.py#L288-L290
|
20,605
|
fastai/fastai
|
fastai/vision/models/unet.py
|
_get_sfs_idxs
|
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] + sfs_idxs
return sfs_idxs
|
python
|
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] + sfs_idxs
return sfs_idxs
|
[
"def",
"_get_sfs_idxs",
"(",
"sizes",
":",
"Sizes",
")",
"->",
"List",
"[",
"int",
"]",
":",
"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",
"]",
"+",
"sfs_idxs",
"return",
"sfs_idxs"
] |
Get the indexes of the layers where the size of the activation changes.
|
[
"Get",
"the",
"indexes",
"of",
"the",
"layers",
"where",
"the",
"size",
"of",
"the",
"activation",
"changes",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/models/unet.py#L7-L12
|
20,606
|
fastai/fastai
|
fastai/widgets/image_downloader.py
|
_url_params
|
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(f"""Unexpected size argument value: {size}.
See `widgets.image_downloader._img_sizes` for supported sizes.""")
if format not in _fmts:
raise RuntimeError(f"Unexpected image file format: {format}. Use jpg, gif, png, bmp, svg, webp, or ico.")
return "&tbs=" + _img_sizes[size] + "," + _fmts[format]
|
python
|
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(f"""Unexpected size argument value: {size}.
See `widgets.image_downloader._img_sizes` for supported sizes.""")
if format not in _fmts:
raise RuntimeError(f"Unexpected image file format: {format}. Use jpg, gif, png, bmp, svg, webp, or ico.")
return "&tbs=" + _img_sizes[size] + "," + _fmts[format]
|
[
"def",
"_url_params",
"(",
"size",
":",
"str",
"=",
"'>400*300'",
",",
"format",
":",
"str",
"=",
"'jpg'",
")",
"->",
"str",
":",
"_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",
"(",
"f\"\"\"Unexpected size argument value: {size}.\n See `widgets.image_downloader._img_sizes` for supported sizes.\"\"\"",
")",
"if",
"format",
"not",
"in",
"_fmts",
":",
"raise",
"RuntimeError",
"(",
"f\"Unexpected image file format: {format}. Use jpg, gif, png, bmp, svg, webp, or ico.\"",
")",
"return",
"\"&tbs=\"",
"+",
"_img_sizes",
"[",
"size",
"]",
"+",
"\",\"",
"+",
"_fmts",
"[",
"format",
"]"
] |
Build Google Images Search Url params and return them as a string.
|
[
"Build",
"Google",
"Images",
"Search",
"Url",
"params",
"and",
"return",
"them",
"as",
"a",
"string",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L93-L101
|
20,607
|
fastai/fastai
|
fastai/widgets/image_downloader.py
|
_search_url
|
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, format) + '&sa=X&ei=XosDVaCXD8TasATItgE&ved=0CAcQ_AUoAg')
|
python
|
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, format) + '&sa=X&ei=XosDVaCXD8TasATItgE&ved=0CAcQ_AUoAg')
|
[
"def",
"_search_url",
"(",
"search_term",
":",
"str",
",",
"size",
":",
"str",
"=",
"'>400*300'",
",",
"format",
":",
"str",
"=",
"'jpg'",
")",
"->",
"str",
":",
"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",
",",
"format",
")",
"+",
"'&sa=X&ei=XosDVaCXD8TasATItgE&ved=0CAcQ_AUoAg'",
")"
] |
Return a Google Images Search URL for a given search term.
|
[
"Return",
"a",
"Google",
"Images",
"Search",
"URL",
"for",
"a",
"given",
"search",
"term",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L103-L107
|
20,608
|
fastai/fastai
|
fastai/widgets/image_downloader.py
|
_download_images
|
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 system has enough CPU cores.
If something doesn't work, try setting up `max_workers=0` to debug.
"""
os.makedirs(Path(label_path), exist_ok=True)
parallel( partial(_download_single_image, label_path, timeout=timeout), img_tuples, max_workers=max_workers)
return get_image_files(label_path)
|
python
|
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 system has enough CPU cores.
If something doesn't work, try setting up `max_workers=0` to debug.
"""
os.makedirs(Path(label_path), exist_ok=True)
parallel( partial(_download_single_image, label_path, timeout=timeout), img_tuples, max_workers=max_workers)
return get_image_files(label_path)
|
[
"def",
"_download_images",
"(",
"label_path",
":",
"PathOrStr",
",",
"img_tuples",
":",
"list",
",",
"max_workers",
":",
"int",
"=",
"defaults",
".",
"cpus",
",",
"timeout",
":",
"int",
"=",
"4",
")",
"->",
"FilePathList",
":",
"os",
".",
"makedirs",
"(",
"Path",
"(",
"label_path",
")",
",",
"exist_ok",
"=",
"True",
")",
"parallel",
"(",
"partial",
"(",
"_download_single_image",
",",
"label_path",
",",
"timeout",
"=",
"timeout",
")",
",",
"img_tuples",
",",
"max_workers",
"=",
"max_workers",
")",
"return",
"get_image_files",
"(",
"label_path",
")"
] |
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.
|
[
"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",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L159-L168
|
20,609
|
fastai/fastai
|
fastai/widgets/image_downloader.py
|
ImageDownloader._init_ui
|
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=Layout(width='60px'))
self._size_input = Dropdown(options= _img_sizes.keys(), value='>400*300', layout=Layout(width='120px'))
self._download_button = Button(description="Search & Download", icon="download", layout=Layout(width='200px'))
self._download_button.on_click(self.on_download_button_click)
self._output = Output()
self._controls_pane = HBox([self._search_input, self._count_input, self._size_input, self._download_button],
layout=Layout(width='auto', height='40px'))
self._heading = ""
self._download_complete_heading = "<h3>Download complete. Here are a few images</h3>"
self._preview_header = widgets.HTML(self._heading, layout=Layout(height='60px'))
self._img_pane = Box(layout=Layout(display='inline'))
return VBox([self._controls_pane, self._preview_header, self._img_pane])
|
python
|
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=Layout(width='60px'))
self._size_input = Dropdown(options= _img_sizes.keys(), value='>400*300', layout=Layout(width='120px'))
self._download_button = Button(description="Search & Download", icon="download", layout=Layout(width='200px'))
self._download_button.on_click(self.on_download_button_click)
self._output = Output()
self._controls_pane = HBox([self._search_input, self._count_input, self._size_input, self._download_button],
layout=Layout(width='auto', height='40px'))
self._heading = ""
self._download_complete_heading = "<h3>Download complete. Here are a few images</h3>"
self._preview_header = widgets.HTML(self._heading, layout=Layout(height='60px'))
self._img_pane = Box(layout=Layout(display='inline'))
return VBox([self._controls_pane, self._preview_header, self._img_pane])
|
[
"def",
"_init_ui",
"(",
"self",
")",
"->",
"VBox",
":",
"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",
"=",
"Layout",
"(",
"width",
"=",
"'60px'",
")",
")",
"self",
".",
"_size_input",
"=",
"Dropdown",
"(",
"options",
"=",
"_img_sizes",
".",
"keys",
"(",
")",
",",
"value",
"=",
"'>400*300'",
",",
"layout",
"=",
"Layout",
"(",
"width",
"=",
"'120px'",
")",
")",
"self",
".",
"_download_button",
"=",
"Button",
"(",
"description",
"=",
"\"Search & Download\"",
",",
"icon",
"=",
"\"download\"",
",",
"layout",
"=",
"Layout",
"(",
"width",
"=",
"'200px'",
")",
")",
"self",
".",
"_download_button",
".",
"on_click",
"(",
"self",
".",
"on_download_button_click",
")",
"self",
".",
"_output",
"=",
"Output",
"(",
")",
"self",
".",
"_controls_pane",
"=",
"HBox",
"(",
"[",
"self",
".",
"_search_input",
",",
"self",
".",
"_count_input",
",",
"self",
".",
"_size_input",
",",
"self",
".",
"_download_button",
"]",
",",
"layout",
"=",
"Layout",
"(",
"width",
"=",
"'auto'",
",",
"height",
"=",
"'40px'",
")",
")",
"self",
".",
"_heading",
"=",
"\"\"",
"self",
".",
"_download_complete_heading",
"=",
"\"<h3>Download complete. Here are a few images</h3>\"",
"self",
".",
"_preview_header",
"=",
"widgets",
".",
"HTML",
"(",
"self",
".",
"_heading",
",",
"layout",
"=",
"Layout",
"(",
"height",
"=",
"'60px'",
")",
")",
"self",
".",
"_img_pane",
"=",
"Box",
"(",
"layout",
"=",
"Layout",
"(",
"display",
"=",
"'inline'",
")",
")",
"return",
"VBox",
"(",
"[",
"self",
".",
"_controls_pane",
",",
"self",
".",
"_preview_header",
",",
"self",
".",
"_img_pane",
"]",
")"
] |
Initialize the widget UI and return the UI.
|
[
"Initialize",
"the",
"widget",
"UI",
"and",
"return",
"the",
"UI",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L27-L42
|
20,610
|
fastai/fastai
|
fastai/widgets/image_downloader.py
|
ImageDownloader.clear_imgs
|
def clear_imgs(self) -> None:
"Clear the widget's images preview pane."
self._preview_header.value = self._heading
self._img_pane.children = tuple()
|
python
|
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",
":",
"self",
".",
"_preview_header",
".",
"value",
"=",
"self",
".",
"_heading",
"self",
".",
"_img_pane",
".",
"children",
"=",
"tuple",
"(",
")"
] |
Clear the widget's images preview pane.
|
[
"Clear",
"the",
"widget",
"s",
"images",
"preview",
"pane",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L48-L51
|
20,611
|
fastai/fastai
|
fastai/widgets/image_downloader.py
|
ImageDownloader.validate_search_input
|
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()
|
python
|
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",
":",
"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.
|
[
"Check",
"if",
"input",
"value",
"is",
"empty",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L53-L58
|
20,612
|
fastai/fastai
|
fastai/widgets/image_downloader.py
|
ImageDownloader.display_images_widgets
|
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)
|
python
|
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",
":",
"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
|
[
"Display",
"a",
"few",
"preview",
"images",
"in",
"the",
"notebook"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L72-L75
|
20,613
|
fastai/fastai
|
fastai/callbacks/lr_finder.py
|
LRFinder.on_train_begin
|
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.
return {'skip_validate': True}
|
python
|
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.
return {'skip_validate': True}
|
[
"def",
"on_train_begin",
"(",
"self",
",",
"pbar",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"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.",
"return",
"{",
"'skip_validate'",
":",
"True",
"}"
] |
Initialize optimizer and learner hyperparameters.
|
[
"Initialize",
"optimizer",
"and",
"learner",
"hyperparameters",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/lr_finder.py#L16-L23
|
20,614
|
fastai/fastai
|
fastai/callbacks/lr_finder.py
|
LRFinder.on_batch_end
|
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 and (smooth_loss > 4*self.best_loss or torch.isnan(smooth_loss))):
#We use the smoothed loss to decide on the stopping since it's less shaky.
return {'stop_epoch': True, 'stop_training': True}
|
python
|
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 and (smooth_loss > 4*self.best_loss or torch.isnan(smooth_loss))):
#We use the smoothed loss to decide on the stopping since it's less shaky.
return {'stop_epoch': True, 'stop_training': True}
|
[
"def",
"on_batch_end",
"(",
"self",
",",
"iteration",
":",
"int",
",",
"smooth_loss",
":",
"TensorOrNumber",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"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",
"and",
"(",
"smooth_loss",
">",
"4",
"*",
"self",
".",
"best_loss",
"or",
"torch",
".",
"isnan",
"(",
"smooth_loss",
")",
")",
")",
":",
"#We use the smoothed loss to decide on the stopping since it's less shaky.",
"return",
"{",
"'stop_epoch'",
":",
"True",
",",
"'stop_training'",
":",
"True",
"}"
] |
Determine if loss has runaway and we should stop.
|
[
"Determine",
"if",
"loss",
"has",
"runaway",
"and",
"we",
"should",
"stop",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/lr_finder.py#L25-L31
|
20,615
|
fastai/fastai
|
fastai/callbacks/lr_finder.py
|
LRFinder.on_train_end
|
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()
print('LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.')
|
python
|
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()
print('LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.')
|
[
"def",
"on_train_end",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"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",
"(",
")",
"print",
"(",
"'LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.'",
")"
] |
Cleanup learn model weights disturbed during LRFinder exploration.
|
[
"Cleanup",
"learn",
"model",
"weights",
"disturbed",
"during",
"LRFinder",
"exploration",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/lr_finder.py#L33-L39
|
20,616
|
fastai/fastai
|
old/fastai/rnn_reg.py
|
WeightDrop._setup
|
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
"""
if isinstance(self.module, torch.nn.RNNBase): self.module.flatten_parameters = noop
for name_w in self.weights:
w = getattr(self.module, name_w)
del self.module._parameters[name_w]
self.module.register_parameter(name_w + '_raw', nn.Parameter(w.data))
|
python
|
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
"""
if isinstance(self.module, torch.nn.RNNBase): self.module.flatten_parameters = noop
for name_w in self.weights:
w = getattr(self.module, name_w)
del self.module._parameters[name_w]
self.module.register_parameter(name_w + '_raw', nn.Parameter(w.data))
|
[
"def",
"_setup",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"module",
",",
"torch",
".",
"nn",
".",
"RNNBase",
")",
":",
"self",
".",
"module",
".",
"flatten_parameters",
"=",
"noop",
"for",
"name_w",
"in",
"self",
".",
"weights",
":",
"w",
"=",
"getattr",
"(",
"self",
".",
"module",
",",
"name_w",
")",
"del",
"self",
".",
"module",
".",
"_parameters",
"[",
"name_w",
"]",
"self",
".",
"module",
".",
"register_parameter",
"(",
"name_w",
"+",
"'_raw'",
",",
"nn",
".",
"Parameter",
"(",
"w",
".",
"data",
")",
")"
] |
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",
"slightly",
"modified",
"name",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/rnn_reg.py#L79-L94
|
20,617
|
fastai/fastai
|
old/fastai/rnn_reg.py
|
WeightDrop._setweights
|
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')
w = torch.nn.functional.dropout(raw_w, p=self.dropout, training=self.training)
if hasattr(self.module, name_w):
delattr(self.module, name_w)
setattr(self.module, name_w, w)
|
python
|
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')
w = torch.nn.functional.dropout(raw_w, p=self.dropout, training=self.training)
if hasattr(self.module, name_w):
delattr(self.module, name_w)
setattr(self.module, name_w, w)
|
[
"def",
"_setweights",
"(",
"self",
")",
":",
"for",
"name_w",
"in",
"self",
".",
"weights",
":",
"raw_w",
"=",
"getattr",
"(",
"self",
".",
"module",
",",
"name_w",
"+",
"'_raw'",
")",
"w",
"=",
"torch",
".",
"nn",
".",
"functional",
".",
"dropout",
"(",
"raw_w",
",",
"p",
"=",
"self",
".",
"dropout",
",",
"training",
"=",
"self",
".",
"training",
")",
"if",
"hasattr",
"(",
"self",
".",
"module",
",",
"name_w",
")",
":",
"delattr",
"(",
"self",
".",
"module",
",",
"name_w",
")",
"setattr",
"(",
"self",
".",
"module",
",",
"name_w",
",",
"w",
")"
] |
Uses pytorch's built-in dropout function to apply dropout to the parameters of
the wrapped module.
Args:
None
Returns:
None
|
[
"Uses",
"pytorch",
"s",
"built",
"-",
"in",
"dropout",
"function",
"to",
"apply",
"dropout",
"to",
"the",
"parameters",
"of",
"the",
"wrapped",
"module",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/rnn_reg.py#L97-L111
|
20,618
|
fastai/fastai
|
fastai/basic_data.py
|
DataBunch.one_batch
|
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
try: x,y = next(iter(dl))
finally: self.num_workers = w
if detach: x,y = to_detach(x,cpu=cpu),to_detach(y,cpu=cpu)
norm = getattr(self,'norm',False)
if denorm and norm:
x = self.denorm(x)
if norm.keywords.get('do_y',False): y = self.denorm(y, do_x=True)
return x,y
|
python
|
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
try: x,y = next(iter(dl))
finally: self.num_workers = w
if detach: x,y = to_detach(x,cpu=cpu),to_detach(y,cpu=cpu)
norm = getattr(self,'norm',False)
if denorm and norm:
x = self.denorm(x)
if norm.keywords.get('do_y',False): y = self.denorm(y, do_x=True)
return x,y
|
[
"def",
"one_batch",
"(",
"self",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Train",
",",
"detach",
":",
"bool",
"=",
"True",
",",
"denorm",
":",
"bool",
"=",
"True",
",",
"cpu",
":",
"bool",
"=",
"True",
")",
"->",
"Collection",
"[",
"Tensor",
"]",
":",
"dl",
"=",
"self",
".",
"dl",
"(",
"ds_type",
")",
"w",
"=",
"self",
".",
"num_workers",
"self",
".",
"num_workers",
"=",
"0",
"try",
":",
"x",
",",
"y",
"=",
"next",
"(",
"iter",
"(",
"dl",
")",
")",
"finally",
":",
"self",
".",
"num_workers",
"=",
"w",
"if",
"detach",
":",
"x",
",",
"y",
"=",
"to_detach",
"(",
"x",
",",
"cpu",
"=",
"cpu",
")",
",",
"to_detach",
"(",
"y",
",",
"cpu",
"=",
"cpu",
")",
"norm",
"=",
"getattr",
"(",
"self",
",",
"'norm'",
",",
"False",
")",
"if",
"denorm",
"and",
"norm",
":",
"x",
"=",
"self",
".",
"denorm",
"(",
"x",
")",
"if",
"norm",
".",
"keywords",
".",
"get",
"(",
"'do_y'",
",",
"False",
")",
":",
"y",
"=",
"self",
".",
"denorm",
"(",
"y",
",",
"do_x",
"=",
"True",
")",
"return",
"x",
",",
"y"
] |
Get one batch from the data loader of `ds_type`. Optionally `detach` and `denorm`.
|
[
"Get",
"one",
"batch",
"from",
"the",
"data",
"loader",
"of",
"ds_type",
".",
"Optionally",
"detach",
"and",
"denorm",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L163-L175
|
20,619
|
fastai/fastai
|
fastai/basic_data.py
|
DataBunch.one_item
|
def one_item(self, item, detach:bool=False, denorm:bool=False, cpu:bool=False):
"Get `item` into a batch. Optionally `detach` and `denorm`."
ds = self.single_ds
with ds.set_item(item):
return self.one_batch(ds_type=DatasetType.Single, detach=detach, denorm=denorm, cpu=cpu)
|
python
|
def one_item(self, item, detach:bool=False, denorm:bool=False, cpu:bool=False):
"Get `item` into a batch. Optionally `detach` and `denorm`."
ds = self.single_ds
with ds.set_item(item):
return self.one_batch(ds_type=DatasetType.Single, detach=detach, denorm=denorm, cpu=cpu)
|
[
"def",
"one_item",
"(",
"self",
",",
"item",
",",
"detach",
":",
"bool",
"=",
"False",
",",
"denorm",
":",
"bool",
"=",
"False",
",",
"cpu",
":",
"bool",
"=",
"False",
")",
":",
"ds",
"=",
"self",
".",
"single_ds",
"with",
"ds",
".",
"set_item",
"(",
"item",
")",
":",
"return",
"self",
".",
"one_batch",
"(",
"ds_type",
"=",
"DatasetType",
".",
"Single",
",",
"detach",
"=",
"detach",
",",
"denorm",
"=",
"denorm",
",",
"cpu",
"=",
"cpu",
")"
] |
Get `item` into a batch. Optionally `detach` and `denorm`.
|
[
"Get",
"item",
"into",
"a",
"batch",
".",
"Optionally",
"detach",
"and",
"denorm",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L177-L181
|
20,620
|
fastai/fastai
|
fastai/basic_data.py
|
DataBunch.show_batch
|
def show_batch(self, rows:int=5, ds_type:DatasetType=DatasetType.Train, reverse:bool=False, **kwargs)->None:
"Show a batch of data in `ds_type` on a few `rows`."
x,y = self.one_batch(ds_type, True, True)
if reverse: x,y = x.flip(0),y.flip(0)
n_items = rows **2 if self.train_ds.x._square_show else rows
if self.dl(ds_type).batch_size < n_items: n_items = self.dl(ds_type).batch_size
xs = [self.train_ds.x.reconstruct(grab_idx(x, i)) for i in range(n_items)]
#TODO: get rid of has_arg if possible
if has_arg(self.train_ds.y.reconstruct, 'x'):
ys = [self.train_ds.y.reconstruct(grab_idx(y, i), x=x) for i,x in enumerate(xs)]
else : ys = [self.train_ds.y.reconstruct(grab_idx(y, i)) for i in range(n_items)]
self.train_ds.x.show_xys(xs, ys, **kwargs)
|
python
|
def show_batch(self, rows:int=5, ds_type:DatasetType=DatasetType.Train, reverse:bool=False, **kwargs)->None:
"Show a batch of data in `ds_type` on a few `rows`."
x,y = self.one_batch(ds_type, True, True)
if reverse: x,y = x.flip(0),y.flip(0)
n_items = rows **2 if self.train_ds.x._square_show else rows
if self.dl(ds_type).batch_size < n_items: n_items = self.dl(ds_type).batch_size
xs = [self.train_ds.x.reconstruct(grab_idx(x, i)) for i in range(n_items)]
#TODO: get rid of has_arg if possible
if has_arg(self.train_ds.y.reconstruct, 'x'):
ys = [self.train_ds.y.reconstruct(grab_idx(y, i), x=x) for i,x in enumerate(xs)]
else : ys = [self.train_ds.y.reconstruct(grab_idx(y, i)) for i in range(n_items)]
self.train_ds.x.show_xys(xs, ys, **kwargs)
|
[
"def",
"show_batch",
"(",
"self",
",",
"rows",
":",
"int",
"=",
"5",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Train",
",",
"reverse",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"x",
",",
"y",
"=",
"self",
".",
"one_batch",
"(",
"ds_type",
",",
"True",
",",
"True",
")",
"if",
"reverse",
":",
"x",
",",
"y",
"=",
"x",
".",
"flip",
"(",
"0",
")",
",",
"y",
".",
"flip",
"(",
"0",
")",
"n_items",
"=",
"rows",
"**",
"2",
"if",
"self",
".",
"train_ds",
".",
"x",
".",
"_square_show",
"else",
"rows",
"if",
"self",
".",
"dl",
"(",
"ds_type",
")",
".",
"batch_size",
"<",
"n_items",
":",
"n_items",
"=",
"self",
".",
"dl",
"(",
"ds_type",
")",
".",
"batch_size",
"xs",
"=",
"[",
"self",
".",
"train_ds",
".",
"x",
".",
"reconstruct",
"(",
"grab_idx",
"(",
"x",
",",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"n_items",
")",
"]",
"#TODO: get rid of has_arg if possible",
"if",
"has_arg",
"(",
"self",
".",
"train_ds",
".",
"y",
".",
"reconstruct",
",",
"'x'",
")",
":",
"ys",
"=",
"[",
"self",
".",
"train_ds",
".",
"y",
".",
"reconstruct",
"(",
"grab_idx",
"(",
"y",
",",
"i",
")",
",",
"x",
"=",
"x",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"xs",
")",
"]",
"else",
":",
"ys",
"=",
"[",
"self",
".",
"train_ds",
".",
"y",
".",
"reconstruct",
"(",
"grab_idx",
"(",
"y",
",",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"n_items",
")",
"]",
"self",
".",
"train_ds",
".",
"x",
".",
"show_xys",
"(",
"xs",
",",
"ys",
",",
"*",
"*",
"kwargs",
")"
] |
Show a batch of data in `ds_type` on a few `rows`.
|
[
"Show",
"a",
"batch",
"of",
"data",
"in",
"ds_type",
"on",
"a",
"few",
"rows",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L183-L194
|
20,621
|
fastai/fastai
|
fastai/basic_data.py
|
DataBunch.sanity_check
|
def sanity_check(self):
"Check the underlying data in the training set can be properly loaded."
final_message = "You can deactivate this warning by passing `no_check=True`."
if not hasattr(self.train_ds, 'items') or len(self.train_ds.items) == 0 or not hasattr(self.train_dl, 'batch_sampler'): return
if len(self.train_dl) == 0:
warn(f"""Your training dataloader is empty, you have only {len(self.train_dl.dataset)} items in your training set.
Your batch size is {self.train_dl.batch_size}, you should lower it.""")
print(final_message)
return
idx = next(iter(self.train_dl.batch_sampler))
samples,fails = [],[]
for i in idx:
try: samples.append(self.train_dl.dataset[i])
except: fails.append(i)
if len(fails) > 0:
warn_msg = "There seems to be something wrong with your dataset, for example, in the first batch can't access"
if len(fails) == len(idx):
warn_msg += f" any element of self.train_ds.\nTried: {show_some(idx)}"
else:
warn_msg += f" these elements in self.train_ds: {show_some(fails)}"
warn(warn_msg)
print(final_message)
return
try: batch = self.collate_fn(samples)
except:
message = "It's not possible to collate samples of your dataset together in a batch."
try:
shapes = [[o[i].data.shape for o in samples] for i in range(2)]
message += f'\nShapes of the inputs/targets:\n{shapes}'
except: pass
warn(message)
print(final_message)
|
python
|
def sanity_check(self):
"Check the underlying data in the training set can be properly loaded."
final_message = "You can deactivate this warning by passing `no_check=True`."
if not hasattr(self.train_ds, 'items') or len(self.train_ds.items) == 0 or not hasattr(self.train_dl, 'batch_sampler'): return
if len(self.train_dl) == 0:
warn(f"""Your training dataloader is empty, you have only {len(self.train_dl.dataset)} items in your training set.
Your batch size is {self.train_dl.batch_size}, you should lower it.""")
print(final_message)
return
idx = next(iter(self.train_dl.batch_sampler))
samples,fails = [],[]
for i in idx:
try: samples.append(self.train_dl.dataset[i])
except: fails.append(i)
if len(fails) > 0:
warn_msg = "There seems to be something wrong with your dataset, for example, in the first batch can't access"
if len(fails) == len(idx):
warn_msg += f" any element of self.train_ds.\nTried: {show_some(idx)}"
else:
warn_msg += f" these elements in self.train_ds: {show_some(fails)}"
warn(warn_msg)
print(final_message)
return
try: batch = self.collate_fn(samples)
except:
message = "It's not possible to collate samples of your dataset together in a batch."
try:
shapes = [[o[i].data.shape for o in samples] for i in range(2)]
message += f'\nShapes of the inputs/targets:\n{shapes}'
except: pass
warn(message)
print(final_message)
|
[
"def",
"sanity_check",
"(",
"self",
")",
":",
"final_message",
"=",
"\"You can deactivate this warning by passing `no_check=True`.\"",
"if",
"not",
"hasattr",
"(",
"self",
".",
"train_ds",
",",
"'items'",
")",
"or",
"len",
"(",
"self",
".",
"train_ds",
".",
"items",
")",
"==",
"0",
"or",
"not",
"hasattr",
"(",
"self",
".",
"train_dl",
",",
"'batch_sampler'",
")",
":",
"return",
"if",
"len",
"(",
"self",
".",
"train_dl",
")",
"==",
"0",
":",
"warn",
"(",
"f\"\"\"Your training dataloader is empty, you have only {len(self.train_dl.dataset)} items in your training set.\n Your batch size is {self.train_dl.batch_size}, you should lower it.\"\"\"",
")",
"print",
"(",
"final_message",
")",
"return",
"idx",
"=",
"next",
"(",
"iter",
"(",
"self",
".",
"train_dl",
".",
"batch_sampler",
")",
")",
"samples",
",",
"fails",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"i",
"in",
"idx",
":",
"try",
":",
"samples",
".",
"append",
"(",
"self",
".",
"train_dl",
".",
"dataset",
"[",
"i",
"]",
")",
"except",
":",
"fails",
".",
"append",
"(",
"i",
")",
"if",
"len",
"(",
"fails",
")",
">",
"0",
":",
"warn_msg",
"=",
"\"There seems to be something wrong with your dataset, for example, in the first batch can't access\"",
"if",
"len",
"(",
"fails",
")",
"==",
"len",
"(",
"idx",
")",
":",
"warn_msg",
"+=",
"f\" any element of self.train_ds.\\nTried: {show_some(idx)}\"",
"else",
":",
"warn_msg",
"+=",
"f\" these elements in self.train_ds: {show_some(fails)}\"",
"warn",
"(",
"warn_msg",
")",
"print",
"(",
"final_message",
")",
"return",
"try",
":",
"batch",
"=",
"self",
".",
"collate_fn",
"(",
"samples",
")",
"except",
":",
"message",
"=",
"\"It's not possible to collate samples of your dataset together in a batch.\"",
"try",
":",
"shapes",
"=",
"[",
"[",
"o",
"[",
"i",
"]",
".",
"data",
".",
"shape",
"for",
"o",
"in",
"samples",
"]",
"for",
"i",
"in",
"range",
"(",
"2",
")",
"]",
"message",
"+=",
"f'\\nShapes of the inputs/targets:\\n{shapes}'",
"except",
":",
"pass",
"warn",
"(",
"message",
")",
"print",
"(",
"final_message",
")"
] |
Check the underlying data in the training set can be properly loaded.
|
[
"Check",
"the",
"underlying",
"data",
"in",
"the",
"training",
"set",
"can",
"be",
"properly",
"loaded",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L239-L270
|
20,622
|
fastai/fastai
|
fastai/train.py
|
one_cycle_scheduler
|
def one_cycle_scheduler(lr_max:float, **kwargs:Any)->OneCycleScheduler:
"Instantiate a `OneCycleScheduler` with `lr_max`."
return partial(OneCycleScheduler, lr_max=lr_max, **kwargs)
|
python
|
def one_cycle_scheduler(lr_max:float, **kwargs:Any)->OneCycleScheduler:
"Instantiate a `OneCycleScheduler` with `lr_max`."
return partial(OneCycleScheduler, lr_max=lr_max, **kwargs)
|
[
"def",
"one_cycle_scheduler",
"(",
"lr_max",
":",
"float",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"OneCycleScheduler",
":",
"return",
"partial",
"(",
"OneCycleScheduler",
",",
"lr_max",
"=",
"lr_max",
",",
"*",
"*",
"kwargs",
")"
] |
Instantiate a `OneCycleScheduler` with `lr_max`.
|
[
"Instantiate",
"a",
"OneCycleScheduler",
"with",
"lr_max",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L10-L12
|
20,623
|
fastai/fastai
|
fastai/train.py
|
fit_one_cycle
|
def fit_one_cycle(learn:Learner, cyc_len:int, max_lr:Union[Floats,slice]=defaults.lr,
moms:Tuple[float,float]=(0.95,0.85), div_factor:float=25., pct_start:float=0.3, final_div:float=None,
wd:float=None, callbacks:Optional[CallbackList]=None, tot_epochs:int=None, start_epoch:int=None)->None:
"Fit a model following the 1cycle policy."
max_lr = learn.lr_range(max_lr)
callbacks = listify(callbacks)
callbacks.append(OneCycleScheduler(learn, max_lr, moms=moms, div_factor=div_factor, pct_start=pct_start,
final_div=final_div, tot_epochs=tot_epochs, start_epoch=start_epoch))
learn.fit(cyc_len, max_lr, wd=wd, callbacks=callbacks)
|
python
|
def fit_one_cycle(learn:Learner, cyc_len:int, max_lr:Union[Floats,slice]=defaults.lr,
moms:Tuple[float,float]=(0.95,0.85), div_factor:float=25., pct_start:float=0.3, final_div:float=None,
wd:float=None, callbacks:Optional[CallbackList]=None, tot_epochs:int=None, start_epoch:int=None)->None:
"Fit a model following the 1cycle policy."
max_lr = learn.lr_range(max_lr)
callbacks = listify(callbacks)
callbacks.append(OneCycleScheduler(learn, max_lr, moms=moms, div_factor=div_factor, pct_start=pct_start,
final_div=final_div, tot_epochs=tot_epochs, start_epoch=start_epoch))
learn.fit(cyc_len, max_lr, wd=wd, callbacks=callbacks)
|
[
"def",
"fit_one_cycle",
"(",
"learn",
":",
"Learner",
",",
"cyc_len",
":",
"int",
",",
"max_lr",
":",
"Union",
"[",
"Floats",
",",
"slice",
"]",
"=",
"defaults",
".",
"lr",
",",
"moms",
":",
"Tuple",
"[",
"float",
",",
"float",
"]",
"=",
"(",
"0.95",
",",
"0.85",
")",
",",
"div_factor",
":",
"float",
"=",
"25.",
",",
"pct_start",
":",
"float",
"=",
"0.3",
",",
"final_div",
":",
"float",
"=",
"None",
",",
"wd",
":",
"float",
"=",
"None",
",",
"callbacks",
":",
"Optional",
"[",
"CallbackList",
"]",
"=",
"None",
",",
"tot_epochs",
":",
"int",
"=",
"None",
",",
"start_epoch",
":",
"int",
"=",
"None",
")",
"->",
"None",
":",
"max_lr",
"=",
"learn",
".",
"lr_range",
"(",
"max_lr",
")",
"callbacks",
"=",
"listify",
"(",
"callbacks",
")",
"callbacks",
".",
"append",
"(",
"OneCycleScheduler",
"(",
"learn",
",",
"max_lr",
",",
"moms",
"=",
"moms",
",",
"div_factor",
"=",
"div_factor",
",",
"pct_start",
"=",
"pct_start",
",",
"final_div",
"=",
"final_div",
",",
"tot_epochs",
"=",
"tot_epochs",
",",
"start_epoch",
"=",
"start_epoch",
")",
")",
"learn",
".",
"fit",
"(",
"cyc_len",
",",
"max_lr",
",",
"wd",
"=",
"wd",
",",
"callbacks",
"=",
"callbacks",
")"
] |
Fit a model following the 1cycle policy.
|
[
"Fit",
"a",
"model",
"following",
"the",
"1cycle",
"policy",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L14-L22
|
20,624
|
fastai/fastai
|
fastai/train.py
|
lr_find
|
def lr_find(learn:Learner, start_lr:Floats=1e-7, end_lr:Floats=10, num_it:int=100, stop_div:bool=True, wd:float=None):
"Explore lr from `start_lr` to `end_lr` over `num_it` iterations in `learn`. If `stop_div`, stops when loss diverges."
start_lr = learn.lr_range(start_lr)
start_lr = np.array(start_lr) if is_listy(start_lr) else start_lr
end_lr = learn.lr_range(end_lr)
end_lr = np.array(end_lr) if is_listy(end_lr) else end_lr
cb = LRFinder(learn, start_lr, end_lr, num_it, stop_div)
epochs = int(np.ceil(num_it/len(learn.data.train_dl)))
learn.fit(epochs, start_lr, callbacks=[cb], wd=wd)
|
python
|
def lr_find(learn:Learner, start_lr:Floats=1e-7, end_lr:Floats=10, num_it:int=100, stop_div:bool=True, wd:float=None):
"Explore lr from `start_lr` to `end_lr` over `num_it` iterations in `learn`. If `stop_div`, stops when loss diverges."
start_lr = learn.lr_range(start_lr)
start_lr = np.array(start_lr) if is_listy(start_lr) else start_lr
end_lr = learn.lr_range(end_lr)
end_lr = np.array(end_lr) if is_listy(end_lr) else end_lr
cb = LRFinder(learn, start_lr, end_lr, num_it, stop_div)
epochs = int(np.ceil(num_it/len(learn.data.train_dl)))
learn.fit(epochs, start_lr, callbacks=[cb], wd=wd)
|
[
"def",
"lr_find",
"(",
"learn",
":",
"Learner",
",",
"start_lr",
":",
"Floats",
"=",
"1e-7",
",",
"end_lr",
":",
"Floats",
"=",
"10",
",",
"num_it",
":",
"int",
"=",
"100",
",",
"stop_div",
":",
"bool",
"=",
"True",
",",
"wd",
":",
"float",
"=",
"None",
")",
":",
"start_lr",
"=",
"learn",
".",
"lr_range",
"(",
"start_lr",
")",
"start_lr",
"=",
"np",
".",
"array",
"(",
"start_lr",
")",
"if",
"is_listy",
"(",
"start_lr",
")",
"else",
"start_lr",
"end_lr",
"=",
"learn",
".",
"lr_range",
"(",
"end_lr",
")",
"end_lr",
"=",
"np",
".",
"array",
"(",
"end_lr",
")",
"if",
"is_listy",
"(",
"end_lr",
")",
"else",
"end_lr",
"cb",
"=",
"LRFinder",
"(",
"learn",
",",
"start_lr",
",",
"end_lr",
",",
"num_it",
",",
"stop_div",
")",
"epochs",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"num_it",
"/",
"len",
"(",
"learn",
".",
"data",
".",
"train_dl",
")",
")",
")",
"learn",
".",
"fit",
"(",
"epochs",
",",
"start_lr",
",",
"callbacks",
"=",
"[",
"cb",
"]",
",",
"wd",
"=",
"wd",
")"
] |
Explore lr from `start_lr` to `end_lr` over `num_it` iterations in `learn`. If `stop_div`, stops when loss diverges.
|
[
"Explore",
"lr",
"from",
"start_lr",
"to",
"end_lr",
"over",
"num_it",
"iterations",
"in",
"learn",
".",
"If",
"stop_div",
"stops",
"when",
"loss",
"diverges",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L24-L32
|
20,625
|
fastai/fastai
|
fastai/train.py
|
to_fp16
|
def to_fp16(learn:Learner, loss_scale:float=None, max_noskip:int=1000, dynamic:bool=True, clip:float=None,
flat_master:bool=False, max_scale:float=2**24)->Learner:
"Put `learn` in FP16 precision mode."
learn.to_fp32()
learn.model = model2half(learn.model)
learn.data.add_tfm(batch_to_half)
learn.mp_cb = MixedPrecision(learn, loss_scale=loss_scale, max_noskip=max_noskip, dynamic=dynamic, clip=clip,
flat_master=flat_master, max_scale=max_scale)
learn.callbacks.append(learn.mp_cb)
return learn
|
python
|
def to_fp16(learn:Learner, loss_scale:float=None, max_noskip:int=1000, dynamic:bool=True, clip:float=None,
flat_master:bool=False, max_scale:float=2**24)->Learner:
"Put `learn` in FP16 precision mode."
learn.to_fp32()
learn.model = model2half(learn.model)
learn.data.add_tfm(batch_to_half)
learn.mp_cb = MixedPrecision(learn, loss_scale=loss_scale, max_noskip=max_noskip, dynamic=dynamic, clip=clip,
flat_master=flat_master, max_scale=max_scale)
learn.callbacks.append(learn.mp_cb)
return learn
|
[
"def",
"to_fp16",
"(",
"learn",
":",
"Learner",
",",
"loss_scale",
":",
"float",
"=",
"None",
",",
"max_noskip",
":",
"int",
"=",
"1000",
",",
"dynamic",
":",
"bool",
"=",
"True",
",",
"clip",
":",
"float",
"=",
"None",
",",
"flat_master",
":",
"bool",
"=",
"False",
",",
"max_scale",
":",
"float",
"=",
"2",
"**",
"24",
")",
"->",
"Learner",
":",
"learn",
".",
"to_fp32",
"(",
")",
"learn",
".",
"model",
"=",
"model2half",
"(",
"learn",
".",
"model",
")",
"learn",
".",
"data",
".",
"add_tfm",
"(",
"batch_to_half",
")",
"learn",
".",
"mp_cb",
"=",
"MixedPrecision",
"(",
"learn",
",",
"loss_scale",
"=",
"loss_scale",
",",
"max_noskip",
"=",
"max_noskip",
",",
"dynamic",
"=",
"dynamic",
",",
"clip",
"=",
"clip",
",",
"flat_master",
"=",
"flat_master",
",",
"max_scale",
"=",
"max_scale",
")",
"learn",
".",
"callbacks",
".",
"append",
"(",
"learn",
".",
"mp_cb",
")",
"return",
"learn"
] |
Put `learn` in FP16 precision mode.
|
[
"Put",
"learn",
"in",
"FP16",
"precision",
"mode",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L34-L43
|
20,626
|
fastai/fastai
|
fastai/train.py
|
to_fp32
|
def to_fp32(learn:Learner):
"Put `learn` back to FP32 precision mode."
learn.data.remove_tfm(batch_to_half)
for cb in learn.callbacks:
if isinstance(cb, MixedPrecision): learn.callbacks.remove(cb)
learn.model = learn.model.float()
return learn
|
python
|
def to_fp32(learn:Learner):
"Put `learn` back to FP32 precision mode."
learn.data.remove_tfm(batch_to_half)
for cb in learn.callbacks:
if isinstance(cb, MixedPrecision): learn.callbacks.remove(cb)
learn.model = learn.model.float()
return learn
|
[
"def",
"to_fp32",
"(",
"learn",
":",
"Learner",
")",
":",
"learn",
".",
"data",
".",
"remove_tfm",
"(",
"batch_to_half",
")",
"for",
"cb",
"in",
"learn",
".",
"callbacks",
":",
"if",
"isinstance",
"(",
"cb",
",",
"MixedPrecision",
")",
":",
"learn",
".",
"callbacks",
".",
"remove",
"(",
"cb",
")",
"learn",
".",
"model",
"=",
"learn",
".",
"model",
".",
"float",
"(",
")",
"return",
"learn"
] |
Put `learn` back to FP32 precision mode.
|
[
"Put",
"learn",
"back",
"to",
"FP32",
"precision",
"mode",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L45-L51
|
20,627
|
fastai/fastai
|
fastai/train.py
|
clip_grad
|
def clip_grad(learn:Learner, clip:float=0.1)->Learner:
"Add gradient clipping of `clip` during training."
learn.callback_fns.append(partial(GradientClipping, clip=clip))
return learn
|
python
|
def clip_grad(learn:Learner, clip:float=0.1)->Learner:
"Add gradient clipping of `clip` during training."
learn.callback_fns.append(partial(GradientClipping, clip=clip))
return learn
|
[
"def",
"clip_grad",
"(",
"learn",
":",
"Learner",
",",
"clip",
":",
"float",
"=",
"0.1",
")",
"->",
"Learner",
":",
"learn",
".",
"callback_fns",
".",
"append",
"(",
"partial",
"(",
"GradientClipping",
",",
"clip",
"=",
"clip",
")",
")",
"return",
"learn"
] |
Add gradient clipping of `clip` during training.
|
[
"Add",
"gradient",
"clipping",
"of",
"clip",
"during",
"training",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L93-L96
|
20,628
|
fastai/fastai
|
fastai/train.py
|
_learner_interpret
|
def _learner_interpret(learn:Learner, ds_type:DatasetType=DatasetType.Valid):
"Create a `ClassificationInterpretation` object from `learner` on `ds_type` with `tta`."
return ClassificationInterpretation.from_learner(learn, ds_type=ds_type)
|
python
|
def _learner_interpret(learn:Learner, ds_type:DatasetType=DatasetType.Valid):
"Create a `ClassificationInterpretation` object from `learner` on `ds_type` with `tta`."
return ClassificationInterpretation.from_learner(learn, ds_type=ds_type)
|
[
"def",
"_learner_interpret",
"(",
"learn",
":",
"Learner",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Valid",
")",
":",
"return",
"ClassificationInterpretation",
".",
"from_learner",
"(",
"learn",
",",
"ds_type",
"=",
"ds_type",
")"
] |
Create a `ClassificationInterpretation` object from `learner` on `ds_type` with `tta`.
|
[
"Create",
"a",
"ClassificationInterpretation",
"object",
"from",
"learner",
"on",
"ds_type",
"with",
"tta",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L198-L200
|
20,629
|
fastai/fastai
|
fastai/train.py
|
ShowGraph.on_epoch_end
|
def on_epoch_end(self, n_epochs:int, last_metrics:MetricsList, **kwargs)->bool:
"If we have `last_metrics` plot them in our pbar graph"
if last_metrics is not None and np.any(last_metrics):
rec = self.learn.recorder
iters = range_of(rec.losses)
val_iter = np.array(rec.nb_batches).cumsum()
x_bounds = (0, (n_epochs - len(rec.nb_batches)) * rec.nb_batches[-1] + len(rec.losses))
y_bounds = (0, max((max(Tensor(rec.losses)), max(Tensor(rec.val_losses)))))
rec.pbar.update_graph([(iters, rec.losses), (val_iter, rec.val_losses)], x_bounds, y_bounds)
return {}
|
python
|
def on_epoch_end(self, n_epochs:int, last_metrics:MetricsList, **kwargs)->bool:
"If we have `last_metrics` plot them in our pbar graph"
if last_metrics is not None and np.any(last_metrics):
rec = self.learn.recorder
iters = range_of(rec.losses)
val_iter = np.array(rec.nb_batches).cumsum()
x_bounds = (0, (n_epochs - len(rec.nb_batches)) * rec.nb_batches[-1] + len(rec.losses))
y_bounds = (0, max((max(Tensor(rec.losses)), max(Tensor(rec.val_losses)))))
rec.pbar.update_graph([(iters, rec.losses), (val_iter, rec.val_losses)], x_bounds, y_bounds)
return {}
|
[
"def",
"on_epoch_end",
"(",
"self",
",",
"n_epochs",
":",
"int",
",",
"last_metrics",
":",
"MetricsList",
",",
"*",
"*",
"kwargs",
")",
"->",
"bool",
":",
"if",
"last_metrics",
"is",
"not",
"None",
"and",
"np",
".",
"any",
"(",
"last_metrics",
")",
":",
"rec",
"=",
"self",
".",
"learn",
".",
"recorder",
"iters",
"=",
"range_of",
"(",
"rec",
".",
"losses",
")",
"val_iter",
"=",
"np",
".",
"array",
"(",
"rec",
".",
"nb_batches",
")",
".",
"cumsum",
"(",
")",
"x_bounds",
"=",
"(",
"0",
",",
"(",
"n_epochs",
"-",
"len",
"(",
"rec",
".",
"nb_batches",
")",
")",
"*",
"rec",
".",
"nb_batches",
"[",
"-",
"1",
"]",
"+",
"len",
"(",
"rec",
".",
"losses",
")",
")",
"y_bounds",
"=",
"(",
"0",
",",
"max",
"(",
"(",
"max",
"(",
"Tensor",
"(",
"rec",
".",
"losses",
")",
")",
",",
"max",
"(",
"Tensor",
"(",
"rec",
".",
"val_losses",
")",
")",
")",
")",
")",
"rec",
".",
"pbar",
".",
"update_graph",
"(",
"[",
"(",
"iters",
",",
"rec",
".",
"losses",
")",
",",
"(",
"val_iter",
",",
"rec",
".",
"val_losses",
")",
"]",
",",
"x_bounds",
",",
"y_bounds",
")",
"return",
"{",
"}"
] |
If we have `last_metrics` plot them in our pbar graph
|
[
"If",
"we",
"have",
"last_metrics",
"plot",
"them",
"in",
"our",
"pbar",
"graph"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L66-L75
|
20,630
|
fastai/fastai
|
fastai/train.py
|
GradientClipping.on_backward_end
|
def on_backward_end(self, **kwargs):
"Clip the gradient before the optimizer step."
if self.clip: nn.utils.clip_grad_norm_(self.learn.model.parameters(), self.clip)
|
python
|
def on_backward_end(self, **kwargs):
"Clip the gradient before the optimizer step."
if self.clip: nn.utils.clip_grad_norm_(self.learn.model.parameters(), self.clip)
|
[
"def",
"on_backward_end",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"clip",
":",
"nn",
".",
"utils",
".",
"clip_grad_norm_",
"(",
"self",
".",
"learn",
".",
"model",
".",
"parameters",
"(",
")",
",",
"self",
".",
"clip",
")"
] |
Clip the gradient before the optimizer step.
|
[
"Clip",
"the",
"gradient",
"before",
"the",
"optimizer",
"step",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L89-L91
|
20,631
|
fastai/fastai
|
fastai/train.py
|
AccumulateScheduler.on_train_begin
|
def on_train_begin(self, **kwargs):
"check if loss is reduction"
if hasattr(self.loss_func, "reduction") and (self.loss_func.reduction != "sum"):
warn("For better gradients consider 'reduction=sum'")
|
python
|
def on_train_begin(self, **kwargs):
"check if loss is reduction"
if hasattr(self.loss_func, "reduction") and (self.loss_func.reduction != "sum"):
warn("For better gradients consider 'reduction=sum'")
|
[
"def",
"on_train_begin",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"loss_func",
",",
"\"reduction\"",
")",
"and",
"(",
"self",
".",
"loss_func",
".",
"reduction",
"!=",
"\"sum\"",
")",
":",
"warn",
"(",
"\"For better gradients consider 'reduction=sum'\"",
")"
] |
check if loss is reduction
|
[
"check",
"if",
"loss",
"is",
"reduction"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L106-L109
|
20,632
|
fastai/fastai
|
fastai/train.py
|
AccumulateScheduler.on_batch_begin
|
def on_batch_begin(self, last_input, last_target, **kwargs):
"accumulate samples and batches"
self.acc_samples += last_input.shape[0]
self.acc_batches += 1
|
python
|
def on_batch_begin(self, last_input, last_target, **kwargs):
"accumulate samples and batches"
self.acc_samples += last_input.shape[0]
self.acc_batches += 1
|
[
"def",
"on_batch_begin",
"(",
"self",
",",
"last_input",
",",
"last_target",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"acc_samples",
"+=",
"last_input",
".",
"shape",
"[",
"0",
"]",
"self",
".",
"acc_batches",
"+=",
"1"
] |
accumulate samples and batches
|
[
"accumulate",
"samples",
"and",
"batches"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L115-L118
|
20,633
|
fastai/fastai
|
fastai/train.py
|
AccumulateScheduler.on_backward_end
|
def on_backward_end(self, **kwargs):
"accumulated step and reset samples, True will result in no stepping"
if (self.acc_batches % self.n_step) == 0:
for p in (self.learn.model.parameters()):
if p.requires_grad: p.grad.div_(self.acc_samples)
self.acc_samples = 0
else: return {'skip_step':True, 'skip_zero':True}
|
python
|
def on_backward_end(self, **kwargs):
"accumulated step and reset samples, True will result in no stepping"
if (self.acc_batches % self.n_step) == 0:
for p in (self.learn.model.parameters()):
if p.requires_grad: p.grad.div_(self.acc_samples)
self.acc_samples = 0
else: return {'skip_step':True, 'skip_zero':True}
|
[
"def",
"on_backward_end",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"self",
".",
"acc_batches",
"%",
"self",
".",
"n_step",
")",
"==",
"0",
":",
"for",
"p",
"in",
"(",
"self",
".",
"learn",
".",
"model",
".",
"parameters",
"(",
")",
")",
":",
"if",
"p",
".",
"requires_grad",
":",
"p",
".",
"grad",
".",
"div_",
"(",
"self",
".",
"acc_samples",
")",
"self",
".",
"acc_samples",
"=",
"0",
"else",
":",
"return",
"{",
"'skip_step'",
":",
"True",
",",
"'skip_zero'",
":",
"True",
"}"
] |
accumulated step and reset samples, True will result in no stepping
|
[
"accumulated",
"step",
"and",
"reset",
"samples",
"True",
"will",
"result",
"in",
"no",
"stepping"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L120-L126
|
20,634
|
fastai/fastai
|
fastai/train.py
|
AccumulateScheduler.on_epoch_end
|
def on_epoch_end(self, **kwargs):
"step the rest of the accumulated grads if not perfectly divisible"
for p in (self.learn.model.parameters()):
if p.requires_grad: p.grad.div_(self.acc_samples)
if not self.drop_last: self.learn.opt.step()
self.learn.opt.zero_grad()
|
python
|
def on_epoch_end(self, **kwargs):
"step the rest of the accumulated grads if not perfectly divisible"
for p in (self.learn.model.parameters()):
if p.requires_grad: p.grad.div_(self.acc_samples)
if not self.drop_last: self.learn.opt.step()
self.learn.opt.zero_grad()
|
[
"def",
"on_epoch_end",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"p",
"in",
"(",
"self",
".",
"learn",
".",
"model",
".",
"parameters",
"(",
")",
")",
":",
"if",
"p",
".",
"requires_grad",
":",
"p",
".",
"grad",
".",
"div_",
"(",
"self",
".",
"acc_samples",
")",
"if",
"not",
"self",
".",
"drop_last",
":",
"self",
".",
"learn",
".",
"opt",
".",
"step",
"(",
")",
"self",
".",
"learn",
".",
"opt",
".",
"zero_grad",
"(",
")"
] |
step the rest of the accumulated grads if not perfectly divisible
|
[
"step",
"the",
"rest",
"of",
"the",
"accumulated",
"grads",
"if",
"not",
"perfectly",
"divisible"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L128-L133
|
20,635
|
fastai/fastai
|
fastai/train.py
|
ClassificationInterpretation.from_learner
|
def from_learner(cls, learn: Learner, ds_type:DatasetType=DatasetType.Valid):
"Create an instance of `ClassificationInterpretation`"
preds = learn.get_preds(ds_type=ds_type, with_loss=True)
return cls(learn, *preds)
|
python
|
def from_learner(cls, learn: Learner, ds_type:DatasetType=DatasetType.Valid):
"Create an instance of `ClassificationInterpretation`"
preds = learn.get_preds(ds_type=ds_type, with_loss=True)
return cls(learn, *preds)
|
[
"def",
"from_learner",
"(",
"cls",
",",
"learn",
":",
"Learner",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Valid",
")",
":",
"preds",
"=",
"learn",
".",
"get_preds",
"(",
"ds_type",
"=",
"ds_type",
",",
"with_loss",
"=",
"True",
")",
"return",
"cls",
"(",
"learn",
",",
"*",
"preds",
")"
] |
Create an instance of `ClassificationInterpretation`
|
[
"Create",
"an",
"instance",
"of",
"ClassificationInterpretation"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L144-L147
|
20,636
|
fastai/fastai
|
fastai/train.py
|
ClassificationInterpretation.confusion_matrix
|
def confusion_matrix(self, slice_size:int=1):
"Confusion matrix as an `np.ndarray`."
x=torch.arange(0,self.data.c)
if slice_size is None: cm = ((self.pred_class==x[:,None]) & (self.y_true==x[:,None,None])).sum(2)
else:
cm = torch.zeros(self.data.c, self.data.c, dtype=x.dtype)
for i in range(0, self.y_true.shape[0], slice_size):
cm_slice = ((self.pred_class[i:i+slice_size]==x[:,None])
& (self.y_true[i:i+slice_size]==x[:,None,None])).sum(2)
torch.add(cm, cm_slice, out=cm)
return to_np(cm)
|
python
|
def confusion_matrix(self, slice_size:int=1):
"Confusion matrix as an `np.ndarray`."
x=torch.arange(0,self.data.c)
if slice_size is None: cm = ((self.pred_class==x[:,None]) & (self.y_true==x[:,None,None])).sum(2)
else:
cm = torch.zeros(self.data.c, self.data.c, dtype=x.dtype)
for i in range(0, self.y_true.shape[0], slice_size):
cm_slice = ((self.pred_class[i:i+slice_size]==x[:,None])
& (self.y_true[i:i+slice_size]==x[:,None,None])).sum(2)
torch.add(cm, cm_slice, out=cm)
return to_np(cm)
|
[
"def",
"confusion_matrix",
"(",
"self",
",",
"slice_size",
":",
"int",
"=",
"1",
")",
":",
"x",
"=",
"torch",
".",
"arange",
"(",
"0",
",",
"self",
".",
"data",
".",
"c",
")",
"if",
"slice_size",
"is",
"None",
":",
"cm",
"=",
"(",
"(",
"self",
".",
"pred_class",
"==",
"x",
"[",
":",
",",
"None",
"]",
")",
"&",
"(",
"self",
".",
"y_true",
"==",
"x",
"[",
":",
",",
"None",
",",
"None",
"]",
")",
")",
".",
"sum",
"(",
"2",
")",
"else",
":",
"cm",
"=",
"torch",
".",
"zeros",
"(",
"self",
".",
"data",
".",
"c",
",",
"self",
".",
"data",
".",
"c",
",",
"dtype",
"=",
"x",
".",
"dtype",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"y_true",
".",
"shape",
"[",
"0",
"]",
",",
"slice_size",
")",
":",
"cm_slice",
"=",
"(",
"(",
"self",
".",
"pred_class",
"[",
"i",
":",
"i",
"+",
"slice_size",
"]",
"==",
"x",
"[",
":",
",",
"None",
"]",
")",
"&",
"(",
"self",
".",
"y_true",
"[",
"i",
":",
"i",
"+",
"slice_size",
"]",
"==",
"x",
"[",
":",
",",
"None",
",",
"None",
"]",
")",
")",
".",
"sum",
"(",
"2",
")",
"torch",
".",
"add",
"(",
"cm",
",",
"cm_slice",
",",
"out",
"=",
"cm",
")",
"return",
"to_np",
"(",
"cm",
")"
] |
Confusion matrix as an `np.ndarray`.
|
[
"Confusion",
"matrix",
"as",
"an",
"np",
".",
"ndarray",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L149-L159
|
20,637
|
fastai/fastai
|
fastai/train.py
|
ClassificationInterpretation.plot_confusion_matrix
|
def plot_confusion_matrix(self, normalize:bool=False, title:str='Confusion matrix', cmap:Any="Blues", slice_size:int=1,
norm_dec:int=2, plot_txt:bool=True, return_fig:bool=None, **kwargs)->Optional[plt.Figure]:
"Plot the confusion matrix, with `title` and using `cmap`."
# This function is mainly copied from the sklearn docs
cm = self.confusion_matrix(slice_size=slice_size)
if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
fig = plt.figure(**kwargs)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
tick_marks = np.arange(self.data.c)
plt.xticks(tick_marks, self.data.y.classes, rotation=90)
plt.yticks(tick_marks, self.data.y.classes, rotation=0)
if plot_txt:
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
coeff = f'{cm[i, j]:.{norm_dec}f}' if normalize else f'{cm[i, j]}'
plt.text(j, i, coeff, horizontalalignment="center", verticalalignment="center", color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.grid(False)
if ifnone(return_fig, defaults.return_fig): return fig
|
python
|
def plot_confusion_matrix(self, normalize:bool=False, title:str='Confusion matrix', cmap:Any="Blues", slice_size:int=1,
norm_dec:int=2, plot_txt:bool=True, return_fig:bool=None, **kwargs)->Optional[plt.Figure]:
"Plot the confusion matrix, with `title` and using `cmap`."
# This function is mainly copied from the sklearn docs
cm = self.confusion_matrix(slice_size=slice_size)
if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
fig = plt.figure(**kwargs)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
tick_marks = np.arange(self.data.c)
plt.xticks(tick_marks, self.data.y.classes, rotation=90)
plt.yticks(tick_marks, self.data.y.classes, rotation=0)
if plot_txt:
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
coeff = f'{cm[i, j]:.{norm_dec}f}' if normalize else f'{cm[i, j]}'
plt.text(j, i, coeff, horizontalalignment="center", verticalalignment="center", color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.grid(False)
if ifnone(return_fig, defaults.return_fig): return fig
|
[
"def",
"plot_confusion_matrix",
"(",
"self",
",",
"normalize",
":",
"bool",
"=",
"False",
",",
"title",
":",
"str",
"=",
"'Confusion matrix'",
",",
"cmap",
":",
"Any",
"=",
"\"Blues\"",
",",
"slice_size",
":",
"int",
"=",
"1",
",",
"norm_dec",
":",
"int",
"=",
"2",
",",
"plot_txt",
":",
"bool",
"=",
"True",
",",
"return_fig",
":",
"bool",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"Optional",
"[",
"plt",
".",
"Figure",
"]",
":",
"# This function is mainly copied from the sklearn docs",
"cm",
"=",
"self",
".",
"confusion_matrix",
"(",
"slice_size",
"=",
"slice_size",
")",
"if",
"normalize",
":",
"cm",
"=",
"cm",
".",
"astype",
"(",
"'float'",
")",
"/",
"cm",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"fig",
"=",
"plt",
".",
"figure",
"(",
"*",
"*",
"kwargs",
")",
"plt",
".",
"imshow",
"(",
"cm",
",",
"interpolation",
"=",
"'nearest'",
",",
"cmap",
"=",
"cmap",
")",
"plt",
".",
"title",
"(",
"title",
")",
"tick_marks",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"data",
".",
"c",
")",
"plt",
".",
"xticks",
"(",
"tick_marks",
",",
"self",
".",
"data",
".",
"y",
".",
"classes",
",",
"rotation",
"=",
"90",
")",
"plt",
".",
"yticks",
"(",
"tick_marks",
",",
"self",
".",
"data",
".",
"y",
".",
"classes",
",",
"rotation",
"=",
"0",
")",
"if",
"plot_txt",
":",
"thresh",
"=",
"cm",
".",
"max",
"(",
")",
"/",
"2.",
"for",
"i",
",",
"j",
"in",
"itertools",
".",
"product",
"(",
"range",
"(",
"cm",
".",
"shape",
"[",
"0",
"]",
")",
",",
"range",
"(",
"cm",
".",
"shape",
"[",
"1",
"]",
")",
")",
":",
"coeff",
"=",
"f'{cm[i, j]:.{norm_dec}f}'",
"if",
"normalize",
"else",
"f'{cm[i, j]}'",
"plt",
".",
"text",
"(",
"j",
",",
"i",
",",
"coeff",
",",
"horizontalalignment",
"=",
"\"center\"",
",",
"verticalalignment",
"=",
"\"center\"",
",",
"color",
"=",
"\"white\"",
"if",
"cm",
"[",
"i",
",",
"j",
"]",
">",
"thresh",
"else",
"\"black\"",
")",
"plt",
".",
"tight_layout",
"(",
")",
"plt",
".",
"ylabel",
"(",
"'Actual'",
")",
"plt",
".",
"xlabel",
"(",
"'Predicted'",
")",
"plt",
".",
"grid",
"(",
"False",
")",
"if",
"ifnone",
"(",
"return_fig",
",",
"defaults",
".",
"return_fig",
")",
":",
"return",
"fig"
] |
Plot the confusion matrix, with `title` and using `cmap`.
|
[
"Plot",
"the",
"confusion",
"matrix",
"with",
"title",
"and",
"using",
"cmap",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L161-L184
|
20,638
|
fastai/fastai
|
fastai/train.py
|
ClassificationInterpretation.most_confused
|
def most_confused(self, min_val:int=1, slice_size:int=1)->Collection[Tuple[str,str,int]]:
"Sorted descending list of largest non-diagonal entries of confusion matrix, presented as actual, predicted, number of occurrences."
cm = self.confusion_matrix(slice_size=slice_size)
np.fill_diagonal(cm, 0)
res = [(self.data.classes[i],self.data.classes[j],cm[i,j])
for i,j in zip(*np.where(cm>=min_val))]
return sorted(res, key=itemgetter(2), reverse=True)
|
python
|
def most_confused(self, min_val:int=1, slice_size:int=1)->Collection[Tuple[str,str,int]]:
"Sorted descending list of largest non-diagonal entries of confusion matrix, presented as actual, predicted, number of occurrences."
cm = self.confusion_matrix(slice_size=slice_size)
np.fill_diagonal(cm, 0)
res = [(self.data.classes[i],self.data.classes[j],cm[i,j])
for i,j in zip(*np.where(cm>=min_val))]
return sorted(res, key=itemgetter(2), reverse=True)
|
[
"def",
"most_confused",
"(",
"self",
",",
"min_val",
":",
"int",
"=",
"1",
",",
"slice_size",
":",
"int",
"=",
"1",
")",
"->",
"Collection",
"[",
"Tuple",
"[",
"str",
",",
"str",
",",
"int",
"]",
"]",
":",
"cm",
"=",
"self",
".",
"confusion_matrix",
"(",
"slice_size",
"=",
"slice_size",
")",
"np",
".",
"fill_diagonal",
"(",
"cm",
",",
"0",
")",
"res",
"=",
"[",
"(",
"self",
".",
"data",
".",
"classes",
"[",
"i",
"]",
",",
"self",
".",
"data",
".",
"classes",
"[",
"j",
"]",
",",
"cm",
"[",
"i",
",",
"j",
"]",
")",
"for",
"i",
",",
"j",
"in",
"zip",
"(",
"*",
"np",
".",
"where",
"(",
"cm",
">=",
"min_val",
")",
")",
"]",
"return",
"sorted",
"(",
"res",
",",
"key",
"=",
"itemgetter",
"(",
"2",
")",
",",
"reverse",
"=",
"True",
")"
] |
Sorted descending list of largest non-diagonal entries of confusion matrix, presented as actual, predicted, number of occurrences.
|
[
"Sorted",
"descending",
"list",
"of",
"largest",
"non",
"-",
"diagonal",
"entries",
"of",
"confusion",
"matrix",
"presented",
"as",
"actual",
"predicted",
"number",
"of",
"occurrences",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L186-L192
|
20,639
|
fastai/fastai
|
fastai/vision/learner.py
|
cnn_config
|
def cnn_config(arch):
"Get the metadata associated with `arch`."
torch.backends.cudnn.benchmark = True
return model_meta.get(arch, _default_meta)
|
python
|
def cnn_config(arch):
"Get the metadata associated with `arch`."
torch.backends.cudnn.benchmark = True
return model_meta.get(arch, _default_meta)
|
[
"def",
"cnn_config",
"(",
"arch",
")",
":",
"torch",
".",
"backends",
".",
"cudnn",
".",
"benchmark",
"=",
"True",
"return",
"model_meta",
".",
"get",
"(",
"arch",
",",
"_default_meta",
")"
] |
Get the metadata associated with `arch`.
|
[
"Get",
"the",
"metadata",
"associated",
"with",
"arch",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/learner.py#L43-L46
|
20,640
|
fastai/fastai
|
fastai/vision/learner.py
|
create_head
|
def create_head(nf:int, nc:int, lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5,
concat_pool:bool=True, bn_final:bool=False):
"Model head that takes `nf` features, runs through `lin_ftrs`, and about `nc` classes."
lin_ftrs = [nf, 512, nc] if lin_ftrs is None else [nf] + lin_ftrs + [nc]
ps = listify(ps)
if len(ps) == 1: ps = [ps[0]/2] * (len(lin_ftrs)-2) + ps
actns = [nn.ReLU(inplace=True)] * (len(lin_ftrs)-2) + [None]
pool = AdaptiveConcatPool2d() if concat_pool else nn.AdaptiveAvgPool2d(1)
layers = [pool, Flatten()]
for ni,no,p,actn in zip(lin_ftrs[:-1], lin_ftrs[1:], ps, actns):
layers += bn_drop_lin(ni, no, True, p, actn)
if bn_final: layers.append(nn.BatchNorm1d(lin_ftrs[-1], momentum=0.01))
return nn.Sequential(*layers)
|
python
|
def create_head(nf:int, nc:int, lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5,
concat_pool:bool=True, bn_final:bool=False):
"Model head that takes `nf` features, runs through `lin_ftrs`, and about `nc` classes."
lin_ftrs = [nf, 512, nc] if lin_ftrs is None else [nf] + lin_ftrs + [nc]
ps = listify(ps)
if len(ps) == 1: ps = [ps[0]/2] * (len(lin_ftrs)-2) + ps
actns = [nn.ReLU(inplace=True)] * (len(lin_ftrs)-2) + [None]
pool = AdaptiveConcatPool2d() if concat_pool else nn.AdaptiveAvgPool2d(1)
layers = [pool, Flatten()]
for ni,no,p,actn in zip(lin_ftrs[:-1], lin_ftrs[1:], ps, actns):
layers += bn_drop_lin(ni, no, True, p, actn)
if bn_final: layers.append(nn.BatchNorm1d(lin_ftrs[-1], momentum=0.01))
return nn.Sequential(*layers)
|
[
"def",
"create_head",
"(",
"nf",
":",
"int",
",",
"nc",
":",
"int",
",",
"lin_ftrs",
":",
"Optional",
"[",
"Collection",
"[",
"int",
"]",
"]",
"=",
"None",
",",
"ps",
":",
"Floats",
"=",
"0.5",
",",
"concat_pool",
":",
"bool",
"=",
"True",
",",
"bn_final",
":",
"bool",
"=",
"False",
")",
":",
"lin_ftrs",
"=",
"[",
"nf",
",",
"512",
",",
"nc",
"]",
"if",
"lin_ftrs",
"is",
"None",
"else",
"[",
"nf",
"]",
"+",
"lin_ftrs",
"+",
"[",
"nc",
"]",
"ps",
"=",
"listify",
"(",
"ps",
")",
"if",
"len",
"(",
"ps",
")",
"==",
"1",
":",
"ps",
"=",
"[",
"ps",
"[",
"0",
"]",
"/",
"2",
"]",
"*",
"(",
"len",
"(",
"lin_ftrs",
")",
"-",
"2",
")",
"+",
"ps",
"actns",
"=",
"[",
"nn",
".",
"ReLU",
"(",
"inplace",
"=",
"True",
")",
"]",
"*",
"(",
"len",
"(",
"lin_ftrs",
")",
"-",
"2",
")",
"+",
"[",
"None",
"]",
"pool",
"=",
"AdaptiveConcatPool2d",
"(",
")",
"if",
"concat_pool",
"else",
"nn",
".",
"AdaptiveAvgPool2d",
"(",
"1",
")",
"layers",
"=",
"[",
"pool",
",",
"Flatten",
"(",
")",
"]",
"for",
"ni",
",",
"no",
",",
"p",
",",
"actn",
"in",
"zip",
"(",
"lin_ftrs",
"[",
":",
"-",
"1",
"]",
",",
"lin_ftrs",
"[",
"1",
":",
"]",
",",
"ps",
",",
"actns",
")",
":",
"layers",
"+=",
"bn_drop_lin",
"(",
"ni",
",",
"no",
",",
"True",
",",
"p",
",",
"actn",
")",
"if",
"bn_final",
":",
"layers",
".",
"append",
"(",
"nn",
".",
"BatchNorm1d",
"(",
"lin_ftrs",
"[",
"-",
"1",
"]",
",",
"momentum",
"=",
"0.01",
")",
")",
"return",
"nn",
".",
"Sequential",
"(",
"*",
"layers",
")"
] |
Model head that takes `nf` features, runs through `lin_ftrs`, and about `nc` classes.
|
[
"Model",
"head",
"that",
"takes",
"nf",
"features",
"runs",
"through",
"lin_ftrs",
"and",
"about",
"nc",
"classes",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/learner.py#L65-L77
|
20,641
|
fastai/fastai
|
fastai/vision/learner.py
|
create_cnn_model
|
def create_cnn_model(base_arch:Callable, nc:int, cut:Union[int,Callable]=None, pretrained:bool=True,
lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, custom_head:Optional[nn.Module]=None,
split_on:Optional[SplitFuncOrIdxList]=None, bn_final:bool=False, concat_pool:bool=True):
"Create custom convnet architecture"
body = create_body(base_arch, pretrained, cut)
if custom_head is None:
nf = num_features_model(nn.Sequential(*body.children())) * (2 if concat_pool else 1)
head = create_head(nf, nc, lin_ftrs, ps=ps, concat_pool=concat_pool, bn_final=bn_final)
else: head = custom_head
return nn.Sequential(body, head)
|
python
|
def create_cnn_model(base_arch:Callable, nc:int, cut:Union[int,Callable]=None, pretrained:bool=True,
lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, custom_head:Optional[nn.Module]=None,
split_on:Optional[SplitFuncOrIdxList]=None, bn_final:bool=False, concat_pool:bool=True):
"Create custom convnet architecture"
body = create_body(base_arch, pretrained, cut)
if custom_head is None:
nf = num_features_model(nn.Sequential(*body.children())) * (2 if concat_pool else 1)
head = create_head(nf, nc, lin_ftrs, ps=ps, concat_pool=concat_pool, bn_final=bn_final)
else: head = custom_head
return nn.Sequential(body, head)
|
[
"def",
"create_cnn_model",
"(",
"base_arch",
":",
"Callable",
",",
"nc",
":",
"int",
",",
"cut",
":",
"Union",
"[",
"int",
",",
"Callable",
"]",
"=",
"None",
",",
"pretrained",
":",
"bool",
"=",
"True",
",",
"lin_ftrs",
":",
"Optional",
"[",
"Collection",
"[",
"int",
"]",
"]",
"=",
"None",
",",
"ps",
":",
"Floats",
"=",
"0.5",
",",
"custom_head",
":",
"Optional",
"[",
"nn",
".",
"Module",
"]",
"=",
"None",
",",
"split_on",
":",
"Optional",
"[",
"SplitFuncOrIdxList",
"]",
"=",
"None",
",",
"bn_final",
":",
"bool",
"=",
"False",
",",
"concat_pool",
":",
"bool",
"=",
"True",
")",
":",
"body",
"=",
"create_body",
"(",
"base_arch",
",",
"pretrained",
",",
"cut",
")",
"if",
"custom_head",
"is",
"None",
":",
"nf",
"=",
"num_features_model",
"(",
"nn",
".",
"Sequential",
"(",
"*",
"body",
".",
"children",
"(",
")",
")",
")",
"*",
"(",
"2",
"if",
"concat_pool",
"else",
"1",
")",
"head",
"=",
"create_head",
"(",
"nf",
",",
"nc",
",",
"lin_ftrs",
",",
"ps",
"=",
"ps",
",",
"concat_pool",
"=",
"concat_pool",
",",
"bn_final",
"=",
"bn_final",
")",
"else",
":",
"head",
"=",
"custom_head",
"return",
"nn",
".",
"Sequential",
"(",
"body",
",",
"head",
")"
] |
Create custom convnet architecture
|
[
"Create",
"custom",
"convnet",
"architecture"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/learner.py#L79-L88
|
20,642
|
fastai/fastai
|
fastai/vision/learner.py
|
cnn_learner
|
def cnn_learner(data:DataBunch, base_arch:Callable, cut:Union[int,Callable]=None, pretrained:bool=True,
lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, custom_head:Optional[nn.Module]=None,
split_on:Optional[SplitFuncOrIdxList]=None, bn_final:bool=False, init=nn.init.kaiming_normal_,
concat_pool:bool=True, **kwargs:Any)->Learner:
"Build convnet style learner."
meta = cnn_config(base_arch)
model = create_cnn_model(base_arch, data.c, cut, pretrained, lin_ftrs, ps=ps, custom_head=custom_head,
split_on=split_on, bn_final=bn_final, concat_pool=concat_pool)
learn = Learner(data, model, **kwargs)
learn.split(split_on or meta['split'])
if pretrained: learn.freeze()
if init: apply_init(model[1], init)
return learn
|
python
|
def cnn_learner(data:DataBunch, base_arch:Callable, cut:Union[int,Callable]=None, pretrained:bool=True,
lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, custom_head:Optional[nn.Module]=None,
split_on:Optional[SplitFuncOrIdxList]=None, bn_final:bool=False, init=nn.init.kaiming_normal_,
concat_pool:bool=True, **kwargs:Any)->Learner:
"Build convnet style learner."
meta = cnn_config(base_arch)
model = create_cnn_model(base_arch, data.c, cut, pretrained, lin_ftrs, ps=ps, custom_head=custom_head,
split_on=split_on, bn_final=bn_final, concat_pool=concat_pool)
learn = Learner(data, model, **kwargs)
learn.split(split_on or meta['split'])
if pretrained: learn.freeze()
if init: apply_init(model[1], init)
return learn
|
[
"def",
"cnn_learner",
"(",
"data",
":",
"DataBunch",
",",
"base_arch",
":",
"Callable",
",",
"cut",
":",
"Union",
"[",
"int",
",",
"Callable",
"]",
"=",
"None",
",",
"pretrained",
":",
"bool",
"=",
"True",
",",
"lin_ftrs",
":",
"Optional",
"[",
"Collection",
"[",
"int",
"]",
"]",
"=",
"None",
",",
"ps",
":",
"Floats",
"=",
"0.5",
",",
"custom_head",
":",
"Optional",
"[",
"nn",
".",
"Module",
"]",
"=",
"None",
",",
"split_on",
":",
"Optional",
"[",
"SplitFuncOrIdxList",
"]",
"=",
"None",
",",
"bn_final",
":",
"bool",
"=",
"False",
",",
"init",
"=",
"nn",
".",
"init",
".",
"kaiming_normal_",
",",
"concat_pool",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Learner",
":",
"meta",
"=",
"cnn_config",
"(",
"base_arch",
")",
"model",
"=",
"create_cnn_model",
"(",
"base_arch",
",",
"data",
".",
"c",
",",
"cut",
",",
"pretrained",
",",
"lin_ftrs",
",",
"ps",
"=",
"ps",
",",
"custom_head",
"=",
"custom_head",
",",
"split_on",
"=",
"split_on",
",",
"bn_final",
"=",
"bn_final",
",",
"concat_pool",
"=",
"concat_pool",
")",
"learn",
"=",
"Learner",
"(",
"data",
",",
"model",
",",
"*",
"*",
"kwargs",
")",
"learn",
".",
"split",
"(",
"split_on",
"or",
"meta",
"[",
"'split'",
"]",
")",
"if",
"pretrained",
":",
"learn",
".",
"freeze",
"(",
")",
"if",
"init",
":",
"apply_init",
"(",
"model",
"[",
"1",
"]",
",",
"init",
")",
"return",
"learn"
] |
Build convnet style learner.
|
[
"Build",
"convnet",
"style",
"learner",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/learner.py#L90-L102
|
20,643
|
fastai/fastai
|
fastai/vision/learner.py
|
unet_learner
|
def unet_learner(data:DataBunch, arch:Callable, pretrained:bool=True, blur_final:bool=True,
norm_type:Optional[NormType]=NormType, split_on:Optional[SplitFuncOrIdxList]=None, blur:bool=False,
self_attention:bool=False, y_range:Optional[Tuple[float,float]]=None, last_cross:bool=True,
bottle:bool=False, cut:Union[int,Callable]=None, **learn_kwargs:Any)->Learner:
"Build Unet learner from `data` and `arch`."
meta = cnn_config(arch)
body = create_body(arch, pretrained, cut)
model = to_device(models.unet.DynamicUnet(body, n_classes=data.c, blur=blur, blur_final=blur_final,
self_attention=self_attention, y_range=y_range, norm_type=norm_type, last_cross=last_cross,
bottle=bottle), data.device)
learn = Learner(data, model, **learn_kwargs)
learn.split(ifnone(split_on, meta['split']))
if pretrained: learn.freeze()
apply_init(model[2], nn.init.kaiming_normal_)
return learn
|
python
|
def unet_learner(data:DataBunch, arch:Callable, pretrained:bool=True, blur_final:bool=True,
norm_type:Optional[NormType]=NormType, split_on:Optional[SplitFuncOrIdxList]=None, blur:bool=False,
self_attention:bool=False, y_range:Optional[Tuple[float,float]]=None, last_cross:bool=True,
bottle:bool=False, cut:Union[int,Callable]=None, **learn_kwargs:Any)->Learner:
"Build Unet learner from `data` and `arch`."
meta = cnn_config(arch)
body = create_body(arch, pretrained, cut)
model = to_device(models.unet.DynamicUnet(body, n_classes=data.c, blur=blur, blur_final=blur_final,
self_attention=self_attention, y_range=y_range, norm_type=norm_type, last_cross=last_cross,
bottle=bottle), data.device)
learn = Learner(data, model, **learn_kwargs)
learn.split(ifnone(split_on, meta['split']))
if pretrained: learn.freeze()
apply_init(model[2], nn.init.kaiming_normal_)
return learn
|
[
"def",
"unet_learner",
"(",
"data",
":",
"DataBunch",
",",
"arch",
":",
"Callable",
",",
"pretrained",
":",
"bool",
"=",
"True",
",",
"blur_final",
":",
"bool",
"=",
"True",
",",
"norm_type",
":",
"Optional",
"[",
"NormType",
"]",
"=",
"NormType",
",",
"split_on",
":",
"Optional",
"[",
"SplitFuncOrIdxList",
"]",
"=",
"None",
",",
"blur",
":",
"bool",
"=",
"False",
",",
"self_attention",
":",
"bool",
"=",
"False",
",",
"y_range",
":",
"Optional",
"[",
"Tuple",
"[",
"float",
",",
"float",
"]",
"]",
"=",
"None",
",",
"last_cross",
":",
"bool",
"=",
"True",
",",
"bottle",
":",
"bool",
"=",
"False",
",",
"cut",
":",
"Union",
"[",
"int",
",",
"Callable",
"]",
"=",
"None",
",",
"*",
"*",
"learn_kwargs",
":",
"Any",
")",
"->",
"Learner",
":",
"meta",
"=",
"cnn_config",
"(",
"arch",
")",
"body",
"=",
"create_body",
"(",
"arch",
",",
"pretrained",
",",
"cut",
")",
"model",
"=",
"to_device",
"(",
"models",
".",
"unet",
".",
"DynamicUnet",
"(",
"body",
",",
"n_classes",
"=",
"data",
".",
"c",
",",
"blur",
"=",
"blur",
",",
"blur_final",
"=",
"blur_final",
",",
"self_attention",
"=",
"self_attention",
",",
"y_range",
"=",
"y_range",
",",
"norm_type",
"=",
"norm_type",
",",
"last_cross",
"=",
"last_cross",
",",
"bottle",
"=",
"bottle",
")",
",",
"data",
".",
"device",
")",
"learn",
"=",
"Learner",
"(",
"data",
",",
"model",
",",
"*",
"*",
"learn_kwargs",
")",
"learn",
".",
"split",
"(",
"ifnone",
"(",
"split_on",
",",
"meta",
"[",
"'split'",
"]",
")",
")",
"if",
"pretrained",
":",
"learn",
".",
"freeze",
"(",
")",
"apply_init",
"(",
"model",
"[",
"2",
"]",
",",
"nn",
".",
"init",
".",
"kaiming_normal_",
")",
"return",
"learn"
] |
Build Unet learner from `data` and `arch`.
|
[
"Build",
"Unet",
"learner",
"from",
"data",
"and",
"arch",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/learner.py#L108-L122
|
20,644
|
fastai/fastai
|
fastai/vision/learner.py
|
_cl_int_from_learner
|
def _cl_int_from_learner(cls, learn:Learner, ds_type:DatasetType=DatasetType.Valid, tta=False):
"Create an instance of `ClassificationInterpretation`. `tta` indicates if we want to use Test Time Augmentation."
preds = learn.TTA(ds_type=ds_type, with_loss=True) if tta else learn.get_preds(ds_type=ds_type, with_loss=True)
return cls(learn, *preds, ds_type=ds_type)
|
python
|
def _cl_int_from_learner(cls, learn:Learner, ds_type:DatasetType=DatasetType.Valid, tta=False):
"Create an instance of `ClassificationInterpretation`. `tta` indicates if we want to use Test Time Augmentation."
preds = learn.TTA(ds_type=ds_type, with_loss=True) if tta else learn.get_preds(ds_type=ds_type, with_loss=True)
return cls(learn, *preds, ds_type=ds_type)
|
[
"def",
"_cl_int_from_learner",
"(",
"cls",
",",
"learn",
":",
"Learner",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Valid",
",",
"tta",
"=",
"False",
")",
":",
"preds",
"=",
"learn",
".",
"TTA",
"(",
"ds_type",
"=",
"ds_type",
",",
"with_loss",
"=",
"True",
")",
"if",
"tta",
"else",
"learn",
".",
"get_preds",
"(",
"ds_type",
"=",
"ds_type",
",",
"with_loss",
"=",
"True",
")",
"return",
"cls",
"(",
"learn",
",",
"*",
"preds",
",",
"ds_type",
"=",
"ds_type",
")"
] |
Create an instance of `ClassificationInterpretation`. `tta` indicates if we want to use Test Time Augmentation.
|
[
"Create",
"an",
"instance",
"of",
"ClassificationInterpretation",
".",
"tta",
"indicates",
"if",
"we",
"want",
"to",
"use",
"Test",
"Time",
"Augmentation",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/learner.py#L125-L128
|
20,645
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
DatasetFormatter.from_toplosses
|
def from_toplosses(cls, learn, n_imgs=None, **kwargs):
"Gets indices with top losses."
train_ds, train_idxs = cls.get_toplosses_idxs(learn, n_imgs, **kwargs)
return train_ds, train_idxs
|
python
|
def from_toplosses(cls, learn, n_imgs=None, **kwargs):
"Gets indices with top losses."
train_ds, train_idxs = cls.get_toplosses_idxs(learn, n_imgs, **kwargs)
return train_ds, train_idxs
|
[
"def",
"from_toplosses",
"(",
"cls",
",",
"learn",
",",
"n_imgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"train_ds",
",",
"train_idxs",
"=",
"cls",
".",
"get_toplosses_idxs",
"(",
"learn",
",",
"n_imgs",
",",
"*",
"*",
"kwargs",
")",
"return",
"train_ds",
",",
"train_idxs"
] |
Gets indices with top losses.
|
[
"Gets",
"indices",
"with",
"top",
"losses",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L17-L20
|
20,646
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
DatasetFormatter.get_toplosses_idxs
|
def get_toplosses_idxs(cls, learn, n_imgs, **kwargs):
"Sorts `ds_type` dataset by top losses and returns dataset and sorted indices."
dl = learn.data.fix_dl
if not n_imgs: n_imgs = len(dl.dataset)
_,_,top_losses = learn.get_preds(ds_type=DatasetType.Fix, with_loss=True)
idxs = torch.topk(top_losses, n_imgs)[1]
return cls.padded_ds(dl.dataset, **kwargs), idxs
|
python
|
def get_toplosses_idxs(cls, learn, n_imgs, **kwargs):
"Sorts `ds_type` dataset by top losses and returns dataset and sorted indices."
dl = learn.data.fix_dl
if not n_imgs: n_imgs = len(dl.dataset)
_,_,top_losses = learn.get_preds(ds_type=DatasetType.Fix, with_loss=True)
idxs = torch.topk(top_losses, n_imgs)[1]
return cls.padded_ds(dl.dataset, **kwargs), idxs
|
[
"def",
"get_toplosses_idxs",
"(",
"cls",
",",
"learn",
",",
"n_imgs",
",",
"*",
"*",
"kwargs",
")",
":",
"dl",
"=",
"learn",
".",
"data",
".",
"fix_dl",
"if",
"not",
"n_imgs",
":",
"n_imgs",
"=",
"len",
"(",
"dl",
".",
"dataset",
")",
"_",
",",
"_",
",",
"top_losses",
"=",
"learn",
".",
"get_preds",
"(",
"ds_type",
"=",
"DatasetType",
".",
"Fix",
",",
"with_loss",
"=",
"True",
")",
"idxs",
"=",
"torch",
".",
"topk",
"(",
"top_losses",
",",
"n_imgs",
")",
"[",
"1",
"]",
"return",
"cls",
".",
"padded_ds",
"(",
"dl",
".",
"dataset",
",",
"*",
"*",
"kwargs",
")",
",",
"idxs"
] |
Sorts `ds_type` dataset by top losses and returns dataset and sorted indices.
|
[
"Sorts",
"ds_type",
"dataset",
"by",
"top",
"losses",
"and",
"returns",
"dataset",
"and",
"sorted",
"indices",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L23-L29
|
20,647
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
DatasetFormatter.padded_ds
|
def padded_ds(ll_input, size=(250, 300), resize_method=ResizeMethod.CROP, padding_mode='zeros', **kwargs):
"For a LabelList `ll_input`, resize each image to `size` using `resize_method` and `padding_mode`."
return ll_input.transform(tfms=crop_pad(), size=size, resize_method=resize_method, padding_mode=padding_mode)
|
python
|
def padded_ds(ll_input, size=(250, 300), resize_method=ResizeMethod.CROP, padding_mode='zeros', **kwargs):
"For a LabelList `ll_input`, resize each image to `size` using `resize_method` and `padding_mode`."
return ll_input.transform(tfms=crop_pad(), size=size, resize_method=resize_method, padding_mode=padding_mode)
|
[
"def",
"padded_ds",
"(",
"ll_input",
",",
"size",
"=",
"(",
"250",
",",
"300",
")",
",",
"resize_method",
"=",
"ResizeMethod",
".",
"CROP",
",",
"padding_mode",
"=",
"'zeros'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"ll_input",
".",
"transform",
"(",
"tfms",
"=",
"crop_pad",
"(",
")",
",",
"size",
"=",
"size",
",",
"resize_method",
"=",
"resize_method",
",",
"padding_mode",
"=",
"padding_mode",
")"
] |
For a LabelList `ll_input`, resize each image to `size` using `resize_method` and `padding_mode`.
|
[
"For",
"a",
"LabelList",
"ll_input",
"resize",
"each",
"image",
"to",
"size",
"using",
"resize_method",
"and",
"padding_mode",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L31-L33
|
20,648
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
DatasetFormatter.from_similars
|
def from_similars(cls, learn, layer_ls:list=[0, 7, 2], **kwargs):
"Gets the indices for the most similar images."
train_ds, train_idxs = cls.get_similars_idxs(learn, layer_ls, **kwargs)
return train_ds, train_idxs
|
python
|
def from_similars(cls, learn, layer_ls:list=[0, 7, 2], **kwargs):
"Gets the indices for the most similar images."
train_ds, train_idxs = cls.get_similars_idxs(learn, layer_ls, **kwargs)
return train_ds, train_idxs
|
[
"def",
"from_similars",
"(",
"cls",
",",
"learn",
",",
"layer_ls",
":",
"list",
"=",
"[",
"0",
",",
"7",
",",
"2",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"train_ds",
",",
"train_idxs",
"=",
"cls",
".",
"get_similars_idxs",
"(",
"learn",
",",
"layer_ls",
",",
"*",
"*",
"kwargs",
")",
"return",
"train_ds",
",",
"train_idxs"
] |
Gets the indices for the most similar images.
|
[
"Gets",
"the",
"indices",
"for",
"the",
"most",
"similar",
"images",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L36-L39
|
20,649
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
DatasetFormatter.get_similars_idxs
|
def get_similars_idxs(cls, learn, layer_ls, **kwargs):
"Gets the indices for the most similar images in `ds_type` dataset"
hook = hook_output(learn.model[layer_ls[0]][layer_ls[1]][layer_ls[2]])
dl = learn.data.fix_dl
ds_actns = cls.get_actns(learn, hook=hook, dl=dl, **kwargs)
similarities = cls.comb_similarity(ds_actns, ds_actns, **kwargs)
idxs = cls.sort_idxs(similarities)
return cls.padded_ds(dl, **kwargs), idxs
|
python
|
def get_similars_idxs(cls, learn, layer_ls, **kwargs):
"Gets the indices for the most similar images in `ds_type` dataset"
hook = hook_output(learn.model[layer_ls[0]][layer_ls[1]][layer_ls[2]])
dl = learn.data.fix_dl
ds_actns = cls.get_actns(learn, hook=hook, dl=dl, **kwargs)
similarities = cls.comb_similarity(ds_actns, ds_actns, **kwargs)
idxs = cls.sort_idxs(similarities)
return cls.padded_ds(dl, **kwargs), idxs
|
[
"def",
"get_similars_idxs",
"(",
"cls",
",",
"learn",
",",
"layer_ls",
",",
"*",
"*",
"kwargs",
")",
":",
"hook",
"=",
"hook_output",
"(",
"learn",
".",
"model",
"[",
"layer_ls",
"[",
"0",
"]",
"]",
"[",
"layer_ls",
"[",
"1",
"]",
"]",
"[",
"layer_ls",
"[",
"2",
"]",
"]",
")",
"dl",
"=",
"learn",
".",
"data",
".",
"fix_dl",
"ds_actns",
"=",
"cls",
".",
"get_actns",
"(",
"learn",
",",
"hook",
"=",
"hook",
",",
"dl",
"=",
"dl",
",",
"*",
"*",
"kwargs",
")",
"similarities",
"=",
"cls",
".",
"comb_similarity",
"(",
"ds_actns",
",",
"ds_actns",
",",
"*",
"*",
"kwargs",
")",
"idxs",
"=",
"cls",
".",
"sort_idxs",
"(",
"similarities",
")",
"return",
"cls",
".",
"padded_ds",
"(",
"dl",
",",
"*",
"*",
"kwargs",
")",
",",
"idxs"
] |
Gets the indices for the most similar images in `ds_type` dataset
|
[
"Gets",
"the",
"indices",
"for",
"the",
"most",
"similar",
"images",
"in",
"ds_type",
"dataset"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L42-L50
|
20,650
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
DatasetFormatter.get_actns
|
def get_actns(learn, hook:Hook, dl:DataLoader, pool=AdaptiveConcatPool2d, pool_dim:int=4, **kwargs):
"Gets activations at the layer specified by `hook`, applies `pool` of dim `pool_dim` and concatenates"
print('Getting activations...')
actns = []
learn.model.eval()
with torch.no_grad():
for (xb,yb) in progress_bar(dl):
learn.model(xb)
actns.append((hook.stored).cpu())
if pool:
pool = pool(pool_dim)
return pool(torch.cat(actns)).view(len(dl.x),-1)
else: return torch.cat(actns).view(len(dl.x),-1)
|
python
|
def get_actns(learn, hook:Hook, dl:DataLoader, pool=AdaptiveConcatPool2d, pool_dim:int=4, **kwargs):
"Gets activations at the layer specified by `hook`, applies `pool` of dim `pool_dim` and concatenates"
print('Getting activations...')
actns = []
learn.model.eval()
with torch.no_grad():
for (xb,yb) in progress_bar(dl):
learn.model(xb)
actns.append((hook.stored).cpu())
if pool:
pool = pool(pool_dim)
return pool(torch.cat(actns)).view(len(dl.x),-1)
else: return torch.cat(actns).view(len(dl.x),-1)
|
[
"def",
"get_actns",
"(",
"learn",
",",
"hook",
":",
"Hook",
",",
"dl",
":",
"DataLoader",
",",
"pool",
"=",
"AdaptiveConcatPool2d",
",",
"pool_dim",
":",
"int",
"=",
"4",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"'Getting activations...'",
")",
"actns",
"=",
"[",
"]",
"learn",
".",
"model",
".",
"eval",
"(",
")",
"with",
"torch",
".",
"no_grad",
"(",
")",
":",
"for",
"(",
"xb",
",",
"yb",
")",
"in",
"progress_bar",
"(",
"dl",
")",
":",
"learn",
".",
"model",
"(",
"xb",
")",
"actns",
".",
"append",
"(",
"(",
"hook",
".",
"stored",
")",
".",
"cpu",
"(",
")",
")",
"if",
"pool",
":",
"pool",
"=",
"pool",
"(",
"pool_dim",
")",
"return",
"pool",
"(",
"torch",
".",
"cat",
"(",
"actns",
")",
")",
".",
"view",
"(",
"len",
"(",
"dl",
".",
"x",
")",
",",
"-",
"1",
")",
"else",
":",
"return",
"torch",
".",
"cat",
"(",
"actns",
")",
".",
"view",
"(",
"len",
"(",
"dl",
".",
"x",
")",
",",
"-",
"1",
")"
] |
Gets activations at the layer specified by `hook`, applies `pool` of dim `pool_dim` and concatenates
|
[
"Gets",
"activations",
"at",
"the",
"layer",
"specified",
"by",
"hook",
"applies",
"pool",
"of",
"dim",
"pool_dim",
"and",
"concatenates"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L53-L67
|
20,651
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
DatasetFormatter.comb_similarity
|
def comb_similarity(t1: torch.Tensor, t2: torch.Tensor, **kwargs):
# https://github.com/pytorch/pytorch/issues/11202
"Computes the similarity function between each embedding of `t1` and `t2` matrices."
print('Computing similarities...')
w1 = t1.norm(p=2, dim=1, keepdim=True)
w2 = w1 if t2 is t1 else t2.norm(p=2, dim=1, keepdim=True)
t = torch.mm(t1, t2.t()) / (w1 * w2.t()).clamp(min=1e-8)
return torch.tril(t, diagonal=-1)
|
python
|
def comb_similarity(t1: torch.Tensor, t2: torch.Tensor, **kwargs):
# https://github.com/pytorch/pytorch/issues/11202
"Computes the similarity function between each embedding of `t1` and `t2` matrices."
print('Computing similarities...')
w1 = t1.norm(p=2, dim=1, keepdim=True)
w2 = w1 if t2 is t1 else t2.norm(p=2, dim=1, keepdim=True)
t = torch.mm(t1, t2.t()) / (w1 * w2.t()).clamp(min=1e-8)
return torch.tril(t, diagonal=-1)
|
[
"def",
"comb_similarity",
"(",
"t1",
":",
"torch",
".",
"Tensor",
",",
"t2",
":",
"torch",
".",
"Tensor",
",",
"*",
"*",
"kwargs",
")",
":",
"# https://github.com/pytorch/pytorch/issues/11202",
"print",
"(",
"'Computing similarities...'",
")",
"w1",
"=",
"t1",
".",
"norm",
"(",
"p",
"=",
"2",
",",
"dim",
"=",
"1",
",",
"keepdim",
"=",
"True",
")",
"w2",
"=",
"w1",
"if",
"t2",
"is",
"t1",
"else",
"t2",
".",
"norm",
"(",
"p",
"=",
"2",
",",
"dim",
"=",
"1",
",",
"keepdim",
"=",
"True",
")",
"t",
"=",
"torch",
".",
"mm",
"(",
"t1",
",",
"t2",
".",
"t",
"(",
")",
")",
"/",
"(",
"w1",
"*",
"w2",
".",
"t",
"(",
")",
")",
".",
"clamp",
"(",
"min",
"=",
"1e-8",
")",
"return",
"torch",
".",
"tril",
"(",
"t",
",",
"diagonal",
"=",
"-",
"1",
")"
] |
Computes the similarity function between each embedding of `t1` and `t2` matrices.
|
[
"Computes",
"the",
"similarity",
"function",
"between",
"each",
"embedding",
"of",
"t1",
"and",
"t2",
"matrices",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L71-L80
|
20,652
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
DatasetFormatter.largest_indices
|
def largest_indices(arr, n):
"Returns the `n` largest indices from a numpy array `arr`."
#https://stackoverflow.com/questions/6910641/how-do-i-get-indices-of-n-maximum-values-in-a-numpy-array
flat = arr.flatten()
indices = np.argpartition(flat, -n)[-n:]
indices = indices[np.argsort(-flat[indices])]
return np.unravel_index(indices, arr.shape)
|
python
|
def largest_indices(arr, n):
"Returns the `n` largest indices from a numpy array `arr`."
#https://stackoverflow.com/questions/6910641/how-do-i-get-indices-of-n-maximum-values-in-a-numpy-array
flat = arr.flatten()
indices = np.argpartition(flat, -n)[-n:]
indices = indices[np.argsort(-flat[indices])]
return np.unravel_index(indices, arr.shape)
|
[
"def",
"largest_indices",
"(",
"arr",
",",
"n",
")",
":",
"#https://stackoverflow.com/questions/6910641/how-do-i-get-indices-of-n-maximum-values-in-a-numpy-array",
"flat",
"=",
"arr",
".",
"flatten",
"(",
")",
"indices",
"=",
"np",
".",
"argpartition",
"(",
"flat",
",",
"-",
"n",
")",
"[",
"-",
"n",
":",
"]",
"indices",
"=",
"indices",
"[",
"np",
".",
"argsort",
"(",
"-",
"flat",
"[",
"indices",
"]",
")",
"]",
"return",
"np",
".",
"unravel_index",
"(",
"indices",
",",
"arr",
".",
"shape",
")"
] |
Returns the `n` largest indices from a numpy array `arr`.
|
[
"Returns",
"the",
"n",
"largest",
"indices",
"from",
"a",
"numpy",
"array",
"arr",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L82-L88
|
20,653
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
DatasetFormatter.sort_idxs
|
def sort_idxs(cls, similarities):
"Sorts `similarities` and return the indexes in pairs ordered by highest similarity."
idxs = cls.largest_indices(similarities, len(similarities))
idxs = [(idxs[0][i], idxs[1][i]) for i in range(len(idxs[0]))]
return [e for l in idxs for e in l]
|
python
|
def sort_idxs(cls, similarities):
"Sorts `similarities` and return the indexes in pairs ordered by highest similarity."
idxs = cls.largest_indices(similarities, len(similarities))
idxs = [(idxs[0][i], idxs[1][i]) for i in range(len(idxs[0]))]
return [e for l in idxs for e in l]
|
[
"def",
"sort_idxs",
"(",
"cls",
",",
"similarities",
")",
":",
"idxs",
"=",
"cls",
".",
"largest_indices",
"(",
"similarities",
",",
"len",
"(",
"similarities",
")",
")",
"idxs",
"=",
"[",
"(",
"idxs",
"[",
"0",
"]",
"[",
"i",
"]",
",",
"idxs",
"[",
"1",
"]",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"idxs",
"[",
"0",
"]",
")",
")",
"]",
"return",
"[",
"e",
"for",
"l",
"in",
"idxs",
"for",
"e",
"in",
"l",
"]"
] |
Sorts `similarities` and return the indexes in pairs ordered by highest similarity.
|
[
"Sorts",
"similarities",
"and",
"return",
"the",
"indexes",
"in",
"pairs",
"ordered",
"by",
"highest",
"similarity",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L91-L95
|
20,654
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.make_img_widget
|
def make_img_widget(cls, img, layout=Layout(), format='jpg'):
"Returns an image widget for specified file name `img`."
return widgets.Image(value=img, format=format, layout=layout)
|
python
|
def make_img_widget(cls, img, layout=Layout(), format='jpg'):
"Returns an image widget for specified file name `img`."
return widgets.Image(value=img, format=format, layout=layout)
|
[
"def",
"make_img_widget",
"(",
"cls",
",",
"img",
",",
"layout",
"=",
"Layout",
"(",
")",
",",
"format",
"=",
"'jpg'",
")",
":",
"return",
"widgets",
".",
"Image",
"(",
"value",
"=",
"img",
",",
"format",
"=",
"format",
",",
"layout",
"=",
"layout",
")"
] |
Returns an image widget for specified file name `img`.
|
[
"Returns",
"an",
"image",
"widget",
"for",
"specified",
"file",
"name",
"img",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L113-L115
|
20,655
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.make_button_widget
|
def make_button_widget(cls, label, file_path=None, handler=None, style=None, layout=Layout(width='auto')):
"Return a Button widget with specified `handler`."
btn = widgets.Button(description=label, layout=layout)
if handler is not None: btn.on_click(handler)
if style is not None: btn.button_style = style
btn.file_path = file_path
btn.flagged_for_delete = False
return btn
|
python
|
def make_button_widget(cls, label, file_path=None, handler=None, style=None, layout=Layout(width='auto')):
"Return a Button widget with specified `handler`."
btn = widgets.Button(description=label, layout=layout)
if handler is not None: btn.on_click(handler)
if style is not None: btn.button_style = style
btn.file_path = file_path
btn.flagged_for_delete = False
return btn
|
[
"def",
"make_button_widget",
"(",
"cls",
",",
"label",
",",
"file_path",
"=",
"None",
",",
"handler",
"=",
"None",
",",
"style",
"=",
"None",
",",
"layout",
"=",
"Layout",
"(",
"width",
"=",
"'auto'",
")",
")",
":",
"btn",
"=",
"widgets",
".",
"Button",
"(",
"description",
"=",
"label",
",",
"layout",
"=",
"layout",
")",
"if",
"handler",
"is",
"not",
"None",
":",
"btn",
".",
"on_click",
"(",
"handler",
")",
"if",
"style",
"is",
"not",
"None",
":",
"btn",
".",
"button_style",
"=",
"style",
"btn",
".",
"file_path",
"=",
"file_path",
"btn",
".",
"flagged_for_delete",
"=",
"False",
"return",
"btn"
] |
Return a Button widget with specified `handler`.
|
[
"Return",
"a",
"Button",
"widget",
"with",
"specified",
"handler",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L118-L125
|
20,656
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.make_dropdown_widget
|
def make_dropdown_widget(cls, description='Description', options=['Label 1', 'Label 2'], value='Label 1',
file_path=None, layout=Layout(), handler=None):
"Return a Dropdown widget with specified `handler`."
dd = widgets.Dropdown(description=description, options=options, value=value, layout=layout)
if file_path is not None: dd.file_path = file_path
if handler is not None: dd.observe(handler, names=['value'])
return dd
|
python
|
def make_dropdown_widget(cls, description='Description', options=['Label 1', 'Label 2'], value='Label 1',
file_path=None, layout=Layout(), handler=None):
"Return a Dropdown widget with specified `handler`."
dd = widgets.Dropdown(description=description, options=options, value=value, layout=layout)
if file_path is not None: dd.file_path = file_path
if handler is not None: dd.observe(handler, names=['value'])
return dd
|
[
"def",
"make_dropdown_widget",
"(",
"cls",
",",
"description",
"=",
"'Description'",
",",
"options",
"=",
"[",
"'Label 1'",
",",
"'Label 2'",
"]",
",",
"value",
"=",
"'Label 1'",
",",
"file_path",
"=",
"None",
",",
"layout",
"=",
"Layout",
"(",
")",
",",
"handler",
"=",
"None",
")",
":",
"dd",
"=",
"widgets",
".",
"Dropdown",
"(",
"description",
"=",
"description",
",",
"options",
"=",
"options",
",",
"value",
"=",
"value",
",",
"layout",
"=",
"layout",
")",
"if",
"file_path",
"is",
"not",
"None",
":",
"dd",
".",
"file_path",
"=",
"file_path",
"if",
"handler",
"is",
"not",
"None",
":",
"dd",
".",
"observe",
"(",
"handler",
",",
"names",
"=",
"[",
"'value'",
"]",
")",
"return",
"dd"
] |
Return a Dropdown widget with specified `handler`.
|
[
"Return",
"a",
"Dropdown",
"widget",
"with",
"specified",
"handler",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L128-L134
|
20,657
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.make_horizontal_box
|
def make_horizontal_box(cls, children, layout=Layout()):
"Make a horizontal box with `children` and `layout`."
return widgets.HBox(children, layout=layout)
|
python
|
def make_horizontal_box(cls, children, layout=Layout()):
"Make a horizontal box with `children` and `layout`."
return widgets.HBox(children, layout=layout)
|
[
"def",
"make_horizontal_box",
"(",
"cls",
",",
"children",
",",
"layout",
"=",
"Layout",
"(",
")",
")",
":",
"return",
"widgets",
".",
"HBox",
"(",
"children",
",",
"layout",
"=",
"layout",
")"
] |
Make a horizontal box with `children` and `layout`.
|
[
"Make",
"a",
"horizontal",
"box",
"with",
"children",
"and",
"layout",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L137-L139
|
20,658
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.make_vertical_box
|
def make_vertical_box(cls, children, layout=Layout(), duplicates=False):
"Make a vertical box with `children` and `layout`."
if not duplicates: return widgets.VBox(children, layout=layout)
else: return widgets.VBox([children[0], children[2]], layout=layout)
|
python
|
def make_vertical_box(cls, children, layout=Layout(), duplicates=False):
"Make a vertical box with `children` and `layout`."
if not duplicates: return widgets.VBox(children, layout=layout)
else: return widgets.VBox([children[0], children[2]], layout=layout)
|
[
"def",
"make_vertical_box",
"(",
"cls",
",",
"children",
",",
"layout",
"=",
"Layout",
"(",
")",
",",
"duplicates",
"=",
"False",
")",
":",
"if",
"not",
"duplicates",
":",
"return",
"widgets",
".",
"VBox",
"(",
"children",
",",
"layout",
"=",
"layout",
")",
"else",
":",
"return",
"widgets",
".",
"VBox",
"(",
"[",
"children",
"[",
"0",
"]",
",",
"children",
"[",
"2",
"]",
"]",
",",
"layout",
"=",
"layout",
")"
] |
Make a vertical box with `children` and `layout`.
|
[
"Make",
"a",
"vertical",
"box",
"with",
"children",
"and",
"layout",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L142-L145
|
20,659
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.create_image_list
|
def create_image_list(self, dataset, fns_idxs):
"Create a list of images, filenames and labels but first removing files that are not supposed to be displayed."
items = dataset.x.items
if self._duplicates:
chunked_idxs = chunks(fns_idxs, 2)
chunked_idxs = [chunk for chunk in chunked_idxs if Path(items[chunk[0]]).is_file() and Path(items[chunk[1]]).is_file()]
return [(dataset.x[i]._repr_jpeg_(), items[i], self._labels[dataset.y[i].data]) for chunk in chunked_idxs for i in chunk]
else:
return [(dataset.x[i]._repr_jpeg_(), items[i], self._labels[dataset.y[i].data]) for i in fns_idxs if
Path(items[i]).is_file()]
|
python
|
def create_image_list(self, dataset, fns_idxs):
"Create a list of images, filenames and labels but first removing files that are not supposed to be displayed."
items = dataset.x.items
if self._duplicates:
chunked_idxs = chunks(fns_idxs, 2)
chunked_idxs = [chunk for chunk in chunked_idxs if Path(items[chunk[0]]).is_file() and Path(items[chunk[1]]).is_file()]
return [(dataset.x[i]._repr_jpeg_(), items[i], self._labels[dataset.y[i].data]) for chunk in chunked_idxs for i in chunk]
else:
return [(dataset.x[i]._repr_jpeg_(), items[i], self._labels[dataset.y[i].data]) for i in fns_idxs if
Path(items[i]).is_file()]
|
[
"def",
"create_image_list",
"(",
"self",
",",
"dataset",
",",
"fns_idxs",
")",
":",
"items",
"=",
"dataset",
".",
"x",
".",
"items",
"if",
"self",
".",
"_duplicates",
":",
"chunked_idxs",
"=",
"chunks",
"(",
"fns_idxs",
",",
"2",
")",
"chunked_idxs",
"=",
"[",
"chunk",
"for",
"chunk",
"in",
"chunked_idxs",
"if",
"Path",
"(",
"items",
"[",
"chunk",
"[",
"0",
"]",
"]",
")",
".",
"is_file",
"(",
")",
"and",
"Path",
"(",
"items",
"[",
"chunk",
"[",
"1",
"]",
"]",
")",
".",
"is_file",
"(",
")",
"]",
"return",
"[",
"(",
"dataset",
".",
"x",
"[",
"i",
"]",
".",
"_repr_jpeg_",
"(",
")",
",",
"items",
"[",
"i",
"]",
",",
"self",
".",
"_labels",
"[",
"dataset",
".",
"y",
"[",
"i",
"]",
".",
"data",
"]",
")",
"for",
"chunk",
"in",
"chunked_idxs",
"for",
"i",
"in",
"chunk",
"]",
"else",
":",
"return",
"[",
"(",
"dataset",
".",
"x",
"[",
"i",
"]",
".",
"_repr_jpeg_",
"(",
")",
",",
"items",
"[",
"i",
"]",
",",
"self",
".",
"_labels",
"[",
"dataset",
".",
"y",
"[",
"i",
"]",
".",
"data",
"]",
")",
"for",
"i",
"in",
"fns_idxs",
"if",
"Path",
"(",
"items",
"[",
"i",
"]",
")",
".",
"is_file",
"(",
")",
"]"
] |
Create a list of images, filenames and labels but first removing files that are not supposed to be displayed.
|
[
"Create",
"a",
"list",
"of",
"images",
"filenames",
"and",
"labels",
"but",
"first",
"removing",
"files",
"that",
"are",
"not",
"supposed",
"to",
"be",
"displayed",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L147-L156
|
20,660
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.relabel
|
def relabel(self, change):
"Relabel images by moving from parent dir with old label `class_old` to parent dir with new label `class_new`."
class_new,class_old,file_path = change.new,change.old,change.owner.file_path
fp = Path(file_path)
parent = fp.parents[1]
self._csv_dict[fp] = class_new
|
python
|
def relabel(self, change):
"Relabel images by moving from parent dir with old label `class_old` to parent dir with new label `class_new`."
class_new,class_old,file_path = change.new,change.old,change.owner.file_path
fp = Path(file_path)
parent = fp.parents[1]
self._csv_dict[fp] = class_new
|
[
"def",
"relabel",
"(",
"self",
",",
"change",
")",
":",
"class_new",
",",
"class_old",
",",
"file_path",
"=",
"change",
".",
"new",
",",
"change",
".",
"old",
",",
"change",
".",
"owner",
".",
"file_path",
"fp",
"=",
"Path",
"(",
"file_path",
")",
"parent",
"=",
"fp",
".",
"parents",
"[",
"1",
"]",
"self",
".",
"_csv_dict",
"[",
"fp",
"]",
"=",
"class_new"
] |
Relabel images by moving from parent dir with old label `class_old` to parent dir with new label `class_new`.
|
[
"Relabel",
"images",
"by",
"moving",
"from",
"parent",
"dir",
"with",
"old",
"label",
"class_old",
"to",
"parent",
"dir",
"with",
"new",
"label",
"class_new",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L158-L163
|
20,661
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.next_batch
|
def next_batch(self, _):
"Handler for 'Next Batch' button click. Delete all flagged images and renders next batch."
for img_widget, delete_btn, fp, in self._batch:
fp = delete_btn.file_path
if (delete_btn.flagged_for_delete == True):
self.delete_image(fp)
self._deleted_fns.append(fp)
self._all_images = self._all_images[self._batch_size:]
self.empty_batch()
self.render()
|
python
|
def next_batch(self, _):
"Handler for 'Next Batch' button click. Delete all flagged images and renders next batch."
for img_widget, delete_btn, fp, in self._batch:
fp = delete_btn.file_path
if (delete_btn.flagged_for_delete == True):
self.delete_image(fp)
self._deleted_fns.append(fp)
self._all_images = self._all_images[self._batch_size:]
self.empty_batch()
self.render()
|
[
"def",
"next_batch",
"(",
"self",
",",
"_",
")",
":",
"for",
"img_widget",
",",
"delete_btn",
",",
"fp",
",",
"in",
"self",
".",
"_batch",
":",
"fp",
"=",
"delete_btn",
".",
"file_path",
"if",
"(",
"delete_btn",
".",
"flagged_for_delete",
"==",
"True",
")",
":",
"self",
".",
"delete_image",
"(",
"fp",
")",
"self",
".",
"_deleted_fns",
".",
"append",
"(",
"fp",
")",
"self",
".",
"_all_images",
"=",
"self",
".",
"_all_images",
"[",
"self",
".",
"_batch_size",
":",
"]",
"self",
".",
"empty_batch",
"(",
")",
"self",
".",
"render",
"(",
")"
] |
Handler for 'Next Batch' button click. Delete all flagged images and renders next batch.
|
[
"Handler",
"for",
"Next",
"Batch",
"button",
"click",
".",
"Delete",
"all",
"flagged",
"images",
"and",
"renders",
"next",
"batch",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L165-L174
|
20,662
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.on_delete
|
def on_delete(self, btn):
"Flag this image as delete or keep."
btn.button_style = "" if btn.flagged_for_delete else "danger"
btn.flagged_for_delete = not btn.flagged_for_delete
|
python
|
def on_delete(self, btn):
"Flag this image as delete or keep."
btn.button_style = "" if btn.flagged_for_delete else "danger"
btn.flagged_for_delete = not btn.flagged_for_delete
|
[
"def",
"on_delete",
"(",
"self",
",",
"btn",
")",
":",
"btn",
".",
"button_style",
"=",
"\"\"",
"if",
"btn",
".",
"flagged_for_delete",
"else",
"\"danger\"",
"btn",
".",
"flagged_for_delete",
"=",
"not",
"btn",
".",
"flagged_for_delete"
] |
Flag this image as delete or keep.
|
[
"Flag",
"this",
"image",
"as",
"delete",
"or",
"keep",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L176-L179
|
20,663
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.get_widgets
|
def get_widgets(self, duplicates):
"Create and format widget set."
widgets = []
for (img,fp,human_readable_label) in self._all_images[:self._batch_size]:
img_widget = self.make_img_widget(img, layout=Layout(height='250px', width='300px'))
dropdown = self.make_dropdown_widget(description='', options=self._labels, value=human_readable_label,
file_path=fp, handler=self.relabel, layout=Layout(width='auto'))
delete_btn = self.make_button_widget('Delete', file_path=fp, handler=self.on_delete)
widgets.append(self.make_vertical_box([img_widget, dropdown, delete_btn],
layout=Layout(width='auto', height='300px',
overflow_x="hidden"), duplicates=duplicates))
self._batch.append((img_widget, delete_btn, fp))
return widgets
|
python
|
def get_widgets(self, duplicates):
"Create and format widget set."
widgets = []
for (img,fp,human_readable_label) in self._all_images[:self._batch_size]:
img_widget = self.make_img_widget(img, layout=Layout(height='250px', width='300px'))
dropdown = self.make_dropdown_widget(description='', options=self._labels, value=human_readable_label,
file_path=fp, handler=self.relabel, layout=Layout(width='auto'))
delete_btn = self.make_button_widget('Delete', file_path=fp, handler=self.on_delete)
widgets.append(self.make_vertical_box([img_widget, dropdown, delete_btn],
layout=Layout(width='auto', height='300px',
overflow_x="hidden"), duplicates=duplicates))
self._batch.append((img_widget, delete_btn, fp))
return widgets
|
[
"def",
"get_widgets",
"(",
"self",
",",
"duplicates",
")",
":",
"widgets",
"=",
"[",
"]",
"for",
"(",
"img",
",",
"fp",
",",
"human_readable_label",
")",
"in",
"self",
".",
"_all_images",
"[",
":",
"self",
".",
"_batch_size",
"]",
":",
"img_widget",
"=",
"self",
".",
"make_img_widget",
"(",
"img",
",",
"layout",
"=",
"Layout",
"(",
"height",
"=",
"'250px'",
",",
"width",
"=",
"'300px'",
")",
")",
"dropdown",
"=",
"self",
".",
"make_dropdown_widget",
"(",
"description",
"=",
"''",
",",
"options",
"=",
"self",
".",
"_labels",
",",
"value",
"=",
"human_readable_label",
",",
"file_path",
"=",
"fp",
",",
"handler",
"=",
"self",
".",
"relabel",
",",
"layout",
"=",
"Layout",
"(",
"width",
"=",
"'auto'",
")",
")",
"delete_btn",
"=",
"self",
".",
"make_button_widget",
"(",
"'Delete'",
",",
"file_path",
"=",
"fp",
",",
"handler",
"=",
"self",
".",
"on_delete",
")",
"widgets",
".",
"append",
"(",
"self",
".",
"make_vertical_box",
"(",
"[",
"img_widget",
",",
"dropdown",
",",
"delete_btn",
"]",
",",
"layout",
"=",
"Layout",
"(",
"width",
"=",
"'auto'",
",",
"height",
"=",
"'300px'",
",",
"overflow_x",
"=",
"\"hidden\"",
")",
",",
"duplicates",
"=",
"duplicates",
")",
")",
"self",
".",
"_batch",
".",
"append",
"(",
"(",
"img_widget",
",",
"delete_btn",
",",
"fp",
")",
")",
"return",
"widgets"
] |
Create and format widget set.
|
[
"Create",
"and",
"format",
"widget",
"set",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L189-L201
|
20,664
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.batch_contains_deleted
|
def batch_contains_deleted(self):
"Check if current batch contains already deleted images."
if not self._duplicates: return False
imgs = [self._all_images[:self._batch_size][0][1], self._all_images[:self._batch_size][1][1]]
return any(img in self._deleted_fns for img in imgs)
|
python
|
def batch_contains_deleted(self):
"Check if current batch contains already deleted images."
if not self._duplicates: return False
imgs = [self._all_images[:self._batch_size][0][1], self._all_images[:self._batch_size][1][1]]
return any(img in self._deleted_fns for img in imgs)
|
[
"def",
"batch_contains_deleted",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_duplicates",
":",
"return",
"False",
"imgs",
"=",
"[",
"self",
".",
"_all_images",
"[",
":",
"self",
".",
"_batch_size",
"]",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"self",
".",
"_all_images",
"[",
":",
"self",
".",
"_batch_size",
"]",
"[",
"1",
"]",
"[",
"1",
"]",
"]",
"return",
"any",
"(",
"img",
"in",
"self",
".",
"_deleted_fns",
"for",
"img",
"in",
"imgs",
")"
] |
Check if current batch contains already deleted images.
|
[
"Check",
"if",
"current",
"batch",
"contains",
"already",
"deleted",
"images",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L203-L207
|
20,665
|
fastai/fastai
|
fastai/widgets/image_cleaner.py
|
ImageCleaner.render
|
def render(self):
"Re-render Jupyter cell for batch of images."
clear_output()
self.write_csv()
if self.empty() and self._skipped>0:
return display(f'No images to show :). {self._skipped} pairs were '
f'skipped since at least one of the images was deleted by the user.')
elif self.empty():
return display('No images to show :)')
if self.batch_contains_deleted():
self.next_batch(None)
self._skipped += 1
else:
display(self.make_horizontal_box(self.get_widgets(self._duplicates)))
display(self.make_button_widget('Next Batch', handler=self.next_batch, style="primary"))
|
python
|
def render(self):
"Re-render Jupyter cell for batch of images."
clear_output()
self.write_csv()
if self.empty() and self._skipped>0:
return display(f'No images to show :). {self._skipped} pairs were '
f'skipped since at least one of the images was deleted by the user.')
elif self.empty():
return display('No images to show :)')
if self.batch_contains_deleted():
self.next_batch(None)
self._skipped += 1
else:
display(self.make_horizontal_box(self.get_widgets(self._duplicates)))
display(self.make_button_widget('Next Batch', handler=self.next_batch, style="primary"))
|
[
"def",
"render",
"(",
"self",
")",
":",
"clear_output",
"(",
")",
"self",
".",
"write_csv",
"(",
")",
"if",
"self",
".",
"empty",
"(",
")",
"and",
"self",
".",
"_skipped",
">",
"0",
":",
"return",
"display",
"(",
"f'No images to show :). {self._skipped} pairs were '",
"f'skipped since at least one of the images was deleted by the user.'",
")",
"elif",
"self",
".",
"empty",
"(",
")",
":",
"return",
"display",
"(",
"'No images to show :)'",
")",
"if",
"self",
".",
"batch_contains_deleted",
"(",
")",
":",
"self",
".",
"next_batch",
"(",
"None",
")",
"self",
".",
"_skipped",
"+=",
"1",
"else",
":",
"display",
"(",
"self",
".",
"make_horizontal_box",
"(",
"self",
".",
"get_widgets",
"(",
"self",
".",
"_duplicates",
")",
")",
")",
"display",
"(",
"self",
".",
"make_button_widget",
"(",
"'Next Batch'",
",",
"handler",
"=",
"self",
".",
"next_batch",
",",
"style",
"=",
"\"primary\"",
")",
")"
] |
Re-render Jupyter cell for batch of images.
|
[
"Re",
"-",
"render",
"Jupyter",
"cell",
"for",
"batch",
"of",
"images",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_cleaner.py#L220-L234
|
20,666
|
fastai/fastai
|
fastai/text/models/transformer.py
|
_line_shift
|
def _line_shift(x:Tensor, mask:bool=False):
"Shift the line i of `x` by p-i elements to the left, is `mask` puts 0s on the diagonal."
bs,nh,n,p = x.size()
x_pad = torch.cat([x.new_zeros(bs,nh,n,1), x], dim=3)
x_shift = x_pad.view(bs,nh,p + 1,n)[:,:,1:].view_as(x)
if mask: x_shift.mul_(torch.tril(x.new_ones(n,p), p-n)[None,None,])
return x_shift
|
python
|
def _line_shift(x:Tensor, mask:bool=False):
"Shift the line i of `x` by p-i elements to the left, is `mask` puts 0s on the diagonal."
bs,nh,n,p = x.size()
x_pad = torch.cat([x.new_zeros(bs,nh,n,1), x], dim=3)
x_shift = x_pad.view(bs,nh,p + 1,n)[:,:,1:].view_as(x)
if mask: x_shift.mul_(torch.tril(x.new_ones(n,p), p-n)[None,None,])
return x_shift
|
[
"def",
"_line_shift",
"(",
"x",
":",
"Tensor",
",",
"mask",
":",
"bool",
"=",
"False",
")",
":",
"bs",
",",
"nh",
",",
"n",
",",
"p",
"=",
"x",
".",
"size",
"(",
")",
"x_pad",
"=",
"torch",
".",
"cat",
"(",
"[",
"x",
".",
"new_zeros",
"(",
"bs",
",",
"nh",
",",
"n",
",",
"1",
")",
",",
"x",
"]",
",",
"dim",
"=",
"3",
")",
"x_shift",
"=",
"x_pad",
".",
"view",
"(",
"bs",
",",
"nh",
",",
"p",
"+",
"1",
",",
"n",
")",
"[",
":",
",",
":",
",",
"1",
":",
"]",
".",
"view_as",
"(",
"x",
")",
"if",
"mask",
":",
"x_shift",
".",
"mul_",
"(",
"torch",
".",
"tril",
"(",
"x",
".",
"new_ones",
"(",
"n",
",",
"p",
")",
",",
"p",
"-",
"n",
")",
"[",
"None",
",",
"None",
",",
"]",
")",
"return",
"x_shift"
] |
Shift the line i of `x` by p-i elements to the left, is `mask` puts 0s on the diagonal.
|
[
"Shift",
"the",
"line",
"i",
"of",
"x",
"by",
"p",
"-",
"i",
"elements",
"to",
"the",
"left",
"is",
"mask",
"puts",
"0s",
"on",
"the",
"diagonal",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/models/transformer.py#L85-L91
|
20,667
|
fastai/fastai
|
fastai/text/models/transformer.py
|
TransformerXL.reset
|
def reset(self):
"Reset the internal memory."
self.hidden = [next(self.parameters()).data.new(0) for i in range(self.n_layers+1)]
|
python
|
def reset(self):
"Reset the internal memory."
self.hidden = [next(self.parameters()).data.new(0) for i in range(self.n_layers+1)]
|
[
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"hidden",
"=",
"[",
"next",
"(",
"self",
".",
"parameters",
"(",
")",
")",
".",
"data",
".",
"new",
"(",
"0",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"n_layers",
"+",
"1",
")",
"]"
] |
Reset the internal memory.
|
[
"Reset",
"the",
"internal",
"memory",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/models/transformer.py#L198-L200
|
20,668
|
fastai/fastai
|
docs_src/nbval/nbdime_reporter.py
|
NbdimeReporter.make_report
|
def make_report(self, outcome):
"""Make report in form of two notebooks.
Use nbdime diff-web to present the difference between reference
cells and test cells.
"""
failures = self.getreports('failed')
if not failures:
return
for rep in failures:
# Check if this is a notebook node
msg = self._getfailureheadline(rep)
lines = rep.longrepr.splitlines()
if len(lines) > 1:
self.section(msg, lines[1])
self._outrep_summary(rep)
tmpdir = tempfile.mkdtemp()
try:
ref_file = os.path.join(tmpdir, 'reference.ipynb')
test_file = os.path.join(tmpdir, 'test_result.ipynb')
with io.open(ref_file, "w", encoding="utf8") as f:
nbformat.write(self.nb_ref, f)
with io.open(test_file, "w", encoding="utf8") as f:
nbformat.write(self.nb_test, f)
run_server(
port=0, # Run on random port
cwd=tmpdir,
closable=True,
on_port=lambda port: browse(
port, ref_file, test_file, None))
finally:
shutil.rmtree(tmpdir)
|
python
|
def make_report(self, outcome):
"""Make report in form of two notebooks.
Use nbdime diff-web to present the difference between reference
cells and test cells.
"""
failures = self.getreports('failed')
if not failures:
return
for rep in failures:
# Check if this is a notebook node
msg = self._getfailureheadline(rep)
lines = rep.longrepr.splitlines()
if len(lines) > 1:
self.section(msg, lines[1])
self._outrep_summary(rep)
tmpdir = tempfile.mkdtemp()
try:
ref_file = os.path.join(tmpdir, 'reference.ipynb')
test_file = os.path.join(tmpdir, 'test_result.ipynb')
with io.open(ref_file, "w", encoding="utf8") as f:
nbformat.write(self.nb_ref, f)
with io.open(test_file, "w", encoding="utf8") as f:
nbformat.write(self.nb_test, f)
run_server(
port=0, # Run on random port
cwd=tmpdir,
closable=True,
on_port=lambda port: browse(
port, ref_file, test_file, None))
finally:
shutil.rmtree(tmpdir)
|
[
"def",
"make_report",
"(",
"self",
",",
"outcome",
")",
":",
"failures",
"=",
"self",
".",
"getreports",
"(",
"'failed'",
")",
"if",
"not",
"failures",
":",
"return",
"for",
"rep",
"in",
"failures",
":",
"# Check if this is a notebook node",
"msg",
"=",
"self",
".",
"_getfailureheadline",
"(",
"rep",
")",
"lines",
"=",
"rep",
".",
"longrepr",
".",
"splitlines",
"(",
")",
"if",
"len",
"(",
"lines",
")",
">",
"1",
":",
"self",
".",
"section",
"(",
"msg",
",",
"lines",
"[",
"1",
"]",
")",
"self",
".",
"_outrep_summary",
"(",
"rep",
")",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"try",
":",
"ref_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"'reference.ipynb'",
")",
"test_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"'test_result.ipynb'",
")",
"with",
"io",
".",
"open",
"(",
"ref_file",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf8\"",
")",
"as",
"f",
":",
"nbformat",
".",
"write",
"(",
"self",
".",
"nb_ref",
",",
"f",
")",
"with",
"io",
".",
"open",
"(",
"test_file",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf8\"",
")",
"as",
"f",
":",
"nbformat",
".",
"write",
"(",
"self",
".",
"nb_test",
",",
"f",
")",
"run_server",
"(",
"port",
"=",
"0",
",",
"# Run on random port",
"cwd",
"=",
"tmpdir",
",",
"closable",
"=",
"True",
",",
"on_port",
"=",
"lambda",
"port",
":",
"browse",
"(",
"port",
",",
"ref_file",
",",
"test_file",
",",
"None",
")",
")",
"finally",
":",
"shutil",
".",
"rmtree",
"(",
"tmpdir",
")"
] |
Make report in form of two notebooks.
Use nbdime diff-web to present the difference between reference
cells and test cells.
|
[
"Make",
"report",
"in",
"form",
"of",
"two",
"notebooks",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/nbdime_reporter.py#L76-L107
|
20,669
|
fastai/fastai
|
old/fastai/fp16.py
|
batchnorm_to_fp32
|
def batchnorm_to_fp32(module):
'''
BatchNorm layers to have parameters in single precision.
Find all layers and convert them back to float. This can't
be done with built in .apply as that function will apply
fn to all modules, parameters, and buffers. Thus we wouldn't
be able to guard the float conversion based on the module type.
'''
if isinstance(module, nn.modules.batchnorm._BatchNorm):
module.float()
for child in module.children():
batchnorm_to_fp32(child)
return module
|
python
|
def batchnorm_to_fp32(module):
'''
BatchNorm layers to have parameters in single precision.
Find all layers and convert them back to float. This can't
be done with built in .apply as that function will apply
fn to all modules, parameters, and buffers. Thus we wouldn't
be able to guard the float conversion based on the module type.
'''
if isinstance(module, nn.modules.batchnorm._BatchNorm):
module.float()
for child in module.children():
batchnorm_to_fp32(child)
return module
|
[
"def",
"batchnorm_to_fp32",
"(",
"module",
")",
":",
"if",
"isinstance",
"(",
"module",
",",
"nn",
".",
"modules",
".",
"batchnorm",
".",
"_BatchNorm",
")",
":",
"module",
".",
"float",
"(",
")",
"for",
"child",
"in",
"module",
".",
"children",
"(",
")",
":",
"batchnorm_to_fp32",
"(",
"child",
")",
"return",
"module"
] |
BatchNorm layers to have parameters in single precision.
Find all layers and convert them back to float. This can't
be done with built in .apply as that function will apply
fn to all modules, parameters, and buffers. Thus we wouldn't
be able to guard the float conversion based on the module type.
|
[
"BatchNorm",
"layers",
"to",
"have",
"parameters",
"in",
"single",
"precision",
".",
"Find",
"all",
"layers",
"and",
"convert",
"them",
"back",
"to",
"float",
".",
"This",
"can",
"t",
"be",
"done",
"with",
"built",
"in",
".",
"apply",
"as",
"that",
"function",
"will",
"apply",
"fn",
"to",
"all",
"modules",
"parameters",
"and",
"buffers",
".",
"Thus",
"we",
"wouldn",
"t",
"be",
"able",
"to",
"guard",
"the",
"float",
"conversion",
"based",
"on",
"the",
"module",
"type",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/fp16.py#L31-L43
|
20,670
|
fastai/fastai
|
old/fastai/fp16.py
|
copy_model_to_fp32
|
def copy_model_to_fp32(m, optim):
""" Creates a fp32 copy of model parameters and sets optimizer parameters
"""
fp32_params = [m_param.clone().type(torch.cuda.FloatTensor).detach() for m_param in trainable_params_(m)]
optim_groups = [group['params'] for group in optim.param_groups]
iter_fp32_params = iter(fp32_params)
for group_params in optim_groups:
for i in range(len(group_params)):
if not group_params[i].requires_grad: continue # only update trainable_params_
fp32_param = next(iter_fp32_params)
assert(fp32_param.shape == group_params[i].shape)
fp32_param.requires_grad = group_params[i].requires_grad
group_params[i] = fp32_param
return fp32_params
|
python
|
def copy_model_to_fp32(m, optim):
""" Creates a fp32 copy of model parameters and sets optimizer parameters
"""
fp32_params = [m_param.clone().type(torch.cuda.FloatTensor).detach() for m_param in trainable_params_(m)]
optim_groups = [group['params'] for group in optim.param_groups]
iter_fp32_params = iter(fp32_params)
for group_params in optim_groups:
for i in range(len(group_params)):
if not group_params[i].requires_grad: continue # only update trainable_params_
fp32_param = next(iter_fp32_params)
assert(fp32_param.shape == group_params[i].shape)
fp32_param.requires_grad = group_params[i].requires_grad
group_params[i] = fp32_param
return fp32_params
|
[
"def",
"copy_model_to_fp32",
"(",
"m",
",",
"optim",
")",
":",
"fp32_params",
"=",
"[",
"m_param",
".",
"clone",
"(",
")",
".",
"type",
"(",
"torch",
".",
"cuda",
".",
"FloatTensor",
")",
".",
"detach",
"(",
")",
"for",
"m_param",
"in",
"trainable_params_",
"(",
"m",
")",
"]",
"optim_groups",
"=",
"[",
"group",
"[",
"'params'",
"]",
"for",
"group",
"in",
"optim",
".",
"param_groups",
"]",
"iter_fp32_params",
"=",
"iter",
"(",
"fp32_params",
")",
"for",
"group_params",
"in",
"optim_groups",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"group_params",
")",
")",
":",
"if",
"not",
"group_params",
"[",
"i",
"]",
".",
"requires_grad",
":",
"continue",
"# only update trainable_params_",
"fp32_param",
"=",
"next",
"(",
"iter_fp32_params",
")",
"assert",
"(",
"fp32_param",
".",
"shape",
"==",
"group_params",
"[",
"i",
"]",
".",
"shape",
")",
"fp32_param",
".",
"requires_grad",
"=",
"group_params",
"[",
"i",
"]",
".",
"requires_grad",
"group_params",
"[",
"i",
"]",
"=",
"fp32_param",
"return",
"fp32_params"
] |
Creates a fp32 copy of model parameters and sets optimizer parameters
|
[
"Creates",
"a",
"fp32",
"copy",
"of",
"model",
"parameters",
"and",
"sets",
"optimizer",
"parameters"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/fp16.py#L45-L58
|
20,671
|
fastai/fastai
|
docs_src/nbval/cover.py
|
setup_coverage
|
def setup_coverage(config, kernel, floc, output_loc=None):
"""Start coverage reporting in kernel.
Currently supported kernel languages are:
- Python
"""
language = kernel.language
if language.startswith('python'):
# Get the pytest-cov coverage object
cov = get_cov(config)
if cov:
# If present, copy the data file location used by pytest-cov
data_file = os.path.abspath(cov.config.data_file)
else:
# Fall back on output_loc and current dir if not
data_file = os.path.abspath(os.path.join(output_loc or os.getcwd(), '.coverage'))
# Get options from pytest-cov's command line arguments:
source = config.option.cov_source
config_file = config.option.cov_config
if isinstance(config_file, str) and os.path.isfile(config_file):
config_file = os.path.abspath(config_file)
# Copy the suffix of plugin if available
suffix = _make_suffix(cov)
if suffix is True:
# Cannot merge data with autogen suffix, so turn off warning
# for missing data in pytest-cov collector
cov._warn_no_data = False
# Build setup command and execute in kernel:
cmd = _python_setup % (data_file, source, config_file, suffix)
msg_id = kernel.kc.execute(cmd, stop_on_error=False)
kernel.await_idle(msg_id, 60) # A minute should be plenty to enable coverage
else:
config.warn(
'C1',
'Coverage currently not supported for language "%s".' % language,
floc)
return
|
python
|
def setup_coverage(config, kernel, floc, output_loc=None):
"""Start coverage reporting in kernel.
Currently supported kernel languages are:
- Python
"""
language = kernel.language
if language.startswith('python'):
# Get the pytest-cov coverage object
cov = get_cov(config)
if cov:
# If present, copy the data file location used by pytest-cov
data_file = os.path.abspath(cov.config.data_file)
else:
# Fall back on output_loc and current dir if not
data_file = os.path.abspath(os.path.join(output_loc or os.getcwd(), '.coverage'))
# Get options from pytest-cov's command line arguments:
source = config.option.cov_source
config_file = config.option.cov_config
if isinstance(config_file, str) and os.path.isfile(config_file):
config_file = os.path.abspath(config_file)
# Copy the suffix of plugin if available
suffix = _make_suffix(cov)
if suffix is True:
# Cannot merge data with autogen suffix, so turn off warning
# for missing data in pytest-cov collector
cov._warn_no_data = False
# Build setup command and execute in kernel:
cmd = _python_setup % (data_file, source, config_file, suffix)
msg_id = kernel.kc.execute(cmd, stop_on_error=False)
kernel.await_idle(msg_id, 60) # A minute should be plenty to enable coverage
else:
config.warn(
'C1',
'Coverage currently not supported for language "%s".' % language,
floc)
return
|
[
"def",
"setup_coverage",
"(",
"config",
",",
"kernel",
",",
"floc",
",",
"output_loc",
"=",
"None",
")",
":",
"language",
"=",
"kernel",
".",
"language",
"if",
"language",
".",
"startswith",
"(",
"'python'",
")",
":",
"# Get the pytest-cov coverage object",
"cov",
"=",
"get_cov",
"(",
"config",
")",
"if",
"cov",
":",
"# If present, copy the data file location used by pytest-cov",
"data_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"cov",
".",
"config",
".",
"data_file",
")",
"else",
":",
"# Fall back on output_loc and current dir if not",
"data_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output_loc",
"or",
"os",
".",
"getcwd",
"(",
")",
",",
"'.coverage'",
")",
")",
"# Get options from pytest-cov's command line arguments:",
"source",
"=",
"config",
".",
"option",
".",
"cov_source",
"config_file",
"=",
"config",
".",
"option",
".",
"cov_config",
"if",
"isinstance",
"(",
"config_file",
",",
"str",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"config_file",
")",
":",
"config_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"config_file",
")",
"# Copy the suffix of plugin if available",
"suffix",
"=",
"_make_suffix",
"(",
"cov",
")",
"if",
"suffix",
"is",
"True",
":",
"# Cannot merge data with autogen suffix, so turn off warning",
"# for missing data in pytest-cov collector",
"cov",
".",
"_warn_no_data",
"=",
"False",
"# Build setup command and execute in kernel:",
"cmd",
"=",
"_python_setup",
"%",
"(",
"data_file",
",",
"source",
",",
"config_file",
",",
"suffix",
")",
"msg_id",
"=",
"kernel",
".",
"kc",
".",
"execute",
"(",
"cmd",
",",
"stop_on_error",
"=",
"False",
")",
"kernel",
".",
"await_idle",
"(",
"msg_id",
",",
"60",
")",
"# A minute should be plenty to enable coverage",
"else",
":",
"config",
".",
"warn",
"(",
"'C1'",
",",
"'Coverage currently not supported for language \"%s\".'",
"%",
"language",
",",
"floc",
")",
"return"
] |
Start coverage reporting in kernel.
Currently supported kernel languages are:
- Python
|
[
"Start",
"coverage",
"reporting",
"in",
"kernel",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/cover.py#L33-L73
|
20,672
|
fastai/fastai
|
docs_src/nbval/cover.py
|
teardown_coverage
|
def teardown_coverage(config, kernel, output_loc=None):
"""Finish coverage reporting in kernel.
The coverage should previously have been started with
setup_coverage.
"""
language = kernel.language
if language.startswith('python'):
# Teardown code does not require any input, simply execute:
msg_id = kernel.kc.execute(_python_teardown)
kernel.await_idle(msg_id, 60) # A minute should be plenty to write out coverage
# Ensure we merge our data into parent data of pytest-cov, if possible
cov = get_cov(config)
_merge_nbval_coverage_data(cov)
else:
# Warnings should be given on setup, or there might be no teardown
# for a specific language, so do nothing here
pass
|
python
|
def teardown_coverage(config, kernel, output_loc=None):
"""Finish coverage reporting in kernel.
The coverage should previously have been started with
setup_coverage.
"""
language = kernel.language
if language.startswith('python'):
# Teardown code does not require any input, simply execute:
msg_id = kernel.kc.execute(_python_teardown)
kernel.await_idle(msg_id, 60) # A minute should be plenty to write out coverage
# Ensure we merge our data into parent data of pytest-cov, if possible
cov = get_cov(config)
_merge_nbval_coverage_data(cov)
else:
# Warnings should be given on setup, or there might be no teardown
# for a specific language, so do nothing here
pass
|
[
"def",
"teardown_coverage",
"(",
"config",
",",
"kernel",
",",
"output_loc",
"=",
"None",
")",
":",
"language",
"=",
"kernel",
".",
"language",
"if",
"language",
".",
"startswith",
"(",
"'python'",
")",
":",
"# Teardown code does not require any input, simply execute:",
"msg_id",
"=",
"kernel",
".",
"kc",
".",
"execute",
"(",
"_python_teardown",
")",
"kernel",
".",
"await_idle",
"(",
"msg_id",
",",
"60",
")",
"# A minute should be plenty to write out coverage",
"# Ensure we merge our data into parent data of pytest-cov, if possible",
"cov",
"=",
"get_cov",
"(",
"config",
")",
"_merge_nbval_coverage_data",
"(",
"cov",
")",
"else",
":",
"# Warnings should be given on setup, or there might be no teardown",
"# for a specific language, so do nothing here",
"pass"
] |
Finish coverage reporting in kernel.
The coverage should previously have been started with
setup_coverage.
|
[
"Finish",
"coverage",
"reporting",
"in",
"kernel",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/cover.py#L76-L95
|
20,673
|
fastai/fastai
|
docs_src/nbval/cover.py
|
get_cov
|
def get_cov(config):
"""Returns the coverage object of pytest-cov."""
# Check with hasplugin to avoid getplugin exception in older pytest.
if config.pluginmanager.hasplugin('_cov'):
plugin = config.pluginmanager.getplugin('_cov')
if plugin.cov_controller:
return plugin.cov_controller.cov
return None
|
python
|
def get_cov(config):
"""Returns the coverage object of pytest-cov."""
# Check with hasplugin to avoid getplugin exception in older pytest.
if config.pluginmanager.hasplugin('_cov'):
plugin = config.pluginmanager.getplugin('_cov')
if plugin.cov_controller:
return plugin.cov_controller.cov
return None
|
[
"def",
"get_cov",
"(",
"config",
")",
":",
"# Check with hasplugin to avoid getplugin exception in older pytest.",
"if",
"config",
".",
"pluginmanager",
".",
"hasplugin",
"(",
"'_cov'",
")",
":",
"plugin",
"=",
"config",
".",
"pluginmanager",
".",
"getplugin",
"(",
"'_cov'",
")",
"if",
"plugin",
".",
"cov_controller",
":",
"return",
"plugin",
".",
"cov_controller",
".",
"cov",
"return",
"None"
] |
Returns the coverage object of pytest-cov.
|
[
"Returns",
"the",
"coverage",
"object",
"of",
"pytest",
"-",
"cov",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/cover.py#L98-L106
|
20,674
|
fastai/fastai
|
docs_src/nbval/cover.py
|
_make_suffix
|
def _make_suffix(cov):
"""Create a suffix for nbval data file depending on pytest-cov config."""
# Check if coverage object has data_suffix:
if cov and cov.data_suffix is not None:
# If True, the suffix will be autogenerated by coverage.py.
# The suffixed data files will be automatically combined later.
if cov.data_suffix is True:
return True
# Has a suffix, but we add our own extension
return cov.data_suffix + '.nbval'
return 'nbval'
|
python
|
def _make_suffix(cov):
"""Create a suffix for nbval data file depending on pytest-cov config."""
# Check if coverage object has data_suffix:
if cov and cov.data_suffix is not None:
# If True, the suffix will be autogenerated by coverage.py.
# The suffixed data files will be automatically combined later.
if cov.data_suffix is True:
return True
# Has a suffix, but we add our own extension
return cov.data_suffix + '.nbval'
return 'nbval'
|
[
"def",
"_make_suffix",
"(",
"cov",
")",
":",
"# Check if coverage object has data_suffix:",
"if",
"cov",
"and",
"cov",
".",
"data_suffix",
"is",
"not",
"None",
":",
"# If True, the suffix will be autogenerated by coverage.py.",
"# The suffixed data files will be automatically combined later.",
"if",
"cov",
".",
"data_suffix",
"is",
"True",
":",
"return",
"True",
"# Has a suffix, but we add our own extension",
"return",
"cov",
".",
"data_suffix",
"+",
"'.nbval'",
"return",
"'nbval'"
] |
Create a suffix for nbval data file depending on pytest-cov config.
|
[
"Create",
"a",
"suffix",
"for",
"nbval",
"data",
"file",
"depending",
"on",
"pytest",
"-",
"cov",
"config",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/cover.py#L109-L119
|
20,675
|
fastai/fastai
|
docs_src/nbval/cover.py
|
_merge_nbval_coverage_data
|
def _merge_nbval_coverage_data(cov):
"""Merge nbval coverage data into pytest-cov data."""
if not cov:
return
suffix = _make_suffix(cov)
if suffix is True:
# Note: If suffix is true, we are running in parallel, so several
# files will be generated. This will cause some warnings about "no coverage"
# but is otherwise OK. Do nothing.
return
# Get the filename of the nbval coverage:
filename = cov.data_files.filename + '.' + suffix
# Read coverage generated by nbval in this run:
nbval_data = coverage.CoverageData(debug=cov.debug)
try:
nbval_data.read_file(os.path.abspath(filename))
except coverage.CoverageException:
return
# Set up aliases (following internal coverage.py code here)
aliases = None
if cov.config.paths:
aliases = coverage.files.PathAliases()
for paths in cov.config.paths.values():
result = paths[0]
for pattern in paths[1:]:
aliases.add(pattern, result)
# Merge nbval data into pytest-cov data:
cov.data.update(nbval_data, aliases=aliases)
# Delete our nbval coverage data
coverage.misc.file_be_gone(filename)
|
python
|
def _merge_nbval_coverage_data(cov):
"""Merge nbval coverage data into pytest-cov data."""
if not cov:
return
suffix = _make_suffix(cov)
if suffix is True:
# Note: If suffix is true, we are running in parallel, so several
# files will be generated. This will cause some warnings about "no coverage"
# but is otherwise OK. Do nothing.
return
# Get the filename of the nbval coverage:
filename = cov.data_files.filename + '.' + suffix
# Read coverage generated by nbval in this run:
nbval_data = coverage.CoverageData(debug=cov.debug)
try:
nbval_data.read_file(os.path.abspath(filename))
except coverage.CoverageException:
return
# Set up aliases (following internal coverage.py code here)
aliases = None
if cov.config.paths:
aliases = coverage.files.PathAliases()
for paths in cov.config.paths.values():
result = paths[0]
for pattern in paths[1:]:
aliases.add(pattern, result)
# Merge nbval data into pytest-cov data:
cov.data.update(nbval_data, aliases=aliases)
# Delete our nbval coverage data
coverage.misc.file_be_gone(filename)
|
[
"def",
"_merge_nbval_coverage_data",
"(",
"cov",
")",
":",
"if",
"not",
"cov",
":",
"return",
"suffix",
"=",
"_make_suffix",
"(",
"cov",
")",
"if",
"suffix",
"is",
"True",
":",
"# Note: If suffix is true, we are running in parallel, so several",
"# files will be generated. This will cause some warnings about \"no coverage\"",
"# but is otherwise OK. Do nothing.",
"return",
"# Get the filename of the nbval coverage:",
"filename",
"=",
"cov",
".",
"data_files",
".",
"filename",
"+",
"'.'",
"+",
"suffix",
"# Read coverage generated by nbval in this run:",
"nbval_data",
"=",
"coverage",
".",
"CoverageData",
"(",
"debug",
"=",
"cov",
".",
"debug",
")",
"try",
":",
"nbval_data",
".",
"read_file",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
")",
"except",
"coverage",
".",
"CoverageException",
":",
"return",
"# Set up aliases (following internal coverage.py code here)",
"aliases",
"=",
"None",
"if",
"cov",
".",
"config",
".",
"paths",
":",
"aliases",
"=",
"coverage",
".",
"files",
".",
"PathAliases",
"(",
")",
"for",
"paths",
"in",
"cov",
".",
"config",
".",
"paths",
".",
"values",
"(",
")",
":",
"result",
"=",
"paths",
"[",
"0",
"]",
"for",
"pattern",
"in",
"paths",
"[",
"1",
":",
"]",
":",
"aliases",
".",
"add",
"(",
"pattern",
",",
"result",
")",
"# Merge nbval data into pytest-cov data:",
"cov",
".",
"data",
".",
"update",
"(",
"nbval_data",
",",
"aliases",
"=",
"aliases",
")",
"# Delete our nbval coverage data",
"coverage",
".",
"misc",
".",
"file_be_gone",
"(",
"filename",
")"
] |
Merge nbval coverage data into pytest-cov data.
|
[
"Merge",
"nbval",
"coverage",
"data",
"into",
"pytest",
"-",
"cov",
"data",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/cover.py#L122-L156
|
20,676
|
fastai/fastai
|
fastai/core.py
|
is1d
|
def is1d(a:Collection)->bool:
"Return `True` if `a` is one-dimensional"
return len(a.shape) == 1 if hasattr(a, 'shape') else True
|
python
|
def is1d(a:Collection)->bool:
"Return `True` if `a` is one-dimensional"
return len(a.shape) == 1 if hasattr(a, 'shape') else True
|
[
"def",
"is1d",
"(",
"a",
":",
"Collection",
")",
"->",
"bool",
":",
"return",
"len",
"(",
"a",
".",
"shape",
")",
"==",
"1",
"if",
"hasattr",
"(",
"a",
",",
"'shape'",
")",
"else",
"True"
] |
Return `True` if `a` is one-dimensional
|
[
"Return",
"True",
"if",
"a",
"is",
"one",
"-",
"dimensional"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L70-L72
|
20,677
|
fastai/fastai
|
fastai/core.py
|
uniqueify
|
def uniqueify(x:Series, sort:bool=False)->List:
"Return sorted unique values of `x`."
res = list(OrderedDict.fromkeys(x).keys())
if sort: res.sort()
return res
|
python
|
def uniqueify(x:Series, sort:bool=False)->List:
"Return sorted unique values of `x`."
res = list(OrderedDict.fromkeys(x).keys())
if sort: res.sort()
return res
|
[
"def",
"uniqueify",
"(",
"x",
":",
"Series",
",",
"sort",
":",
"bool",
"=",
"False",
")",
"->",
"List",
":",
"res",
"=",
"list",
"(",
"OrderedDict",
".",
"fromkeys",
"(",
"x",
")",
".",
"keys",
"(",
")",
")",
"if",
"sort",
":",
"res",
".",
"sort",
"(",
")",
"return",
"res"
] |
Return sorted unique values of `x`.
|
[
"Return",
"sorted",
"unique",
"values",
"of",
"x",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L74-L78
|
20,678
|
fastai/fastai
|
fastai/core.py
|
find_classes
|
def find_classes(folder:Path)->FilePathList:
"List of label subdirectories in imagenet-style `folder`."
classes = [d for d in folder.iterdir()
if d.is_dir() and not d.name.startswith('.')]
assert(len(classes)>0)
return sorted(classes, key=lambda d: d.name)
|
python
|
def find_classes(folder:Path)->FilePathList:
"List of label subdirectories in imagenet-style `folder`."
classes = [d for d in folder.iterdir()
if d.is_dir() and not d.name.startswith('.')]
assert(len(classes)>0)
return sorted(classes, key=lambda d: d.name)
|
[
"def",
"find_classes",
"(",
"folder",
":",
"Path",
")",
"->",
"FilePathList",
":",
"classes",
"=",
"[",
"d",
"for",
"d",
"in",
"folder",
".",
"iterdir",
"(",
")",
"if",
"d",
".",
"is_dir",
"(",
")",
"and",
"not",
"d",
".",
"name",
".",
"startswith",
"(",
"'.'",
")",
"]",
"assert",
"(",
"len",
"(",
"classes",
")",
">",
"0",
")",
"return",
"sorted",
"(",
"classes",
",",
"key",
"=",
"lambda",
"d",
":",
"d",
".",
"name",
")"
] |
List of label subdirectories in imagenet-style `folder`.
|
[
"List",
"of",
"label",
"subdirectories",
"in",
"imagenet",
"-",
"style",
"folder",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L84-L89
|
20,679
|
fastai/fastai
|
fastai/core.py
|
random_split
|
def random_split(valid_pct:float, *arrs:NPArrayableList)->SplitArrayList:
"Randomly split `arrs` with `valid_pct` ratio. good for creating validation set."
assert (valid_pct>=0 and valid_pct<=1), 'Validation set percentage should be between 0 and 1'
is_train = np.random.uniform(size=(len(arrs[0]),)) > valid_pct
return arrays_split(is_train, *arrs)
|
python
|
def random_split(valid_pct:float, *arrs:NPArrayableList)->SplitArrayList:
"Randomly split `arrs` with `valid_pct` ratio. good for creating validation set."
assert (valid_pct>=0 and valid_pct<=1), 'Validation set percentage should be between 0 and 1'
is_train = np.random.uniform(size=(len(arrs[0]),)) > valid_pct
return arrays_split(is_train, *arrs)
|
[
"def",
"random_split",
"(",
"valid_pct",
":",
"float",
",",
"*",
"arrs",
":",
"NPArrayableList",
")",
"->",
"SplitArrayList",
":",
"assert",
"(",
"valid_pct",
">=",
"0",
"and",
"valid_pct",
"<=",
"1",
")",
",",
"'Validation set percentage should be between 0 and 1'",
"is_train",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"(",
"len",
"(",
"arrs",
"[",
"0",
"]",
")",
",",
")",
")",
">",
"valid_pct",
"return",
"arrays_split",
"(",
"is_train",
",",
"*",
"arrs",
")"
] |
Randomly split `arrs` with `valid_pct` ratio. good for creating validation set.
|
[
"Randomly",
"split",
"arrs",
"with",
"valid_pct",
"ratio",
".",
"good",
"for",
"creating",
"validation",
"set",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L97-L101
|
20,680
|
fastai/fastai
|
fastai/core.py
|
listify
|
def listify(p:OptListOrItem=None, q:OptListOrItem=None):
"Make `p` listy and the same length as `q`."
if p is None: p=[]
elif isinstance(p, str): p = [p]
elif not isinstance(p, Iterable): p = [p]
#Rank 0 tensors in PyTorch are Iterable but don't have a length.
else:
try: a = len(p)
except: p = [p]
n = q if type(q)==int else len(p) if q is None else len(q)
if len(p)==1: p = p * n
assert len(p)==n, f'List len mismatch ({len(p)} vs {n})'
return list(p)
|
python
|
def listify(p:OptListOrItem=None, q:OptListOrItem=None):
"Make `p` listy and the same length as `q`."
if p is None: p=[]
elif isinstance(p, str): p = [p]
elif not isinstance(p, Iterable): p = [p]
#Rank 0 tensors in PyTorch are Iterable but don't have a length.
else:
try: a = len(p)
except: p = [p]
n = q if type(q)==int else len(p) if q is None else len(q)
if len(p)==1: p = p * n
assert len(p)==n, f'List len mismatch ({len(p)} vs {n})'
return list(p)
|
[
"def",
"listify",
"(",
"p",
":",
"OptListOrItem",
"=",
"None",
",",
"q",
":",
"OptListOrItem",
"=",
"None",
")",
":",
"if",
"p",
"is",
"None",
":",
"p",
"=",
"[",
"]",
"elif",
"isinstance",
"(",
"p",
",",
"str",
")",
":",
"p",
"=",
"[",
"p",
"]",
"elif",
"not",
"isinstance",
"(",
"p",
",",
"Iterable",
")",
":",
"p",
"=",
"[",
"p",
"]",
"#Rank 0 tensors in PyTorch are Iterable but don't have a length.",
"else",
":",
"try",
":",
"a",
"=",
"len",
"(",
"p",
")",
"except",
":",
"p",
"=",
"[",
"p",
"]",
"n",
"=",
"q",
"if",
"type",
"(",
"q",
")",
"==",
"int",
"else",
"len",
"(",
"p",
")",
"if",
"q",
"is",
"None",
"else",
"len",
"(",
"q",
")",
"if",
"len",
"(",
"p",
")",
"==",
"1",
":",
"p",
"=",
"p",
"*",
"n",
"assert",
"len",
"(",
"p",
")",
"==",
"n",
",",
"f'List len mismatch ({len(p)} vs {n})'",
"return",
"list",
"(",
"p",
")"
] |
Make `p` listy and the same length as `q`.
|
[
"Make",
"p",
"listy",
"and",
"the",
"same",
"length",
"as",
"q",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L103-L115
|
20,681
|
fastai/fastai
|
fastai/core.py
|
camel2snake
|
def camel2snake(name:str)->str:
"Change `name` from camel to snake style."
s1 = re.sub(_camel_re1, r'\1_\2', name)
return re.sub(_camel_re2, r'\1_\2', s1).lower()
|
python
|
def camel2snake(name:str)->str:
"Change `name` from camel to snake style."
s1 = re.sub(_camel_re1, r'\1_\2', name)
return re.sub(_camel_re2, r'\1_\2', s1).lower()
|
[
"def",
"camel2snake",
"(",
"name",
":",
"str",
")",
"->",
"str",
":",
"s1",
"=",
"re",
".",
"sub",
"(",
"_camel_re1",
",",
"r'\\1_\\2'",
",",
"name",
")",
"return",
"re",
".",
"sub",
"(",
"_camel_re2",
",",
"r'\\1_\\2'",
",",
"s1",
")",
".",
"lower",
"(",
")"
] |
Change `name` from camel to snake style.
|
[
"Change",
"name",
"from",
"camel",
"to",
"snake",
"style",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L119-L122
|
20,682
|
fastai/fastai
|
fastai/core.py
|
even_mults
|
def even_mults(start:float, stop:float, n:int)->np.ndarray:
"Build log-stepped array from `start` to `stop` in `n` steps."
mult = stop/start
step = mult**(1/(n-1))
return np.array([start*(step**i) for i in range(n)])
|
python
|
def even_mults(start:float, stop:float, n:int)->np.ndarray:
"Build log-stepped array from `start` to `stop` in `n` steps."
mult = stop/start
step = mult**(1/(n-1))
return np.array([start*(step**i) for i in range(n)])
|
[
"def",
"even_mults",
"(",
"start",
":",
"float",
",",
"stop",
":",
"float",
",",
"n",
":",
"int",
")",
"->",
"np",
".",
"ndarray",
":",
"mult",
"=",
"stop",
"/",
"start",
"step",
"=",
"mult",
"**",
"(",
"1",
"/",
"(",
"n",
"-",
"1",
")",
")",
"return",
"np",
".",
"array",
"(",
"[",
"start",
"*",
"(",
"step",
"**",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
")"
] |
Build log-stepped array from `start` to `stop` in `n` steps.
|
[
"Build",
"log",
"-",
"stepped",
"array",
"from",
"start",
"to",
"stop",
"in",
"n",
"steps",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L124-L128
|
20,683
|
fastai/fastai
|
fastai/core.py
|
extract_kwargs
|
def extract_kwargs(names:Collection[str], kwargs:KWArgs):
"Extract the keys in `names` from the `kwargs`."
new_kwargs = {}
for arg_name in names:
if arg_name in kwargs:
arg_val = kwargs.pop(arg_name)
new_kwargs[arg_name] = arg_val
return new_kwargs, kwargs
|
python
|
def extract_kwargs(names:Collection[str], kwargs:KWArgs):
"Extract the keys in `names` from the `kwargs`."
new_kwargs = {}
for arg_name in names:
if arg_name in kwargs:
arg_val = kwargs.pop(arg_name)
new_kwargs[arg_name] = arg_val
return new_kwargs, kwargs
|
[
"def",
"extract_kwargs",
"(",
"names",
":",
"Collection",
"[",
"str",
"]",
",",
"kwargs",
":",
"KWArgs",
")",
":",
"new_kwargs",
"=",
"{",
"}",
"for",
"arg_name",
"in",
"names",
":",
"if",
"arg_name",
"in",
"kwargs",
":",
"arg_val",
"=",
"kwargs",
".",
"pop",
"(",
"arg_name",
")",
"new_kwargs",
"[",
"arg_name",
"]",
"=",
"arg_val",
"return",
"new_kwargs",
",",
"kwargs"
] |
Extract the keys in `names` from the `kwargs`.
|
[
"Extract",
"the",
"keys",
"in",
"names",
"from",
"the",
"kwargs",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L130-L137
|
20,684
|
fastai/fastai
|
fastai/core.py
|
partition
|
def partition(a:Collection, sz:int)->List[Collection]:
"Split iterables `a` in equal parts of size `sz`"
return [a[i:i+sz] for i in range(0, len(a), sz)]
|
python
|
def partition(a:Collection, sz:int)->List[Collection]:
"Split iterables `a` in equal parts of size `sz`"
return [a[i:i+sz] for i in range(0, len(a), sz)]
|
[
"def",
"partition",
"(",
"a",
":",
"Collection",
",",
"sz",
":",
"int",
")",
"->",
"List",
"[",
"Collection",
"]",
":",
"return",
"[",
"a",
"[",
"i",
":",
"i",
"+",
"sz",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"a",
")",
",",
"sz",
")",
"]"
] |
Split iterables `a` in equal parts of size `sz`
|
[
"Split",
"iterables",
"a",
"in",
"equal",
"parts",
"of",
"size",
"sz"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L139-L141
|
20,685
|
fastai/fastai
|
fastai/core.py
|
partition_by_cores
|
def partition_by_cores(a:Collection, n_cpus:int)->List[Collection]:
"Split data in `a` equally among `n_cpus` cores"
return partition(a, len(a)//n_cpus + 1)
|
python
|
def partition_by_cores(a:Collection, n_cpus:int)->List[Collection]:
"Split data in `a` equally among `n_cpus` cores"
return partition(a, len(a)//n_cpus + 1)
|
[
"def",
"partition_by_cores",
"(",
"a",
":",
"Collection",
",",
"n_cpus",
":",
"int",
")",
"->",
"List",
"[",
"Collection",
"]",
":",
"return",
"partition",
"(",
"a",
",",
"len",
"(",
"a",
")",
"//",
"n_cpus",
"+",
"1",
")"
] |
Split data in `a` equally among `n_cpus` cores
|
[
"Split",
"data",
"in",
"a",
"equally",
"among",
"n_cpus",
"cores"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L143-L145
|
20,686
|
fastai/fastai
|
fastai/core.py
|
series2cat
|
def series2cat(df:DataFrame, *col_names):
"Categorifies the columns `col_names` in `df`."
for c in listify(col_names): df[c] = df[c].astype('category').cat.as_ordered()
|
python
|
def series2cat(df:DataFrame, *col_names):
"Categorifies the columns `col_names` in `df`."
for c in listify(col_names): df[c] = df[c].astype('category').cat.as_ordered()
|
[
"def",
"series2cat",
"(",
"df",
":",
"DataFrame",
",",
"*",
"col_names",
")",
":",
"for",
"c",
"in",
"listify",
"(",
"col_names",
")",
":",
"df",
"[",
"c",
"]",
"=",
"df",
"[",
"c",
"]",
".",
"astype",
"(",
"'category'",
")",
".",
"cat",
".",
"as_ordered",
"(",
")"
] |
Categorifies the columns `col_names` in `df`.
|
[
"Categorifies",
"the",
"columns",
"col_names",
"in",
"df",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L147-L149
|
20,687
|
fastai/fastai
|
fastai/core.py
|
download_url
|
def download_url(url:str, dest:str, overwrite:bool=False, pbar:ProgressBar=None,
show_progress=True, chunk_size=1024*1024, timeout=4, retries=5)->None:
"Download `url` to `dest` unless it exists and not `overwrite`."
if os.path.exists(dest) and not overwrite: return
s = requests.Session()
s.mount('http://',requests.adapters.HTTPAdapter(max_retries=retries))
u = s.get(url, stream=True, timeout=timeout)
try: file_size = int(u.headers["Content-Length"])
except: show_progress = False
with open(dest, 'wb') as f:
nbytes = 0
if show_progress: pbar = progress_bar(range(file_size), auto_update=False, leave=False, parent=pbar)
try:
for chunk in u.iter_content(chunk_size=chunk_size):
nbytes += len(chunk)
if show_progress: pbar.update(nbytes)
f.write(chunk)
except requests.exceptions.ConnectionError as e:
fname = url.split('/')[-1]
from fastai.datasets import Config
data_dir = Config().data_path()
timeout_txt =(f'\n Download of {url} has failed after {retries} retries\n'
f' Fix the download manually:\n'
f'$ mkdir -p {data_dir}\n'
f'$ cd {data_dir}\n'
f'$ wget -c {url}\n'
f'$ tar -zxvf {fname}\n\n'
f'And re-run your code once the download is successful\n')
print(timeout_txt)
import sys;sys.exit(1)
|
python
|
def download_url(url:str, dest:str, overwrite:bool=False, pbar:ProgressBar=None,
show_progress=True, chunk_size=1024*1024, timeout=4, retries=5)->None:
"Download `url` to `dest` unless it exists and not `overwrite`."
if os.path.exists(dest) and not overwrite: return
s = requests.Session()
s.mount('http://',requests.adapters.HTTPAdapter(max_retries=retries))
u = s.get(url, stream=True, timeout=timeout)
try: file_size = int(u.headers["Content-Length"])
except: show_progress = False
with open(dest, 'wb') as f:
nbytes = 0
if show_progress: pbar = progress_bar(range(file_size), auto_update=False, leave=False, parent=pbar)
try:
for chunk in u.iter_content(chunk_size=chunk_size):
nbytes += len(chunk)
if show_progress: pbar.update(nbytes)
f.write(chunk)
except requests.exceptions.ConnectionError as e:
fname = url.split('/')[-1]
from fastai.datasets import Config
data_dir = Config().data_path()
timeout_txt =(f'\n Download of {url} has failed after {retries} retries\n'
f' Fix the download manually:\n'
f'$ mkdir -p {data_dir}\n'
f'$ cd {data_dir}\n'
f'$ wget -c {url}\n'
f'$ tar -zxvf {fname}\n\n'
f'And re-run your code once the download is successful\n')
print(timeout_txt)
import sys;sys.exit(1)
|
[
"def",
"download_url",
"(",
"url",
":",
"str",
",",
"dest",
":",
"str",
",",
"overwrite",
":",
"bool",
"=",
"False",
",",
"pbar",
":",
"ProgressBar",
"=",
"None",
",",
"show_progress",
"=",
"True",
",",
"chunk_size",
"=",
"1024",
"*",
"1024",
",",
"timeout",
"=",
"4",
",",
"retries",
"=",
"5",
")",
"->",
"None",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
"and",
"not",
"overwrite",
":",
"return",
"s",
"=",
"requests",
".",
"Session",
"(",
")",
"s",
".",
"mount",
"(",
"'http://'",
",",
"requests",
".",
"adapters",
".",
"HTTPAdapter",
"(",
"max_retries",
"=",
"retries",
")",
")",
"u",
"=",
"s",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
",",
"timeout",
"=",
"timeout",
")",
"try",
":",
"file_size",
"=",
"int",
"(",
"u",
".",
"headers",
"[",
"\"Content-Length\"",
"]",
")",
"except",
":",
"show_progress",
"=",
"False",
"with",
"open",
"(",
"dest",
",",
"'wb'",
")",
"as",
"f",
":",
"nbytes",
"=",
"0",
"if",
"show_progress",
":",
"pbar",
"=",
"progress_bar",
"(",
"range",
"(",
"file_size",
")",
",",
"auto_update",
"=",
"False",
",",
"leave",
"=",
"False",
",",
"parent",
"=",
"pbar",
")",
"try",
":",
"for",
"chunk",
"in",
"u",
".",
"iter_content",
"(",
"chunk_size",
"=",
"chunk_size",
")",
":",
"nbytes",
"+=",
"len",
"(",
"chunk",
")",
"if",
"show_progress",
":",
"pbar",
".",
"update",
"(",
"nbytes",
")",
"f",
".",
"write",
"(",
"chunk",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
"as",
"e",
":",
"fname",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"from",
"fastai",
".",
"datasets",
"import",
"Config",
"data_dir",
"=",
"Config",
"(",
")",
".",
"data_path",
"(",
")",
"timeout_txt",
"=",
"(",
"f'\\n Download of {url} has failed after {retries} retries\\n'",
"f' Fix the download manually:\\n'",
"f'$ mkdir -p {data_dir}\\n'",
"f'$ cd {data_dir}\\n'",
"f'$ wget -c {url}\\n'",
"f'$ tar -zxvf {fname}\\n\\n'",
"f'And re-run your code once the download is successful\\n'",
")",
"print",
"(",
"timeout_txt",
")",
"import",
"sys",
"sys",
".",
"exit",
"(",
"1",
")"
] |
Download `url` to `dest` unless it exists and not `overwrite`.
|
[
"Download",
"url",
"to",
"dest",
"unless",
"it",
"exists",
"and",
"not",
"overwrite",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L170-L201
|
20,688
|
fastai/fastai
|
fastai/core.py
|
join_paths
|
def join_paths(fnames:FilePathList, path:PathOrStr='.')->Collection[Path]:
"Join `path` to every file name in `fnames`."
path = Path(path)
return [join_path(o,path) for o in fnames]
|
python
|
def join_paths(fnames:FilePathList, path:PathOrStr='.')->Collection[Path]:
"Join `path` to every file name in `fnames`."
path = Path(path)
return [join_path(o,path) for o in fnames]
|
[
"def",
"join_paths",
"(",
"fnames",
":",
"FilePathList",
",",
"path",
":",
"PathOrStr",
"=",
"'.'",
")",
"->",
"Collection",
"[",
"Path",
"]",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"return",
"[",
"join_path",
"(",
"o",
",",
"path",
")",
"for",
"o",
"in",
"fnames",
"]"
] |
Join `path` to every file name in `fnames`.
|
[
"Join",
"path",
"to",
"every",
"file",
"name",
"in",
"fnames",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L216-L219
|
20,689
|
fastai/fastai
|
fastai/core.py
|
loadtxt_str
|
def loadtxt_str(path:PathOrStr)->np.ndarray:
"Return `ndarray` of `str` of lines of text from `path`."
with open(path, 'r') as f: lines = f.readlines()
return np.array([l.strip() for l in lines])
|
python
|
def loadtxt_str(path:PathOrStr)->np.ndarray:
"Return `ndarray` of `str` of lines of text from `path`."
with open(path, 'r') as f: lines = f.readlines()
return np.array([l.strip() for l in lines])
|
[
"def",
"loadtxt_str",
"(",
"path",
":",
"PathOrStr",
")",
"->",
"np",
".",
"ndarray",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"return",
"np",
".",
"array",
"(",
"[",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"lines",
"]",
")"
] |
Return `ndarray` of `str` of lines of text from `path`.
|
[
"Return",
"ndarray",
"of",
"str",
"of",
"lines",
"of",
"text",
"from",
"path",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L221-L224
|
20,690
|
fastai/fastai
|
fastai/core.py
|
save_texts
|
def save_texts(fname:PathOrStr, texts:Collection[str]):
"Save in `fname` the content of `texts`."
with open(fname, 'w') as f:
for t in texts: f.write(f'{t}\n')
|
python
|
def save_texts(fname:PathOrStr, texts:Collection[str]):
"Save in `fname` the content of `texts`."
with open(fname, 'w') as f:
for t in texts: f.write(f'{t}\n')
|
[
"def",
"save_texts",
"(",
"fname",
":",
"PathOrStr",
",",
"texts",
":",
"Collection",
"[",
"str",
"]",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"f",
":",
"for",
"t",
"in",
"texts",
":",
"f",
".",
"write",
"(",
"f'{t}\\n'",
")"
] |
Save in `fname` the content of `texts`.
|
[
"Save",
"in",
"fname",
"the",
"content",
"of",
"texts",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L226-L229
|
20,691
|
fastai/fastai
|
fastai/core.py
|
df_names_to_idx
|
def df_names_to_idx(names:IntsOrStrs, df:DataFrame):
"Return the column indexes of `names` in `df`."
if not is_listy(names): names = [names]
if isinstance(names[0], int): return names
return [df.columns.get_loc(c) for c in names]
|
python
|
def df_names_to_idx(names:IntsOrStrs, df:DataFrame):
"Return the column indexes of `names` in `df`."
if not is_listy(names): names = [names]
if isinstance(names[0], int): return names
return [df.columns.get_loc(c) for c in names]
|
[
"def",
"df_names_to_idx",
"(",
"names",
":",
"IntsOrStrs",
",",
"df",
":",
"DataFrame",
")",
":",
"if",
"not",
"is_listy",
"(",
"names",
")",
":",
"names",
"=",
"[",
"names",
"]",
"if",
"isinstance",
"(",
"names",
"[",
"0",
"]",
",",
"int",
")",
":",
"return",
"names",
"return",
"[",
"df",
".",
"columns",
".",
"get_loc",
"(",
"c",
")",
"for",
"c",
"in",
"names",
"]"
] |
Return the column indexes of `names` in `df`.
|
[
"Return",
"the",
"column",
"indexes",
"of",
"names",
"in",
"df",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L231-L235
|
20,692
|
fastai/fastai
|
fastai/core.py
|
one_hot
|
def one_hot(x:Collection[int], c:int):
"One-hot encode `x` with `c` classes."
res = np.zeros((c,), np.float32)
res[listify(x)] = 1.
return res
|
python
|
def one_hot(x:Collection[int], c:int):
"One-hot encode `x` with `c` classes."
res = np.zeros((c,), np.float32)
res[listify(x)] = 1.
return res
|
[
"def",
"one_hot",
"(",
"x",
":",
"Collection",
"[",
"int",
"]",
",",
"c",
":",
"int",
")",
":",
"res",
"=",
"np",
".",
"zeros",
"(",
"(",
"c",
",",
")",
",",
"np",
".",
"float32",
")",
"res",
"[",
"listify",
"(",
"x",
")",
"]",
"=",
"1.",
"return",
"res"
] |
One-hot encode `x` with `c` classes.
|
[
"One",
"-",
"hot",
"encode",
"x",
"with",
"c",
"classes",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L237-L241
|
20,693
|
fastai/fastai
|
fastai/core.py
|
index_row
|
def index_row(a:Union[Collection,pd.DataFrame,pd.Series], idxs:Collection[int])->Any:
"Return the slice of `a` corresponding to `idxs`."
if a is None: return a
if isinstance(a,(pd.DataFrame,pd.Series)):
res = a.iloc[idxs]
if isinstance(res,(pd.DataFrame,pd.Series)): return res.copy()
return res
return a[idxs]
|
python
|
def index_row(a:Union[Collection,pd.DataFrame,pd.Series], idxs:Collection[int])->Any:
"Return the slice of `a` corresponding to `idxs`."
if a is None: return a
if isinstance(a,(pd.DataFrame,pd.Series)):
res = a.iloc[idxs]
if isinstance(res,(pd.DataFrame,pd.Series)): return res.copy()
return res
return a[idxs]
|
[
"def",
"index_row",
"(",
"a",
":",
"Union",
"[",
"Collection",
",",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
"]",
",",
"idxs",
":",
"Collection",
"[",
"int",
"]",
")",
"->",
"Any",
":",
"if",
"a",
"is",
"None",
":",
"return",
"a",
"if",
"isinstance",
"(",
"a",
",",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
")",
")",
":",
"res",
"=",
"a",
".",
"iloc",
"[",
"idxs",
"]",
"if",
"isinstance",
"(",
"res",
",",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"Series",
")",
")",
":",
"return",
"res",
".",
"copy",
"(",
")",
"return",
"res",
"return",
"a",
"[",
"idxs",
"]"
] |
Return the slice of `a` corresponding to `idxs`.
|
[
"Return",
"the",
"slice",
"of",
"a",
"corresponding",
"to",
"idxs",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L243-L250
|
20,694
|
fastai/fastai
|
fastai/core.py
|
func_args
|
def func_args(func)->bool:
"Return the arguments of `func`."
code = func.__code__
return code.co_varnames[:code.co_argcount]
|
python
|
def func_args(func)->bool:
"Return the arguments of `func`."
code = func.__code__
return code.co_varnames[:code.co_argcount]
|
[
"def",
"func_args",
"(",
"func",
")",
"->",
"bool",
":",
"code",
"=",
"func",
".",
"__code__",
"return",
"code",
".",
"co_varnames",
"[",
":",
"code",
".",
"co_argcount",
"]"
] |
Return the arguments of `func`.
|
[
"Return",
"the",
"arguments",
"of",
"func",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L252-L255
|
20,695
|
fastai/fastai
|
fastai/core.py
|
split_kwargs_by_func
|
def split_kwargs_by_func(kwargs, func):
"Split `kwargs` between those expected by `func` and the others."
args = func_args(func)
func_kwargs = {a:kwargs.pop(a) for a in args if a in kwargs}
return func_kwargs, kwargs
|
python
|
def split_kwargs_by_func(kwargs, func):
"Split `kwargs` between those expected by `func` and the others."
args = func_args(func)
func_kwargs = {a:kwargs.pop(a) for a in args if a in kwargs}
return func_kwargs, kwargs
|
[
"def",
"split_kwargs_by_func",
"(",
"kwargs",
",",
"func",
")",
":",
"args",
"=",
"func_args",
"(",
"func",
")",
"func_kwargs",
"=",
"{",
"a",
":",
"kwargs",
".",
"pop",
"(",
"a",
")",
"for",
"a",
"in",
"args",
"if",
"a",
"in",
"kwargs",
"}",
"return",
"func_kwargs",
",",
"kwargs"
] |
Split `kwargs` between those expected by `func` and the others.
|
[
"Split",
"kwargs",
"between",
"those",
"expected",
"by",
"func",
"and",
"the",
"others",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L261-L265
|
20,696
|
fastai/fastai
|
fastai/core.py
|
array
|
def array(a, dtype:type=None, **kwargs)->np.ndarray:
"Same as `np.array` but also handles generators. `kwargs` are passed to `np.array` with `dtype`."
if not isinstance(a, collections.Sized) and not getattr(a,'__array_interface__',False):
a = list(a)
if np.int_==np.int32 and dtype is None and is_listy(a) and len(a) and isinstance(a[0],int):
dtype=np.int64
return np.array(a, dtype=dtype, **kwargs)
|
python
|
def array(a, dtype:type=None, **kwargs)->np.ndarray:
"Same as `np.array` but also handles generators. `kwargs` are passed to `np.array` with `dtype`."
if not isinstance(a, collections.Sized) and not getattr(a,'__array_interface__',False):
a = list(a)
if np.int_==np.int32 and dtype is None and is_listy(a) and len(a) and isinstance(a[0],int):
dtype=np.int64
return np.array(a, dtype=dtype, **kwargs)
|
[
"def",
"array",
"(",
"a",
",",
"dtype",
":",
"type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"not",
"isinstance",
"(",
"a",
",",
"collections",
".",
"Sized",
")",
"and",
"not",
"getattr",
"(",
"a",
",",
"'__array_interface__'",
",",
"False",
")",
":",
"a",
"=",
"list",
"(",
"a",
")",
"if",
"np",
".",
"int_",
"==",
"np",
".",
"int32",
"and",
"dtype",
"is",
"None",
"and",
"is_listy",
"(",
"a",
")",
"and",
"len",
"(",
"a",
")",
"and",
"isinstance",
"(",
"a",
"[",
"0",
"]",
",",
"int",
")",
":",
"dtype",
"=",
"np",
".",
"int64",
"return",
"np",
".",
"array",
"(",
"a",
",",
"dtype",
"=",
"dtype",
",",
"*",
"*",
"kwargs",
")"
] |
Same as `np.array` but also handles generators. `kwargs` are passed to `np.array` with `dtype`.
|
[
"Same",
"as",
"np",
".",
"array",
"but",
"also",
"handles",
"generators",
".",
"kwargs",
"are",
"passed",
"to",
"np",
".",
"array",
"with",
"dtype",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L267-L273
|
20,697
|
fastai/fastai
|
fastai/core.py
|
text2html_table
|
def text2html_table(items:Collection[Collection[str]])->str:
"Put the texts in `items` in an HTML table, `widths` are the widths of the columns in %."
html_code = f"""<table border="1" class="dataframe">"""
html_code += f""" <thead>\n <tr style="text-align: right;">\n"""
for i in items[0]: html_code += f" <th>{_treat_html(i)}</th>"
html_code += f" </tr>\n </thead>\n <tbody>"
html_code += " <tbody>"
for line in items[1:]:
html_code += " <tr>"
for i in line: html_code += f" <td>{_treat_html(i)}</td>"
html_code += " </tr>"
html_code += " </tbody>\n</table>"
return html_code
|
python
|
def text2html_table(items:Collection[Collection[str]])->str:
"Put the texts in `items` in an HTML table, `widths` are the widths of the columns in %."
html_code = f"""<table border="1" class="dataframe">"""
html_code += f""" <thead>\n <tr style="text-align: right;">\n"""
for i in items[0]: html_code += f" <th>{_treat_html(i)}</th>"
html_code += f" </tr>\n </thead>\n <tbody>"
html_code += " <tbody>"
for line in items[1:]:
html_code += " <tr>"
for i in line: html_code += f" <td>{_treat_html(i)}</td>"
html_code += " </tr>"
html_code += " </tbody>\n</table>"
return html_code
|
[
"def",
"text2html_table",
"(",
"items",
":",
"Collection",
"[",
"Collection",
"[",
"str",
"]",
"]",
")",
"->",
"str",
":",
"html_code",
"=",
"f\"\"\"<table border=\"1\" class=\"dataframe\">\"\"\"",
"html_code",
"+=",
"f\"\"\" <thead>\\n <tr style=\"text-align: right;\">\\n\"\"\"",
"for",
"i",
"in",
"items",
"[",
"0",
"]",
":",
"html_code",
"+=",
"f\" <th>{_treat_html(i)}</th>\"",
"html_code",
"+=",
"f\" </tr>\\n </thead>\\n <tbody>\"",
"html_code",
"+=",
"\" <tbody>\"",
"for",
"line",
"in",
"items",
"[",
"1",
":",
"]",
":",
"html_code",
"+=",
"\" <tr>\"",
"for",
"i",
"in",
"line",
":",
"html_code",
"+=",
"f\" <td>{_treat_html(i)}</td>\"",
"html_code",
"+=",
"\" </tr>\"",
"html_code",
"+=",
"\" </tbody>\\n</table>\"",
"return",
"html_code"
] |
Put the texts in `items` in an HTML table, `widths` are the widths of the columns in %.
|
[
"Put",
"the",
"texts",
"in",
"items",
"in",
"an",
"HTML",
"table",
"widths",
"are",
"the",
"widths",
"of",
"the",
"columns",
"in",
"%",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L306-L318
|
20,698
|
fastai/fastai
|
fastai/core.py
|
parallel
|
def parallel(func, arr:Collection, max_workers:int=None):
"Call `func` on every element of `arr` in parallel using `max_workers`."
max_workers = ifnone(max_workers, defaults.cpus)
if max_workers<2: results = [func(o,i) for i,o in progress_bar(enumerate(arr), total=len(arr))]
else:
with ProcessPoolExecutor(max_workers=max_workers) as ex:
futures = [ex.submit(func,o,i) for i,o in enumerate(arr)]
results = []
for f in progress_bar(concurrent.futures.as_completed(futures), total=len(arr)): results.append(f.result())
if any([o is not None for o in results]): return results
|
python
|
def parallel(func, arr:Collection, max_workers:int=None):
"Call `func` on every element of `arr` in parallel using `max_workers`."
max_workers = ifnone(max_workers, defaults.cpus)
if max_workers<2: results = [func(o,i) for i,o in progress_bar(enumerate(arr), total=len(arr))]
else:
with ProcessPoolExecutor(max_workers=max_workers) as ex:
futures = [ex.submit(func,o,i) for i,o in enumerate(arr)]
results = []
for f in progress_bar(concurrent.futures.as_completed(futures), total=len(arr)): results.append(f.result())
if any([o is not None for o in results]): return results
|
[
"def",
"parallel",
"(",
"func",
",",
"arr",
":",
"Collection",
",",
"max_workers",
":",
"int",
"=",
"None",
")",
":",
"max_workers",
"=",
"ifnone",
"(",
"max_workers",
",",
"defaults",
".",
"cpus",
")",
"if",
"max_workers",
"<",
"2",
":",
"results",
"=",
"[",
"func",
"(",
"o",
",",
"i",
")",
"for",
"i",
",",
"o",
"in",
"progress_bar",
"(",
"enumerate",
"(",
"arr",
")",
",",
"total",
"=",
"len",
"(",
"arr",
")",
")",
"]",
"else",
":",
"with",
"ProcessPoolExecutor",
"(",
"max_workers",
"=",
"max_workers",
")",
"as",
"ex",
":",
"futures",
"=",
"[",
"ex",
".",
"submit",
"(",
"func",
",",
"o",
",",
"i",
")",
"for",
"i",
",",
"o",
"in",
"enumerate",
"(",
"arr",
")",
"]",
"results",
"=",
"[",
"]",
"for",
"f",
"in",
"progress_bar",
"(",
"concurrent",
".",
"futures",
".",
"as_completed",
"(",
"futures",
")",
",",
"total",
"=",
"len",
"(",
"arr",
")",
")",
":",
"results",
".",
"append",
"(",
"f",
".",
"result",
"(",
")",
")",
"if",
"any",
"(",
"[",
"o",
"is",
"not",
"None",
"for",
"o",
"in",
"results",
"]",
")",
":",
"return",
"results"
] |
Call `func` on every element of `arr` in parallel using `max_workers`.
|
[
"Call",
"func",
"on",
"every",
"element",
"of",
"arr",
"in",
"parallel",
"using",
"max_workers",
"."
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L320-L329
|
20,699
|
fastai/fastai
|
fastai/core.py
|
subplots
|
def subplots(rows:int, cols:int, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, title=None, **kwargs):
"Like `plt.subplots` but with consistent axs shape, `kwargs` passed to `fig.suptitle` with `title`"
figsize = ifnone(figsize, (imgsize*cols, imgsize*rows))
fig, axs = plt.subplots(rows,cols,figsize=figsize)
if rows==cols==1: axs = [[axs]] # subplots(1,1) returns Axes, not [Axes]
elif (rows==1 and cols!=1) or (cols==1 and rows!=1): axs = [axs]
if title is not None: fig.suptitle(title, **kwargs)
return array(axs)
|
python
|
def subplots(rows:int, cols:int, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, title=None, **kwargs):
"Like `plt.subplots` but with consistent axs shape, `kwargs` passed to `fig.suptitle` with `title`"
figsize = ifnone(figsize, (imgsize*cols, imgsize*rows))
fig, axs = plt.subplots(rows,cols,figsize=figsize)
if rows==cols==1: axs = [[axs]] # subplots(1,1) returns Axes, not [Axes]
elif (rows==1 and cols!=1) or (cols==1 and rows!=1): axs = [axs]
if title is not None: fig.suptitle(title, **kwargs)
return array(axs)
|
[
"def",
"subplots",
"(",
"rows",
":",
"int",
",",
"cols",
":",
"int",
",",
"imgsize",
":",
"int",
"=",
"4",
",",
"figsize",
":",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"=",
"None",
",",
"title",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"figsize",
"=",
"ifnone",
"(",
"figsize",
",",
"(",
"imgsize",
"*",
"cols",
",",
"imgsize",
"*",
"rows",
")",
")",
"fig",
",",
"axs",
"=",
"plt",
".",
"subplots",
"(",
"rows",
",",
"cols",
",",
"figsize",
"=",
"figsize",
")",
"if",
"rows",
"==",
"cols",
"==",
"1",
":",
"axs",
"=",
"[",
"[",
"axs",
"]",
"]",
"# subplots(1,1) returns Axes, not [Axes]",
"elif",
"(",
"rows",
"==",
"1",
"and",
"cols",
"!=",
"1",
")",
"or",
"(",
"cols",
"==",
"1",
"and",
"rows",
"!=",
"1",
")",
":",
"axs",
"=",
"[",
"axs",
"]",
"if",
"title",
"is",
"not",
"None",
":",
"fig",
".",
"suptitle",
"(",
"title",
",",
"*",
"*",
"kwargs",
")",
"return",
"array",
"(",
"axs",
")"
] |
Like `plt.subplots` but with consistent axs shape, `kwargs` passed to `fig.suptitle` with `title`
|
[
"Like",
"plt",
".",
"subplots",
"but",
"with",
"consistent",
"axs",
"shape",
"kwargs",
"passed",
"to",
"fig",
".",
"suptitle",
"with",
"title"
] |
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
|
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L331-L338
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.