repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
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(...
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(...
[ "def", "_url_params", "(", "size", ":", "str", "=", "'>400*300'", ",", "format", ":", "str", "=", "'jpg'", ")", "->", "str", ":", "_fmts", "=", "{", "'jpg'", ":", "'ift:jpg'", ",", "'gif'", ":", "'ift:gif'", ",", "'png'", ":", "'ift:png'", ",", "'bmp...
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
train
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, fo...
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, fo...
[ "def", "_search_url", "(", "search_term", ":", "str", ",", "size", ":", "str", "=", "'>400*300'", ",", "format", ":", "str", "=", "'jpg'", ")", "->", "str", ":", "return", "(", "'https://www.google.com/search?q='", "+", "quote", "(", "search_term", ")", "+...
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
train
fastai/fastai
fastai/widgets/image_downloader.py
_fetch_img_tuples
def _fetch_img_tuples(url:str, format:str='jpg', n_images:int=10) -> list: "Parse the Google Images Search for urls and return the image metadata as tuples (fname, url)." headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'} html = r...
python
def _fetch_img_tuples(url:str, format:str='jpg', n_images:int=10) -> list: "Parse the Google Images Search for urls and return the image metadata as tuples (fname, url)." headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'} html = r...
[ "def", "_fetch_img_tuples", "(", "url", ":", "str", ",", "format", ":", "str", "=", "'jpg'", ",", "n_images", ":", "int", "=", "10", ")", "->", "list", ":", "headers", "=", "{", "'User-Agent'", ":", "'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like ...
Parse the Google Images Search for urls and return the image metadata as tuples (fname, url).
[ "Parse", "the", "Google", "Images", "Search", "for", "urls", "and", "return", "the", "image", "metadata", "as", "tuples", "(", "fname", "url", ")", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L113-L117
train
fastai/fastai
fastai/widgets/image_downloader.py
_html_to_img_tuples
def _html_to_img_tuples(html:str, format:str='jpg', n_images:int=10) -> list: "Parse the google images html to img tuples containining `(fname, url)`" bs = BeautifulSoup(html, 'html.parser') img_tags = bs.find_all('div', {'class': 'rg_meta'}) metadata_dicts = (json.loads(e.text) for e in img_tags) ...
python
def _html_to_img_tuples(html:str, format:str='jpg', n_images:int=10) -> list: "Parse the google images html to img tuples containining `(fname, url)`" bs = BeautifulSoup(html, 'html.parser') img_tags = bs.find_all('div', {'class': 'rg_meta'}) metadata_dicts = (json.loads(e.text) for e in img_tags) ...
[ "def", "_html_to_img_tuples", "(", "html", ":", "str", ",", "format", ":", "str", "=", "'jpg'", ",", "n_images", ":", "int", "=", "10", ")", "->", "list", ":", "bs", "=", "BeautifulSoup", "(", "html", ",", "'html.parser'", ")", "img_tags", "=", "bs", ...
Parse the google images html to img tuples containining `(fname, url)`
[ "Parse", "the", "google", "images", "html", "to", "img", "tuples", "containining", "(", "fname", "url", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L119-L125
train
fastai/fastai
fastai/widgets/image_downloader.py
_fetch_img_tuples_webdriver
def _fetch_img_tuples_webdriver(url:str, format:str='jpg', n_images:int=150) -> list: """ Parse the Google Images Search for urls and return the image metadata as tuples (fname, url). Use this for downloads of >100 images. Requires `selenium`. """ try: from selenium import webdriver ...
python
def _fetch_img_tuples_webdriver(url:str, format:str='jpg', n_images:int=150) -> list: """ Parse the Google Images Search for urls and return the image metadata as tuples (fname, url). Use this for downloads of >100 images. Requires `selenium`. """ try: from selenium import webdriver ...
[ "def", "_fetch_img_tuples_webdriver", "(", "url", ":", "str", ",", "format", ":", "str", "=", "'jpg'", ",", "n_images", ":", "int", "=", "150", ")", "->", "list", ":", "try", ":", "from", "selenium", "import", "webdriver", "from", "selenium", ".", "webdr...
Parse the Google Images Search for urls and return the image metadata as tuples (fname, url). Use this for downloads of >100 images. Requires `selenium`.
[ "Parse", "the", "Google", "Images", "Search", "for", "urls", "and", "return", "the", "image", "metadata", "as", "tuples", "(", "fname", "url", ")", ".", "Use", "this", "for", "downloads", "of", ">", "100", "images", ".", "Requires", "selenium", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L127-L157
train
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 s...
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 s...
[ "def", "_download_images", "(", "label_path", ":", "PathOrStr", ",", "img_tuples", ":", "list", ",", "max_workers", ":", "int", "=", "defaults", ".", "cpus", ",", "timeout", ":", "int", "=", "4", ")", "->", "FilePathList", ":", "os", ".", "makedirs", "("...
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", "sy...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L159-L168
train
fastai/fastai
fastai/widgets/image_downloader.py
_download_single_image
def _download_single_image(label_path:Path, img_tuple:tuple, i:int, timeout:int=4) -> None: """ Downloads a single image from Google Search results to `label_path` given an `img_tuple` that contains `(fname, url)` of an image to download. `i` is just an iteration number `int`. """ suffix = re.f...
python
def _download_single_image(label_path:Path, img_tuple:tuple, i:int, timeout:int=4) -> None: """ Downloads a single image from Google Search results to `label_path` given an `img_tuple` that contains `(fname, url)` of an image to download. `i` is just an iteration number `int`. """ suffix = re.f...
[ "def", "_download_single_image", "(", "label_path", ":", "Path", ",", "img_tuple", ":", "tuple", ",", "i", ":", "int", ",", "timeout", ":", "int", "=", "4", ")", "->", "None", ":", "suffix", "=", "re", ".", "findall", "(", "r'\\.\\w+?(?=(?:\\?|$))'", ","...
Downloads a single image from Google Search results to `label_path` given an `img_tuple` that contains `(fname, url)` of an image to download. `i` is just an iteration number `int`.
[ "Downloads", "a", "single", "image", "from", "Google", "Search", "results", "to", "label_path", "given", "an", "img_tuple", "that", "contains", "(", "fname", "url", ")", "of", "an", "image", "to", "download", ".", "i", "is", "just", "an", "iteration", "num...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L170-L179
train
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=Layo...
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=Layo...
[ "def", "_init_ui", "(", "self", ")", "->", "VBox", ":", "self", ".", "_search_input", "=", "Text", "(", "placeholder", "=", "\"What images to search for?\"", ")", "self", ".", "_count_input", "=", "BoundedIntText", "(", "placeholder", "=", "\"How many pics?\"", ...
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
train
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
train
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\"", ",",...
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
train
fastai/fastai
fastai/widgets/image_downloader.py
ImageDownloader.on_download_button_click
def on_download_button_click(self, btn) -> None: "Download button click handler: validate search term and download images." term = self._search_input.value limit = int(self._count_input.value) size = self._size_input.value if not self.validate_search_input(): return self....
python
def on_download_button_click(self, btn) -> None: "Download button click handler: validate search term and download images." term = self._search_input.value limit = int(self._count_input.value) size = self._size_input.value if not self.validate_search_input(): return self....
[ "def", "on_download_button_click", "(", "self", ",", "btn", ")", "->", "None", ":", "term", "=", "self", ".", "_search_input", ".", "value", "limit", "=", "int", "(", "self", ".", "_count_input", ".", "value", ")", "size", "=", "self", ".", "_size_input"...
Download button click handler: validate search term and download images.
[ "Download", "button", "click", "handler", ":", "validate", "search", "term", "and", "download", "images", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L60-L70
train
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'",...
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
train
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. re...
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. re...
[ "def", "on_train_begin", "(", "self", ",", "pbar", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "setattr", "(", "pbar", ",", "'clean_on_interrupt'", ",", "True", ")", "self", ".", "learn", ".", "save", "(", "'tmp'", ")", "self", ".", ...
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
train
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...
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...
[ "def", "on_batch_end", "(", "self", ",", "iteration", ":", "int", ",", "smooth_loss", ":", "TensorOrNumber", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "iteration", "==", "0", "or", "smooth_loss", "<", "self", ".", "best_loss", ...
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
train
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() ...
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() ...
[ "def", "on_train_end", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "learn", ".", "load", "(", "'tmp'", ",", "purge", "=", "False", ")", "if", "hasattr", "(", "self", ".", "learn", ".", "model", ",", "'re...
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
train
fastai/fastai
old/fastai/rnn_reg.py
dropout_mask
def dropout_mask(x, sz, dropout): """ Applies a dropout mask whose size is determined by passed argument 'sz'. Args: x (nn.Variable): A torch Variable object sz (tuple(int, int, int)): The expected size of the new tensor dropout (float): The dropout fraction to apply This method use...
python
def dropout_mask(x, sz, dropout): """ Applies a dropout mask whose size is determined by passed argument 'sz'. Args: x (nn.Variable): A torch Variable object sz (tuple(int, int, int)): The expected size of the new tensor dropout (float): The dropout fraction to apply This method use...
[ "def", "dropout_mask", "(", "x", ",", "sz", ",", "dropout", ")", ":", "return", "x", ".", "new", "(", "*", "sz", ")", ".", "bernoulli_", "(", "1", "-", "dropout", ")", "/", "(", "1", "-", "dropout", ")" ]
Applies a dropout mask whose size is determined by passed argument 'sz'. Args: x (nn.Variable): A torch Variable object sz (tuple(int, int, int)): The expected size of the new tensor dropout (float): The dropout fraction to apply This method uses the bernoulli distribution to decide whi...
[ "Applies", "a", "dropout", "mask", "whose", "size", "is", "determined", "by", "passed", "argument", "sz", ".", "Args", ":", "x", "(", "nn", ".", "Variable", ")", ":", "A", "torch", "Variable", "object", "sz", "(", "tuple", "(", "int", "int", "int", "...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/rnn_reg.py#L9-L47
train
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 ...
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 ...
[ "def", "_setup", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "module", ",", "torch", ".", "nn", ".", "RNNBase", ")", ":", "self", ".", "module", ".", "flatten_parameters", "=", "noop", "for", "name_w", "in", "self", ".", "weights", "...
for each string defined in self.weights, the corresponding attribute in the wrapped module is referenced, then deleted, and subsequently registered as a new parameter with a slightly modified name. Args: None Returns: None
[ "for", "each", "string", "defined", "in", "self", ".", "weights", "the", "corresponding", "attribute", "in", "the", "wrapped", "module", "is", "referenced", "then", "deleted", "and", "subsequently", "registered", "as", "a", "new", "parameter", "with", "a", "sl...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/rnn_reg.py#L79-L94
train
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') ...
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') ...
[ "def", "_setweights", "(", "self", ")", ":", "for", "name_w", "in", "self", ".", "weights", ":", "raw_w", "=", "getattr", "(", "self", ".", "module", ",", "name_w", "+", "'_raw'", ")", "w", "=", "torch", ".", "nn", ".", "functional", ".", "dropout", ...
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
train
fastai/fastai
fastai/basic_data.py
load_data
def load_data(path:PathOrStr, file:PathLikeOrBinaryStream='data_save.pkl', bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None, device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False, **kwargs)->DataBunch: "Load ...
python
def load_data(path:PathOrStr, file:PathLikeOrBinaryStream='data_save.pkl', bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None, device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False, **kwargs)->DataBunch: "Load ...
[ "def", "load_data", "(", "path", ":", "PathOrStr", ",", "file", ":", "PathLikeOrBinaryStream", "=", "'data_save.pkl'", ",", "bs", ":", "int", "=", "64", ",", "val_bs", ":", "int", "=", "None", ",", "num_workers", ":", "int", "=", "defaults", ".", "cpus",...
Load a saved `DataBunch` from `path/file`. `file` can be file-like (file or buffer)
[ "Load", "a", "saved", "DataBunch", "from", "path", "/", "file", ".", "file", "can", "be", "file", "-", "like", "(", "file", "or", "buffer", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L272-L279
train
fastai/fastai
fastai/basic_data.py
DataBunch.create
def create(cls, train_ds:Dataset, valid_ds:Dataset, test_ds:Optional[Dataset]=None, path:PathOrStr='.', bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None, device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False, *...
python
def create(cls, train_ds:Dataset, valid_ds:Dataset, test_ds:Optional[Dataset]=None, path:PathOrStr='.', bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None, device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False, *...
[ "def", "create", "(", "cls", ",", "train_ds", ":", "Dataset", ",", "valid_ds", ":", "Dataset", ",", "test_ds", ":", "Optional", "[", "Dataset", "]", "=", "None", ",", "path", ":", "PathOrStr", "=", "'.'", ",", "bs", ":", "int", "=", "64", ",", "val...
Create a `DataBunch` from `train_ds`, `valid_ds` and maybe `test_ds` with a batch size of `bs`. Passes `**dl_kwargs` to `DataLoader()`
[ "Create", "a", "DataBunch", "from", "train_ds", "valid_ds", "and", "maybe", "test_ds", "with", "a", "batch", "size", "of", "bs", ".", "Passes", "**", "dl_kwargs", "to", "DataLoader", "()" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L112-L120
train
fastai/fastai
fastai/basic_data.py
DataBunch.dl
def dl(self, ds_type:DatasetType=DatasetType.Valid)->DeviceDataLoader: "Returns appropriate `Dataset` for validation, training, or test (`ds_type`)." #TODO: refactor return (self.train_dl if ds_type == DatasetType.Train else self.test_dl if ds_type == DatasetType.Test else ...
python
def dl(self, ds_type:DatasetType=DatasetType.Valid)->DeviceDataLoader: "Returns appropriate `Dataset` for validation, training, or test (`ds_type`)." #TODO: refactor return (self.train_dl if ds_type == DatasetType.Train else self.test_dl if ds_type == DatasetType.Test else ...
[ "def", "dl", "(", "self", ",", "ds_type", ":", "DatasetType", "=", "DatasetType", ".", "Valid", ")", "->", "DeviceDataLoader", ":", "#TODO: refactor", "return", "(", "self", ".", "train_dl", "if", "ds_type", "==", "DatasetType", ".", "Train", "else", "self",...
Returns appropriate `Dataset` for validation, training, or test (`ds_type`).
[ "Returns", "appropriate", "Dataset", "for", "validation", "training", "or", "test", "(", "ds_type", ")", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L125-L132
train
fastai/fastai
fastai/basic_data.py
DataBunch.dls
def dls(self)->List[DeviceDataLoader]: "Returns a list of all DeviceDataLoaders. If you need a specific DeviceDataLoader, access via the relevant property (`train_dl`, `valid_dl`, etc) as the index of DLs in this list is not guaranteed to remain constant." res = [self.train_dl, self.fix_dl, self.single_...
python
def dls(self)->List[DeviceDataLoader]: "Returns a list of all DeviceDataLoaders. If you need a specific DeviceDataLoader, access via the relevant property (`train_dl`, `valid_dl`, etc) as the index of DLs in this list is not guaranteed to remain constant." res = [self.train_dl, self.fix_dl, self.single_...
[ "def", "dls", "(", "self", ")", "->", "List", "[", "DeviceDataLoader", "]", ":", "res", "=", "[", "self", ".", "train_dl", ",", "self", ".", "fix_dl", ",", "self", ".", "single_dl", "]", "# Preserve the original ordering of Train, Valid, Fix, Single, Test Data Loa...
Returns a list of all DeviceDataLoaders. If you need a specific DeviceDataLoader, access via the relevant property (`train_dl`, `valid_dl`, etc) as the index of DLs in this list is not guaranteed to remain constant.
[ "Returns", "a", "list", "of", "all", "DeviceDataLoaders", ".", "If", "you", "need", "a", "specific", "DeviceDataLoader", "access", "via", "the", "relevant", "property", "(", "train_dl", "valid_dl", "etc", ")", "as", "the", "index", "of", "DLs", "in", "this",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L135-L141
train
fastai/fastai
fastai/basic_data.py
DataBunch.save
def save(self, file:PathLikeOrBinaryStream= 'data_save.pkl')->None: "Save the `DataBunch` in `self.path/file`. `file` can be file-like (file or buffer)" if not getattr(self, 'label_list', False): warn("Serializing the `DataBunch` only works when you created it using the data block API.") ...
python
def save(self, file:PathLikeOrBinaryStream= 'data_save.pkl')->None: "Save the `DataBunch` in `self.path/file`. `file` can be file-like (file or buffer)" if not getattr(self, 'label_list', False): warn("Serializing the `DataBunch` only works when you created it using the data block API.") ...
[ "def", "save", "(", "self", ",", "file", ":", "PathLikeOrBinaryStream", "=", "'data_save.pkl'", ")", "->", "None", ":", "if", "not", "getattr", "(", "self", ",", "'label_list'", ",", "False", ")", ":", "warn", "(", "\"Serializing the `DataBunch` only works when ...
Save the `DataBunch` in `self.path/file`. `file` can be file-like (file or buffer)
[ "Save", "the", "DataBunch", "in", "self", ".", "path", "/", "file", ".", "file", "can", "be", "file", "-", "like", "(", "file", "or", "buffer", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L149-L154
train
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 ...
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 ...
[ "def", "one_batch", "(", "self", ",", "ds_type", ":", "DatasetType", "=", "DatasetType", ".", "Train", ",", "detach", ":", "bool", "=", "True", ",", "denorm", ":", "bool", "=", "True", ",", "cpu", ":", "bool", "=", "True", ")", "->", "Collection", "[...
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
train
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", ...
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
train
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_...
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_...
[ "def", "show_batch", "(", "self", ",", "rows", ":", "int", "=", "5", ",", "ds_type", ":", "DatasetType", "=", "DatasetType", ".", "Train", ",", "reverse", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", "->", "None", ":", "x", ",", "y", ...
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
train
fastai/fastai
fastai/basic_data.py
DataBunch.export
def export(self, file:PathLikeOrBinaryStream='export.pkl'): "Export the minimal state of `self` for inference in `self.path/file`. `file` can be file-like (file or buffer)" xtra = dict(normalize=self.norm.keywords) if getattr(self, 'norm', False) else {} try_save(self.valid_ds.get_state(**xtra),...
python
def export(self, file:PathLikeOrBinaryStream='export.pkl'): "Export the minimal state of `self` for inference in `self.path/file`. `file` can be file-like (file or buffer)" xtra = dict(normalize=self.norm.keywords) if getattr(self, 'norm', False) else {} try_save(self.valid_ds.get_state(**xtra),...
[ "def", "export", "(", "self", ",", "file", ":", "PathLikeOrBinaryStream", "=", "'export.pkl'", ")", ":", "xtra", "=", "dict", "(", "normalize", "=", "self", ".", "norm", ".", "keywords", ")", "if", "getattr", "(", "self", ",", "'norm'", ",", "False", "...
Export the minimal state of `self` for inference in `self.path/file`. `file` can be file-like (file or buffer)
[ "Export", "the", "minimal", "state", "of", "self", "for", "inference", "in", "self", ".", "path", "/", "file", ".", "file", "can", "be", "file", "-", "like", "(", "file", "or", "buffer", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/basic_data.py#L196-L199
train
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'): re...
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'): re...
[ "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...
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
train
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
train
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)...
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)...
[ "def", "fit_one_cycle", "(", "learn", ":", "Learner", ",", "cyc_len", ":", "int", ",", "max_lr", ":", "Union", "[", "Floats", ",", "slice", "]", "=", "defaults", ".", "lr", ",", "moms", ":", "Tuple", "[", "float", ",", "float", "]", "=", "(", "0.95...
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
train
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 i...
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 i...
[ "def", "lr_find", "(", "learn", ":", "Learner", ",", "start_lr", ":", "Floats", "=", "1e-7", ",", "end_lr", ":", "Floats", "=", "10", ",", "num_it", ":", "int", "=", "100", ",", "stop_div", ":", "bool", "=", "True", ",", "wd", ":", "float", "=", ...
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
train
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) ...
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) ...
[ "def", "to_fp16", "(", "learn", ":", "Learner", ",", "loss_scale", ":", "float", "=", "None", ",", "max_noskip", ":", "int", "=", "1000", ",", "dynamic", ":", "bool", "=", "True", ",", "clip", ":", "float", "=", "None", ",", "flat_master", ":", "bool...
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
train
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", "....
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
train
fastai/fastai
fastai/train.py
mixup
def mixup(learn:Learner, alpha:float=0.4, stack_x:bool=False, stack_y:bool=True) -> Learner: "Add mixup https://arxiv.org/abs/1710.09412 to `learn`." learn.callback_fns.append(partial(MixUpCallback, alpha=alpha, stack_x=stack_x, stack_y=stack_y)) return learn
python
def mixup(learn:Learner, alpha:float=0.4, stack_x:bool=False, stack_y:bool=True) -> Learner: "Add mixup https://arxiv.org/abs/1710.09412 to `learn`." learn.callback_fns.append(partial(MixUpCallback, alpha=alpha, stack_x=stack_x, stack_y=stack_y)) return learn
[ "def", "mixup", "(", "learn", ":", "Learner", ",", "alpha", ":", "float", "=", "0.4", ",", "stack_x", ":", "bool", "=", "False", ",", "stack_y", ":", "bool", "=", "True", ")", "->", "Learner", ":", "learn", ".", "callback_fns", ".", "append", "(", ...
Add mixup https://arxiv.org/abs/1710.09412 to `learn`.
[ "Add", "mixup", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1710", ".", "09412", "to", "learn", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L53-L56
train
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", "lea...
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
train
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
train
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...
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...
[ "def", "on_epoch_end", "(", "self", ",", "n_epochs", ":", "int", ",", "last_metrics", ":", "MetricsList", ",", "*", "*", "kwargs", ")", "->", "bool", ":", "if", "last_metrics", "is", "not", "None", "and", "np", ".", "any", "(", "last_metrics", ")", ":"...
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
train
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
train
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 b...
check if loss is reduction
[ "check", "if", "loss", "is", "reduction" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L106-L109
train
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
train
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 ...
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 ...
[ "def", "on_backward_end", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "(", "self", ".", "acc_batches", "%", "self", ".", "n_step", ")", "==", "0", ":", "for", "p", "in", "(", "self", ".", "learn", ".", "model", ".", "parameters", "(", "...
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
train
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_", "(", "...
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
train
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", ")", ...
Create an instance of `ClassificationInterpretation`
[ "Create", "an", "instance", "of", "ClassificationInterpretation" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L144-L147
train
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)...
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)...
[ "def", "confusion_matrix", "(", "self", ",", "slice_size", ":", "int", "=", "1", ")", ":", "x", "=", "torch", ".", "arange", "(", "0", ",", "self", ".", "data", ".", "c", ")", "if", "slice_size", "is", "None", ":", "cm", "=", "(", "(", "self", ...
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
train
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`." # T...
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`." # T...
[ "def", "plot_confusion_matrix", "(", "self", ",", "normalize", ":", "bool", "=", "False", ",", "title", ":", "str", "=", "'Confusion matrix'", ",", "cmap", ":", "Any", "=", "\"Blues\"", ",", "slice_size", ":", "int", "=", "1", ",", "norm_dec", ":", "int"...
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
train
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)...
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)...
[ "def", "most_confused", "(", "self", ",", "min_val", ":", "int", "=", "1", ",", "slice_size", ":", "int", "=", "1", ")", "->", "Collection", "[", "Tuple", "[", "str", ",", "str", ",", "int", "]", "]", ":", "cm", "=", "self", ".", "confusion_matrix"...
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
train
fastai/fastai
fastai/train.py
ClassificationInterpretation.top_losses
def top_losses(self, k:int=None, largest=True): "`k` largest(/smallest) losses and indexes, defaulting to all losses (sorted by `largest`)." return self.losses.topk(ifnone(k, len(self.losses)), largest=largest)
python
def top_losses(self, k:int=None, largest=True): "`k` largest(/smallest) losses and indexes, defaulting to all losses (sorted by `largest`)." return self.losses.topk(ifnone(k, len(self.losses)), largest=largest)
[ "def", "top_losses", "(", "self", ",", "k", ":", "int", "=", "None", ",", "largest", "=", "True", ")", ":", "return", "self", ".", "losses", ".", "topk", "(", "ifnone", "(", "k", ",", "len", "(", "self", ".", "losses", ")", ")", ",", "largest", ...
`k` largest(/smallest) losses and indexes, defaulting to all losses (sorted by `largest`).
[ "k", "largest", "(", "/", "smallest", ")", "losses", "and", "indexes", "defaulting", "to", "all", "losses", "(", "sorted", "by", "largest", ")", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/train.py#L194-L196
train
fastai/fastai
old/fastai/metrics.py
fbeta
def fbeta(log_preds, targs, beta, thresh=0.5, epsilon=1e-8): """Calculates the F-beta score (the weighted harmonic mean of precision and recall). This is the micro averaged version where the true positives, false negatives and false positives are calculated globally (as opposed to on a per label basis). ...
python
def fbeta(log_preds, targs, beta, thresh=0.5, epsilon=1e-8): """Calculates the F-beta score (the weighted harmonic mean of precision and recall). This is the micro averaged version where the true positives, false negatives and false positives are calculated globally (as opposed to on a per label basis). ...
[ "def", "fbeta", "(", "log_preds", ",", "targs", ",", "beta", ",", "thresh", "=", "0.5", ",", "epsilon", "=", "1e-8", ")", ":", "assert", "beta", ">", "0", ",", "'beta needs to be greater than 0'", "beta2", "=", "beta", "**", "2", "rec", "=", "recall", ...
Calculates the F-beta score (the weighted harmonic mean of precision and recall). This is the micro averaged version where the true positives, false negatives and false positives are calculated globally (as opposed to on a per label basis). beta == 1 places equal weight on precision and recall, b < 1 empha...
[ "Calculates", "the", "F", "-", "beta", "score", "(", "the", "weighted", "harmonic", "mean", "of", "precision", "and", "recall", ")", ".", "This", "is", "the", "micro", "averaged", "version", "where", "the", "true", "positives", "false", "negatives", "and", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/metrics.py#L48-L60
train
fastai/fastai
old/fastai/metrics.py
fbeta_np
def fbeta_np(preds, targs, beta, thresh=0.5, epsilon=1e-8): """ see fbeta """ assert beta > 0, 'beta needs to be greater than 0' beta2 = beta ** 2 rec = recall_np(preds, targs, thresh) prec = precision_np(preds, targs, thresh) return (1 + beta2) * prec * rec / (beta2 * prec + rec + epsilon)
python
def fbeta_np(preds, targs, beta, thresh=0.5, epsilon=1e-8): """ see fbeta """ assert beta > 0, 'beta needs to be greater than 0' beta2 = beta ** 2 rec = recall_np(preds, targs, thresh) prec = precision_np(preds, targs, thresh) return (1 + beta2) * prec * rec / (beta2 * prec + rec + epsilon)
[ "def", "fbeta_np", "(", "preds", ",", "targs", ",", "beta", ",", "thresh", "=", "0.5", ",", "epsilon", "=", "1e-8", ")", ":", "assert", "beta", ">", "0", ",", "'beta needs to be greater than 0'", "beta2", "=", "beta", "**", "2", "rec", "=", "recall_np", ...
see fbeta
[ "see", "fbeta" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/metrics.py#L62-L68
train
fastai/fastai
examples/train_imagenet.py
main
def main( gpu:Param("GPU to run on", str)=None ): """Distributed training of Imagenet. Fastest speed is if you run with: python -m fastai.launch""" path = Path('/mnt/fe2_disk/') tot_epochs,size,bs,lr = 60,224,256,3e-1 dirname = 'imagenet' gpu = setup_distrib(gpu) if gpu is None: bs *= torch.cud...
python
def main( gpu:Param("GPU to run on", str)=None ): """Distributed training of Imagenet. Fastest speed is if you run with: python -m fastai.launch""" path = Path('/mnt/fe2_disk/') tot_epochs,size,bs,lr = 60,224,256,3e-1 dirname = 'imagenet' gpu = setup_distrib(gpu) if gpu is None: bs *= torch.cud...
[ "def", "main", "(", "gpu", ":", "Param", "(", "\"GPU to run on\"", ",", "str", ")", "=", "None", ")", ":", "path", "=", "Path", "(", "'/mnt/fe2_disk/'", ")", "tot_epochs", ",", "size", ",", "bs", ",", "lr", "=", "60", ",", "224", ",", "256", ",", ...
Distributed training of Imagenet. Fastest speed is if you run with: python -m fastai.launch
[ "Distributed", "training", "of", "Imagenet", ".", "Fastest", "speed", "is", "if", "you", "run", "with", ":", "python", "-", "m", "fastai", ".", "launch" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/examples/train_imagenet.py#L22-L60
train
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
train
fastai/fastai
fastai/vision/learner.py
create_body
def create_body(arch:Callable, pretrained:bool=True, cut:Optional[Union[int, Callable]]=None): "Cut off the body of a typically pretrained `model` at `cut` (int) or cut the model as specified by `cut(model)` (function)." model = arch(pretrained) cut = ifnone(cut, cnn_config(arch)['cut']) if cut is None:...
python
def create_body(arch:Callable, pretrained:bool=True, cut:Optional[Union[int, Callable]]=None): "Cut off the body of a typically pretrained `model` at `cut` (int) or cut the model as specified by `cut(model)` (function)." model = arch(pretrained) cut = ifnone(cut, cnn_config(arch)['cut']) if cut is None:...
[ "def", "create_body", "(", "arch", ":", "Callable", ",", "pretrained", ":", "bool", "=", "True", ",", "cut", ":", "Optional", "[", "Union", "[", "int", ",", "Callable", "]", "]", "=", "None", ")", ":", "model", "=", "arch", "(", "pretrained", ")", ...
Cut off the body of a typically pretrained `model` at `cut` (int) or cut the model as specified by `cut(model)` (function).
[ "Cut", "off", "the", "body", "of", "a", "typically", "pretrained", "model", "at", "cut", "(", "int", ")", "or", "cut", "the", "model", "as", "specified", "by", "cut", "(", "model", ")", "(", "function", ")", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/learner.py#L53-L62
train
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] ...
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] ...
[ "def", "create_head", "(", "nf", ":", "int", ",", "nc", ":", "int", ",", "lin_ftrs", ":", "Optional", "[", "Collection", "[", "int", "]", "]", "=", "None", ",", "ps", ":", "Floats", "=", "0.5", ",", "concat_pool", ":", "bool", "=", "True", ",", "...
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
train
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 c...
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 c...
[ "def", "create_cnn_model", "(", "base_arch", ":", "Callable", ",", "nc", ":", "int", ",", "cut", ":", "Union", "[", "int", ",", "Callable", "]", "=", "None", ",", "pretrained", ":", "bool", "=", "True", ",", "lin_ftrs", ":", "Optional", "[", "Collectio...
Create custom convnet architecture
[ "Create", "custom", "convnet", "architecture" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/learner.py#L79-L88
train
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_norm...
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_norm...
[ "def", "cnn_learner", "(", "data", ":", "DataBunch", ",", "base_arch", ":", "Callable", ",", "cut", ":", "Union", "[", "int", ",", "Callable", "]", "=", "None", ",", "pretrained", ":", "bool", "=", "True", ",", "lin_ftrs", ":", "Optional", "[", "Collec...
Build convnet style learner.
[ "Build", "convnet", "style", "learner", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/learner.py#L90-L102
train
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, ...
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, ...
[ "def", "unet_learner", "(", "data", ":", "DataBunch", ",", "arch", ":", "Callable", ",", "pretrained", ":", "bool", "=", "True", ",", "blur_final", ":", "bool", "=", "True", ",", "norm_type", ":", "Optional", "[", "NormType", "]", "=", "NormType", ",", ...
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
train
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_l...
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_l...
[ "def", "_cl_int_from_learner", "(", "cls", ",", "learn", ":", "Learner", ",", "ds_type", ":", "DatasetType", "=", "DatasetType", ".", "Valid", ",", "tta", "=", "False", ")", ":", "preds", "=", "learn", ".", "TTA", "(", "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
train
fastai/fastai
fastai/vision/learner.py
_cl_int_plot_top_losses
def _cl_int_plot_top_losses(self, k, largest=True, figsize=(12,12), heatmap:bool=True, heatmap_thresh:int=16, return_fig:bool=None)->Optional[plt.Figure]: "Show images in `top_losses` along with their prediction, actual, loss, and probability of actual class." tl_val,tl_idx = self.to...
python
def _cl_int_plot_top_losses(self, k, largest=True, figsize=(12,12), heatmap:bool=True, heatmap_thresh:int=16, return_fig:bool=None)->Optional[plt.Figure]: "Show images in `top_losses` along with their prediction, actual, loss, and probability of actual class." tl_val,tl_idx = self.to...
[ "def", "_cl_int_plot_top_losses", "(", "self", ",", "k", ",", "largest", "=", "True", ",", "figsize", "=", "(", "12", ",", "12", ")", ",", "heatmap", ":", "bool", "=", "True", ",", "heatmap_thresh", ":", "int", "=", "16", ",", "return_fig", ":", "boo...
Show images in `top_losses` along with their prediction, actual, loss, and probability of actual class.
[ "Show", "images", "in", "top_losses", "along", "with", "their", "prediction", "actual", "loss", "and", "probability", "of", "actual", "class", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/learner.py#L130-L158
train
fastai/fastai
fastai/vision/learner.py
_cl_int_plot_multi_top_losses
def _cl_int_plot_multi_top_losses(self, samples:int=3, figsize:Tuple[int,int]=(8,8), save_misclassified:bool=False): "Show images in `top_losses` along with their prediction, actual, loss, and probability of predicted class in a multilabeled dataset." if samples >20: print("Max 20 samples") retu...
python
def _cl_int_plot_multi_top_losses(self, samples:int=3, figsize:Tuple[int,int]=(8,8), save_misclassified:bool=False): "Show images in `top_losses` along with their prediction, actual, loss, and probability of predicted class in a multilabeled dataset." if samples >20: print("Max 20 samples") retu...
[ "def", "_cl_int_plot_multi_top_losses", "(", "self", ",", "samples", ":", "int", "=", "3", ",", "figsize", ":", "Tuple", "[", "int", ",", "int", "]", "=", "(", "8", ",", "8", ")", ",", "save_misclassified", ":", "bool", "=", "False", ")", ":", "if", ...
Show images in `top_losses` along with their prediction, actual, loss, and probability of predicted class in a multilabeled dataset.
[ "Show", "images", "in", "top_losses", "along", "with", "their", "prediction", "actual", "loss", "and", "probability", "of", "predicted", "class", "in", "a", "multilabeled", "dataset", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/learner.py#L160-L200
train
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",...
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
train
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 = to...
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 = to...
[ "def", "get_toplosses_idxs", "(", "cls", ",", "learn", ",", "n_imgs", ",", "*", "*", "kwargs", ")", ":", "dl", "=", "learn", ".", "data", ".", "fix_dl", "if", "not", "n_imgs", ":", "n_imgs", "=", "len", "(", "dl", ".", "dataset", ")", "_", ",", "...
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
train
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=p...
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=p...
[ "def", "padded_ds", "(", "ll_input", ",", "size", "=", "(", "250", ",", "300", ")", ",", "resize_method", "=", "ResizeMethod", ".", "CROP", ",", "padding_mode", "=", "'zeros'", ",", "*", "*", "kwargs", ")", ":", "return", "ll_input", ".", "transform", ...
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
train
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", ",", "laye...
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
train
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) si...
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) si...
[ "def", "get_similars_idxs", "(", "cls", ",", "learn", ",", "layer_ls", ",", "*", "*", "kwargs", ")", ":", "hook", "=", "hook_output", "(", "learn", ".", "model", "[", "layer_ls", "[", "0", "]", "]", "[", "layer_ls", "[", "1", "]", "]", "[", "layer_...
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
train
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...
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...
[ "def", "get_actns", "(", "learn", ",", "hook", ":", "Hook", ",", "dl", ":", "DataLoader", ",", "pool", "=", "AdaptiveConcatPool2d", ",", "pool_dim", ":", "int", "=", "4", ",", "*", "*", "kwargs", ")", ":", "print", "(", "'Getting activations...'", ")", ...
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
train
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 ...
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 ...
[ "def", "comb_similarity", "(", "t1", ":", "torch", ".", "Tensor", ",", "t2", ":", "torch", ".", "Tensor", ",", "*", "*", "kwargs", ")", ":", "# https://github.com/pytorch/pytorch/issues/11202", "print", "(", "'Computing similarities...'", ")", "w1", "=", "t1", ...
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
train
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.argso...
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.argso...
[ "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", ",",...
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
train
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", "["...
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
train
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
train
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.but...
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.but...
[ "def", "make_button_widget", "(", "cls", ",", "label", ",", "file_path", "=", "None", ",", "handler", "=", "None", ",", "style", "=", "None", ",", "layout", "=", "Layout", "(", "width", "=", "'auto'", ")", ")", ":", "btn", "=", "widgets", ".", "Butto...
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
train
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...
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...
[ "def", "make_dropdown_widget", "(", "cls", ",", "description", "=", "'Description'", ",", "options", "=", "[", "'Label 1'", ",", "'Label 2'", "]", ",", "value", "=", "'Label 1'", ",", "file_path", "=", "None", ",", "layout", "=", "Layout", "(", ")", ",", ...
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
train
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
train
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", ...
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
train
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 ...
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 ...
[ "def", "create_image_list", "(", "self", ",", "dataset", ",", "fns_idxs", ")", ":", "items", "=", "dataset", ".", "x", ".", "items", "if", "self", ".", "_duplicates", ":", "chunked_idxs", "=", "chunks", "(", "fns_idxs", ",", "2", ")", "chunked_idxs", "="...
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
train
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] =...
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] =...
[ "def", "relabel", "(", "self", ",", "change", ")", ":", "class_new", ",", "class_old", ",", "file_path", "=", "change", ".", "new", ",", "change", ".", "old", ",", "change", ".", "owner", ".", "file_path", "fp", "=", "Path", "(", "file_path", ")", "p...
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
train
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) ...
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) ...
[ "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", ...
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
train
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
train
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_wid...
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_wid...
[ "def", "get_widgets", "(", "self", ",", "duplicates", ")", ":", "widgets", "=", "[", "]", "for", "(", "img", ",", "fp", ",", "human_readable_label", ")", "in", "self", ".", "_all_images", "[", ":", "self", ".", "_batch_size", "]", ":", "img_widget", "=...
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
train
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...
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
train
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 ...
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 ...
[ "def", "render", "(", "self", ")", ":", "clear_output", "(", ")", "self", ".", "write_csv", "(", ")", "if", "self", ".", "empty", "(", ")", "and", "self", ".", "_skipped", ">", "0", ":", "return", "display", "(", "f'No images to show :). {self._skipped} pa...
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
train
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.n...
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.n...
[ "def", "_line_shift", "(", "x", ":", "Tensor", ",", "mask", ":", "bool", "=", "False", ")", ":", "bs", ",", "nh", ",", "n", ",", "p", "=", "x", ".", "size", "(", ")", "x_pad", "=", "torch", ".", "cat", "(", "[", "x", ".", "new_zeros", "(", ...
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
train
fastai/fastai
fastai/text/models/transformer.py
tfmer_lm_split
def tfmer_lm_split(model:nn.Module) -> List[nn.Module]: "Split a RNN `model` in groups for differential learning rates." encoder = model[0] n = len(encoder.layers)//3 groups = [list(encoder.layers[:n]), list(encoder.layers[n:2*n]), list(encoder.layers[2*n:])] return groups + [[encoder.encoder, model...
python
def tfmer_lm_split(model:nn.Module) -> List[nn.Module]: "Split a RNN `model` in groups for differential learning rates." encoder = model[0] n = len(encoder.layers)//3 groups = [list(encoder.layers[:n]), list(encoder.layers[n:2*n]), list(encoder.layers[2*n:])] return groups + [[encoder.encoder, model...
[ "def", "tfmer_lm_split", "(", "model", ":", "nn", ".", "Module", ")", "->", "List", "[", "nn", ".", "Module", "]", ":", "encoder", "=", "model", "[", "0", "]", "n", "=", "len", "(", "encoder", ".", "layers", ")", "//", "3", "groups", "=", "[", ...
Split a RNN `model` in groups for differential learning rates.
[ "Split", "a", "RNN", "model", "in", "groups", "for", "differential", "learning", "rates", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/models/transformer.py#L255-L260
train
fastai/fastai
fastai/text/models/transformer.py
tfmer_clas_split
def tfmer_clas_split(model:nn.Module) -> List[nn.Module]: "Split a RNN `model` in groups for differential learning rates." encoder = model[0].module n = len(encoder.layers)//3 groups = [[encoder.encoder], list(encoder.layers[:n]), list(encoder.layers[n:2*n]), list(encoder.layers[2*n:])] return group...
python
def tfmer_clas_split(model:nn.Module) -> List[nn.Module]: "Split a RNN `model` in groups for differential learning rates." encoder = model[0].module n = len(encoder.layers)//3 groups = [[encoder.encoder], list(encoder.layers[:n]), list(encoder.layers[n:2*n]), list(encoder.layers[2*n:])] return group...
[ "def", "tfmer_clas_split", "(", "model", ":", "nn", ".", "Module", ")", "->", "List", "[", "nn", ".", "Module", "]", ":", "encoder", "=", "model", "[", "0", "]", ".", "module", "n", "=", "len", "(", "encoder", ".", "layers", ")", "//", "3", "grou...
Split a RNN `model` in groups for differential learning rates.
[ "Split", "a", "RNN", "model", "in", "groups", "for", "differential", "learning", "rates", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/models/transformer.py#L262-L267
train
fastai/fastai
fastai/text/models/transformer.py
tfmerXL_lm_split
def tfmerXL_lm_split(model:nn.Module) -> List[nn.Module]: "Split a RNN `model` in groups for differential learning rates." encoder = model[0] n = len(encoder.layers)//3 groups = [list(encoder.layers[:n]) + [ParameterModule(encoder.u), ParameterModule(encoder.v)]] return groups + [list(encoder.layers...
python
def tfmerXL_lm_split(model:nn.Module) -> List[nn.Module]: "Split a RNN `model` in groups for differential learning rates." encoder = model[0] n = len(encoder.layers)//3 groups = [list(encoder.layers[:n]) + [ParameterModule(encoder.u), ParameterModule(encoder.v)]] return groups + [list(encoder.layers...
[ "def", "tfmerXL_lm_split", "(", "model", ":", "nn", ".", "Module", ")", "->", "List", "[", "nn", ".", "Module", "]", ":", "encoder", "=", "model", "[", "0", "]", "n", "=", "len", "(", "encoder", ".", "layers", ")", "//", "3", "groups", "=", "[", ...
Split a RNN `model` in groups for differential learning rates.
[ "Split", "a", "RNN", "model", "in", "groups", "for", "differential", "learning", "rates", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/models/transformer.py#L277-L282
train
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
train
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: ...
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: ...
[ "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", "=", "sel...
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
train
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 ...
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 ...
[ "def", "batchnorm_to_fp32", "(", "module", ")", ":", "if", "isinstance", "(", "module", ",", "nn", ".", "modules", ".", "batchnorm", ".", "_BatchNorm", ")", ":", "module", ".", "float", "(", ")", "for", "child", "in", "module", ".", "children", "(", ")...
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", "func...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/fp16.py#L31-L43
train
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...
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...
[ "def", "copy_model_to_fp32", "(", "m", ",", "optim", ")", ":", "fp32_params", "=", "[", "m_param", ".", "clone", "(", ")", ".", "type", "(", "torch", ".", "cuda", ".", "FloatTensor", ")", ".", "detach", "(", ")", "for", "m_param", "in", "trainable_para...
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
train
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) ...
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) ...
[ "def", "setup_coverage", "(", "config", ",", "kernel", ",", "floc", ",", "output_loc", "=", "None", ")", ":", "language", "=", "kernel", ".", "language", "if", "language", ".", "startswith", "(", "'python'", ")", ":", "# Get the pytest-cov coverage object", "c...
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
train
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 execu...
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 execu...
[ "def", "teardown_coverage", "(", "config", ",", "kernel", ",", "output_loc", "=", "None", ")", ":", "language", "=", "kernel", ".", "language", "if", "language", ".", "startswith", "(", "'python'", ")", ":", "# Teardown code does not require any input, simply execut...
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
train
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_contr...
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_contr...
[ "def", "get_cov", "(", "config", ")", ":", "# Check with hasplugin to avoid getplugin exception in older pytest.", "if", "config", ".", "pluginmanager", ".", "hasplugin", "(", "'_cov'", ")", ":", "plugin", "=", "config", ".", "pluginmanager", ".", "getplugin", "(", ...
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
train
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 com...
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 com...
[ "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 com...
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
train
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 ...
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 ...
[ "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 generat...
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
train
fastai/fastai
fastai/core.py
chunks
def chunks(l:Collection, n:int)->Iterable: "Yield successive `n`-sized chunks from `l`." for i in range(0, len(l), n): yield l[i:i+n]
python
def chunks(l:Collection, n:int)->Iterable: "Yield successive `n`-sized chunks from `l`." for i in range(0, len(l), n): yield l[i:i+n]
[ "def", "chunks", "(", "l", ":", "Collection", ",", "n", ":", "int", ")", "->", "Iterable", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "l", ")", ",", "n", ")", ":", "yield", "l", "[", "i", ":", "i", "+", "n", "]" ]
Yield successive `n`-sized chunks from `l`.
[ "Yield", "successive", "n", "-", "sized", "chunks", "from", "l", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L57-L59
train
fastai/fastai
fastai/core.py
to_int
def to_int(b:Any)->Union[int,List[int]]: "Convert `b` to an int or list of ints (if `is_listy`); raises exception if not convertible" if is_listy(b): return [to_int(x) for x in b] else: return int(b)
python
def to_int(b:Any)->Union[int,List[int]]: "Convert `b` to an int or list of ints (if `is_listy`); raises exception if not convertible" if is_listy(b): return [to_int(x) for x in b] else: return int(b)
[ "def", "to_int", "(", "b", ":", "Any", ")", "->", "Union", "[", "int", ",", "List", "[", "int", "]", "]", ":", "if", "is_listy", "(", "b", ")", ":", "return", "[", "to_int", "(", "x", ")", "for", "x", "in", "b", "]", "else", ":", "return", ...
Convert `b` to an int or list of ints (if `is_listy`); raises exception if not convertible
[ "Convert", "b", "to", "an", "int", "or", "list", "of", "ints", "(", "if", "is_listy", ")", ";", "raises", "exception", "if", "not", "convertible" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L61-L64
train
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
train
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", ".", "sor...
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
train
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"...
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
train
fastai/fastai
fastai/core.py
arrays_split
def arrays_split(mask:NPArrayMask, *arrs:NPArrayableList)->SplitArrayList: "Given `arrs` is [a,b,...] and `mask`index - return[(a[mask],a[~mask]),(b[mask],b[~mask]),...]." assert all([len(arr)==len(arrs[0]) for arr in arrs]), 'All arrays should have same length' mask = array(mask) return list(zip(*[(a[m...
python
def arrays_split(mask:NPArrayMask, *arrs:NPArrayableList)->SplitArrayList: "Given `arrs` is [a,b,...] and `mask`index - return[(a[mask],a[~mask]),(b[mask],b[~mask]),...]." assert all([len(arr)==len(arrs[0]) for arr in arrs]), 'All arrays should have same length' mask = array(mask) return list(zip(*[(a[m...
[ "def", "arrays_split", "(", "mask", ":", "NPArrayMask", ",", "*", "arrs", ":", "NPArrayableList", ")", "->", "SplitArrayList", ":", "assert", "all", "(", "[", "len", "(", "arr", ")", "==", "len", "(", "arrs", "[", "0", "]", ")", "for", "arr", "in", ...
Given `arrs` is [a,b,...] and `mask`index - return[(a[mask],a[~mask]),(b[mask],b[~mask]),...].
[ "Given", "arrs", "is", "[", "a", "b", "...", "]", "and", "mask", "index", "-", "return", "[", "(", "a", "[", "mask", "]", "a", "[", "~mask", "]", ")", "(", "b", "[", "mask", "]", "b", "[", "~mask", "]", ")", "...", "]", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/core.py#L91-L95
train
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...
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...
[ "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...
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
train