text
stringlengths
81
112k
Build Google Images Search Url params and return them as a string. def _url_params(size:str='>400*300', format:str='jpg') -> str: "Build Google Images Search Url params and return them as a string." _fmts = {'jpg':'ift:jpg','gif':'ift:gif','png':'ift:png','bmp':'ift:bmp', 'svg':'ift:svg','webp':'webp','ico':'ift:ico'} if size not in _img_sizes: raise RuntimeError(f"""Unexpected size argument value: {size}. See `widgets.image_downloader._img_sizes` for supported sizes.""") if format not in _fmts: raise RuntimeError(f"Unexpected image file format: {format}. Use jpg, gif, png, bmp, svg, webp, or ico.") return "&tbs=" + _img_sizes[size] + "," + _fmts[format]
Return a Google Images Search URL for a given search term. def _search_url(search_term:str, size:str='>400*300', format:str='jpg') -> str: "Return a Google Images Search URL for a given search term." return ('https://www.google.com/search?q=' + quote(search_term) + '&espv=2&biw=1366&bih=667&site=webhp&source=lnms&tbm=isch' + _url_params(size, format) + '&sa=X&ei=XosDVaCXD8TasATItgE&ved=0CAcQ_AUoAg')
Parse the Google Images Search for urls and return the image metadata as tuples (fname, url). 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 = requests.get(url, headers=headers).text return _html_to_img_tuples(html, format=format, n_images=n_images)
Parse the google images html to img tuples containining `(fname, url)` 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) img_tuples = ((_img_fname(d['ou']), d['ou']) for d in metadata_dicts if d['ity'] == format) return list(itertools.islice(img_tuples, n_images))
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`. 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 from selenium.webdriver.common.keys import Keys except: print("""Looks like you're trying to download > 100 images and `selenium` is not installed. Try running `pip install selenium` to fix this. You'll also need chrome and `chromedriver` installed.""") options = webdriver.ChromeOptions() options.add_argument("--headless") try: driver = webdriver.Chrome(chrome_options=options) except: print("""Error initializing chromedriver. Check if it's in your path by running `which chromedriver`""") driver.set_window_size(1440, 900) driver.get(url) for i in range(n_images // 100 + 1): driver.execute_script("window.scrollTo(0, document.body.scrollHeight)") time.sleep(0.5 + random.random()/2.0) n_available = len(driver.find_elements_by_css_selector("div.rg_meta")) if n_available < n_images: raise ValueError(f"Requested {n_images} images, but only found {n_available}.") html = driver.page_source driver.close() return _html_to_img_tuples(html, format=format, n_images=n_images)
Downloads images in `img_tuples` to `label_path`. If the directory doesn't exist, it'll be created automatically. Uses `parallel` to speed things up in `max_workers` when the system has enough CPU cores. If something doesn't work, try setting up `max_workers=0` to debug. def _download_images(label_path:PathOrStr, img_tuples:list, max_workers:int=defaults.cpus, timeout:int=4) -> FilePathList: """ Downloads images in `img_tuples` to `label_path`. If the directory doesn't exist, it'll be created automatically. Uses `parallel` to speed things up in `max_workers` when the system has enough CPU cores. If something doesn't work, try setting up `max_workers=0` to debug. """ os.makedirs(Path(label_path), exist_ok=True) parallel( partial(_download_single_image, label_path, timeout=timeout), img_tuples, max_workers=max_workers) return get_image_files(label_path)
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`. 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.findall(r'\.\w+?(?=(?:\?|$))', img_tuple[1]) suffix = suffix[0].lower() if len(suffix)>0 else '.jpg' fname = f"{i:08d}{suffix}" download_url(img_tuple[1], label_path/fname, timeout=timeout)
Initialize the widget UI and return the UI. def _init_ui(self) -> VBox: "Initialize the widget UI and return the UI." self._search_input = Text(placeholder="What images to search for?") self._count_input = BoundedIntText(placeholder="How many pics?", value=10, min=1, max=5000, step=1, layout=Layout(width='60px')) self._size_input = Dropdown(options= _img_sizes.keys(), value='>400*300', layout=Layout(width='120px')) self._download_button = Button(description="Search & Download", icon="download", layout=Layout(width='200px')) self._download_button.on_click(self.on_download_button_click) self._output = Output() self._controls_pane = HBox([self._search_input, self._count_input, self._size_input, self._download_button], layout=Layout(width='auto', height='40px')) self._heading = "" self._download_complete_heading = "<h3>Download complete. Here are a few images</h3>" self._preview_header = widgets.HTML(self._heading, layout=Layout(height='60px')) self._img_pane = Box(layout=Layout(display='inline')) return VBox([self._controls_pane, self._preview_header, self._img_pane])
Clear the widget's images preview pane. def clear_imgs(self) -> None: "Clear the widget's images preview pane." self._preview_header.value = self._heading self._img_pane.children = tuple()
Check if input value is empty. 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()
Download button click handler: validate search term and download images. 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.clear_imgs() downloaded_images = download_google_images(self._path, term, n_images=limit, size=size) self.display_images_widgets(downloaded_images[:min(limit, 12)]) self._preview_header.value = self._download_complete_heading self.render()
Display a few preview images in the notebook 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)
Initialize optimizer and learner hyperparameters. def on_train_begin(self, pbar, **kwargs:Any)->None: "Initialize optimizer and learner hyperparameters." setattr(pbar, 'clean_on_interrupt', True) self.learn.save('tmp') self.opt = self.learn.opt self.opt.lr = self.sched.start self.stop,self.best_loss = False,0. return {'skip_validate': True}
Determine if loss has runaway and we should stop. def on_batch_end(self, iteration:int, smooth_loss:TensorOrNumber, **kwargs:Any)->None: "Determine if loss has runaway and we should stop." if iteration==0 or smooth_loss < self.best_loss: self.best_loss = smooth_loss self.opt.lr = self.sched.step() if self.sched.is_done or (self.stop_div and (smooth_loss > 4*self.best_loss or torch.isnan(smooth_loss))): #We use the smoothed loss to decide on the stopping since it's less shaky. return {'stop_epoch': True, 'stop_training': True}
Cleanup learn model weights disturbed during LRFinder exploration. def on_train_end(self, **kwargs:Any)->None: "Cleanup learn model weights disturbed during LRFinder exploration." self.learn.load('tmp', purge=False) if hasattr(self.learn.model, 'reset'): self.learn.model.reset() for cb in self.callbacks: if hasattr(cb, 'reset'): cb.reset() print('LR Finder is complete, type {learner_name}.recorder.plot() to see the graph.')
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 which activations to keep. Additionally, the sampled activations is rescaled is using the factor 1/(1 - dropout). In the example given below, one can see that approximately .8 fraction of the returned tensors are zero. Rescaling with the factor 1/(1 - 0.8) returns a tensor with 5's in the unit places. The official link to the pytorch bernoulli function is here: http://pytorch.org/docs/master/torch.html#torch.bernoulli Examples: >>> a_Var = torch.autograd.Variable(torch.Tensor(2, 3, 4).uniform_(0, 1), requires_grad=False) >>> a_Var Variable containing: (0 ,.,.) = 0.6890 0.5412 0.4303 0.8918 0.3871 0.7944 0.0791 0.5979 0.4575 0.7036 0.6186 0.7217 (1 ,.,.) = 0.8354 0.1690 0.1734 0.8099 0.6002 0.2602 0.7907 0.4446 0.5877 0.7464 0.4257 0.3386 [torch.FloatTensor of size 2x3x4] >>> a_mask = dropout_mask(a_Var.data, (1,a_Var.size(1),a_Var.size(2)), dropout=0.8) >>> a_mask (0 ,.,.) = 0 5 0 0 0 0 0 5 5 0 5 0 [torch.FloatTensor of size 1x3x4] 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 uses the bernoulli distribution to decide which activations to keep. Additionally, the sampled activations is rescaled is using the factor 1/(1 - dropout). In the example given below, one can see that approximately .8 fraction of the returned tensors are zero. Rescaling with the factor 1/(1 - 0.8) returns a tensor with 5's in the unit places. The official link to the pytorch bernoulli function is here: http://pytorch.org/docs/master/torch.html#torch.bernoulli Examples: >>> a_Var = torch.autograd.Variable(torch.Tensor(2, 3, 4).uniform_(0, 1), requires_grad=False) >>> a_Var Variable containing: (0 ,.,.) = 0.6890 0.5412 0.4303 0.8918 0.3871 0.7944 0.0791 0.5979 0.4575 0.7036 0.6186 0.7217 (1 ,.,.) = 0.8354 0.1690 0.1734 0.8099 0.6002 0.2602 0.7907 0.4446 0.5877 0.7464 0.4257 0.3386 [torch.FloatTensor of size 2x3x4] >>> a_mask = dropout_mask(a_Var.data, (1,a_Var.size(1),a_Var.size(2)), dropout=0.8) >>> a_mask (0 ,.,.) = 0 5 0 0 0 0 0 5 5 0 5 0 [torch.FloatTensor of size 1x3x4] """ return x.new(*sz).bernoulli_(1-dropout)/(1-dropout)
for each string defined in self.weights, the corresponding attribute in the wrapped module is referenced, then deleted, and subsequently registered as a new parameter with a slightly modified name. Args: None Returns: None def _setup(self): """ for each string defined in self.weights, the corresponding attribute in the wrapped module is referenced, then deleted, and subsequently registered as a new parameter with a slightly modified name. Args: None Returns: None """ if isinstance(self.module, torch.nn.RNNBase): self.module.flatten_parameters = noop for name_w in self.weights: w = getattr(self.module, name_w) del self.module._parameters[name_w] self.module.register_parameter(name_w + '_raw', nn.Parameter(w.data))
Uses pytorch's built-in dropout function to apply dropout to the parameters of the wrapped module. Args: None Returns: None def _setweights(self): """ Uses pytorch's built-in dropout function to apply dropout to the parameters of the wrapped module. Args: None Returns: None """ for name_w in self.weights: raw_w = getattr(self.module, name_w + '_raw') w = torch.nn.functional.dropout(raw_w, p=self.dropout, training=self.training) if hasattr(self.module, name_w): delattr(self.module, name_w) setattr(self.module, name_w, w)
Load a saved `DataBunch` from `path/file`. `file` can be file-like (file or buffer) 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 a saved `DataBunch` from `path/file`. `file` can be file-like (file or buffer)" source = Path(path)/file if is_pathlike(file) else file ll = torch.load(source, map_location='cpu') if defaults.device == torch.device('cpu') else torch.load(source) return ll.databunch(path=path, bs=bs, val_bs=val_bs, num_workers=num_workers, dl_tfms=dl_tfms, device=device, collate_fn=collate_fn, no_check=no_check, **kwargs)
Create a `DataBunch` from `train_ds`, `valid_ds` and maybe `test_ds` with a batch size of `bs`. Passes `**dl_kwargs` to `DataLoader()` 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, **dl_kwargs)->'DataBunch': "Create a `DataBunch` from `train_ds`, `valid_ds` and maybe `test_ds` with a batch size of `bs`. Passes `**dl_kwargs` to `DataLoader()`" datasets = cls._init_ds(train_ds, valid_ds, test_ds) val_bs = ifnone(val_bs, bs) dls = [DataLoader(d, b, shuffle=s, drop_last=s, num_workers=num_workers, **dl_kwargs) for d,b,s in zip(datasets, (bs,val_bs,val_bs,val_bs), (True,False,False,False)) if d is not None] return cls(*dls, path=path, device=device, dl_tfms=dl_tfms, collate_fn=collate_fn, no_check=no_check)
Returns appropriate `Dataset` for validation, training, or test (`ds_type`). 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 self.valid_dl if ds_type == DatasetType.Valid else self.single_dl if ds_type == DatasetType.Single else self.fix_dl)
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. 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_dl] # Preserve the original ordering of Train, Valid, Fix, Single, Test Data Loaders # (Unknown/not verified as of 1.0.47 whether there are other methods explicitly using DLs their list index) if self.valid_dl: res.insert(1, self.valid_dl) return res if not self.test_dl else res + [self.test_dl]
Save the `DataBunch` in `self.path/file`. `file` can be file-like (file or buffer) 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.") return try_save(self.label_list, self.path, file)
Get one batch from the data loader of `ds_type`. Optionally `detach` and `denorm`. def one_batch(self, ds_type:DatasetType=DatasetType.Train, detach:bool=True, denorm:bool=True, cpu:bool=True)->Collection[Tensor]: "Get one batch from the data loader of `ds_type`. Optionally `detach` and `denorm`." dl = self.dl(ds_type) w = self.num_workers self.num_workers = 0 try: x,y = next(iter(dl)) finally: self.num_workers = w if detach: x,y = to_detach(x,cpu=cpu),to_detach(y,cpu=cpu) norm = getattr(self,'norm',False) if denorm and norm: x = self.denorm(x) if norm.keywords.get('do_y',False): y = self.denorm(y, do_x=True) return x,y
Get `item` into a batch. Optionally `detach` and `denorm`. 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)
Show a batch of data in `ds_type` on a few `rows`. def show_batch(self, rows:int=5, ds_type:DatasetType=DatasetType.Train, reverse:bool=False, **kwargs)->None: "Show a batch of data in `ds_type` on a few `rows`." x,y = self.one_batch(ds_type, True, True) if reverse: x,y = x.flip(0),y.flip(0) n_items = rows **2 if self.train_ds.x._square_show else rows if self.dl(ds_type).batch_size < n_items: n_items = self.dl(ds_type).batch_size xs = [self.train_ds.x.reconstruct(grab_idx(x, i)) for i in range(n_items)] #TODO: get rid of has_arg if possible if has_arg(self.train_ds.y.reconstruct, 'x'): ys = [self.train_ds.y.reconstruct(grab_idx(y, i), x=x) for i,x in enumerate(xs)] else : ys = [self.train_ds.y.reconstruct(grab_idx(y, i)) for i in range(n_items)] self.train_ds.x.show_xys(xs, ys, **kwargs)
Export the minimal state of `self` for inference in `self.path/file`. `file` can be file-like (file or buffer) 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), self.path, file)
Check the underlying data in the training set can be properly loaded. def sanity_check(self): "Check the underlying data in the training set can be properly loaded." final_message = "You can deactivate this warning by passing `no_check=True`." if not hasattr(self.train_ds, 'items') or len(self.train_ds.items) == 0 or not hasattr(self.train_dl, 'batch_sampler'): return if len(self.train_dl) == 0: warn(f"""Your training dataloader is empty, you have only {len(self.train_dl.dataset)} items in your training set. Your batch size is {self.train_dl.batch_size}, you should lower it.""") print(final_message) return idx = next(iter(self.train_dl.batch_sampler)) samples,fails = [],[] for i in idx: try: samples.append(self.train_dl.dataset[i]) except: fails.append(i) if len(fails) > 0: warn_msg = "There seems to be something wrong with your dataset, for example, in the first batch can't access" if len(fails) == len(idx): warn_msg += f" any element of self.train_ds.\nTried: {show_some(idx)}" else: warn_msg += f" these elements in self.train_ds: {show_some(fails)}" warn(warn_msg) print(final_message) return try: batch = self.collate_fn(samples) except: message = "It's not possible to collate samples of your dataset together in a batch." try: shapes = [[o[i].data.shape for o in samples] for i in range(2)] message += f'\nShapes of the inputs/targets:\n{shapes}' except: pass warn(message) print(final_message)
Instantiate a `OneCycleScheduler` with `lr_max`. def one_cycle_scheduler(lr_max:float, **kwargs:Any)->OneCycleScheduler: "Instantiate a `OneCycleScheduler` with `lr_max`." return partial(OneCycleScheduler, lr_max=lr_max, **kwargs)
Fit a model following the 1cycle policy. def fit_one_cycle(learn:Learner, cyc_len:int, max_lr:Union[Floats,slice]=defaults.lr, moms:Tuple[float,float]=(0.95,0.85), div_factor:float=25., pct_start:float=0.3, final_div:float=None, wd:float=None, callbacks:Optional[CallbackList]=None, tot_epochs:int=None, start_epoch:int=None)->None: "Fit a model following the 1cycle policy." max_lr = learn.lr_range(max_lr) callbacks = listify(callbacks) callbacks.append(OneCycleScheduler(learn, max_lr, moms=moms, div_factor=div_factor, pct_start=pct_start, final_div=final_div, tot_epochs=tot_epochs, start_epoch=start_epoch)) learn.fit(cyc_len, max_lr, wd=wd, callbacks=callbacks)
Explore lr from `start_lr` to `end_lr` over `num_it` iterations in `learn`. If `stop_div`, stops when loss diverges. def lr_find(learn:Learner, start_lr:Floats=1e-7, end_lr:Floats=10, num_it:int=100, stop_div:bool=True, wd:float=None): "Explore lr from `start_lr` to `end_lr` over `num_it` iterations in `learn`. If `stop_div`, stops when loss diverges." start_lr = learn.lr_range(start_lr) start_lr = np.array(start_lr) if is_listy(start_lr) else start_lr end_lr = learn.lr_range(end_lr) end_lr = np.array(end_lr) if is_listy(end_lr) else end_lr cb = LRFinder(learn, start_lr, end_lr, num_it, stop_div) epochs = int(np.ceil(num_it/len(learn.data.train_dl))) learn.fit(epochs, start_lr, callbacks=[cb], wd=wd)
Put `learn` in FP16 precision mode. def to_fp16(learn:Learner, loss_scale:float=None, max_noskip:int=1000, dynamic:bool=True, clip:float=None, flat_master:bool=False, max_scale:float=2**24)->Learner: "Put `learn` in FP16 precision mode." learn.to_fp32() learn.model = model2half(learn.model) learn.data.add_tfm(batch_to_half) learn.mp_cb = MixedPrecision(learn, loss_scale=loss_scale, max_noskip=max_noskip, dynamic=dynamic, clip=clip, flat_master=flat_master, max_scale=max_scale) learn.callbacks.append(learn.mp_cb) return learn
Put `learn` back to FP32 precision mode. 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
Add mixup https://arxiv.org/abs/1710.09412 to `learn`. 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
Add gradient clipping of `clip` during training. 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
Create a `ClassificationInterpretation` object from `learner` on `ds_type` with `tta`. 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)
If we have `last_metrics` plot them in our pbar graph def on_epoch_end(self, n_epochs:int, last_metrics:MetricsList, **kwargs)->bool: "If we have `last_metrics` plot them in our pbar graph" if last_metrics is not None and np.any(last_metrics): rec = self.learn.recorder iters = range_of(rec.losses) val_iter = np.array(rec.nb_batches).cumsum() x_bounds = (0, (n_epochs - len(rec.nb_batches)) * rec.nb_batches[-1] + len(rec.losses)) y_bounds = (0, max((max(Tensor(rec.losses)), max(Tensor(rec.val_losses))))) rec.pbar.update_graph([(iters, rec.losses), (val_iter, rec.val_losses)], x_bounds, y_bounds) return {}
Clip the gradient before the optimizer step. 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)
check if loss is reduction 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'")
accumulate samples and batches 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
accumulated step and reset samples, True will result in no stepping def on_backward_end(self, **kwargs): "accumulated step and reset samples, True will result in no stepping" if (self.acc_batches % self.n_step) == 0: for p in (self.learn.model.parameters()): if p.requires_grad: p.grad.div_(self.acc_samples) self.acc_samples = 0 else: return {'skip_step':True, 'skip_zero':True}
step the rest of the accumulated grads if not perfectly divisible 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()
Create an instance of `ClassificationInterpretation` 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)
Confusion matrix as an `np.ndarray`. def confusion_matrix(self, slice_size:int=1): "Confusion matrix as an `np.ndarray`." x=torch.arange(0,self.data.c) if slice_size is None: cm = ((self.pred_class==x[:,None]) & (self.y_true==x[:,None,None])).sum(2) else: cm = torch.zeros(self.data.c, self.data.c, dtype=x.dtype) for i in range(0, self.y_true.shape[0], slice_size): cm_slice = ((self.pred_class[i:i+slice_size]==x[:,None]) & (self.y_true[i:i+slice_size]==x[:,None,None])).sum(2) torch.add(cm, cm_slice, out=cm) return to_np(cm)
Plot the confusion matrix, with `title` and using `cmap`. def plot_confusion_matrix(self, normalize:bool=False, title:str='Confusion matrix', cmap:Any="Blues", slice_size:int=1, norm_dec:int=2, plot_txt:bool=True, return_fig:bool=None, **kwargs)->Optional[plt.Figure]: "Plot the confusion matrix, with `title` and using `cmap`." # This function is mainly copied from the sklearn docs cm = self.confusion_matrix(slice_size=slice_size) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] fig = plt.figure(**kwargs) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) tick_marks = np.arange(self.data.c) plt.xticks(tick_marks, self.data.y.classes, rotation=90) plt.yticks(tick_marks, self.data.y.classes, rotation=0) if plot_txt: thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): coeff = f'{cm[i, j]:.{norm_dec}f}' if normalize else f'{cm[i, j]}' plt.text(j, i, coeff, horizontalalignment="center", verticalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('Actual') plt.xlabel('Predicted') plt.grid(False) if ifnone(return_fig, defaults.return_fig): return fig
Sorted descending list of largest non-diagonal entries of confusion matrix, presented as actual, predicted, number of occurrences. def most_confused(self, min_val:int=1, slice_size:int=1)->Collection[Tuple[str,str,int]]: "Sorted descending list of largest non-diagonal entries of confusion matrix, presented as actual, predicted, number of occurrences." cm = self.confusion_matrix(slice_size=slice_size) np.fill_diagonal(cm, 0) res = [(self.data.classes[i],self.data.classes[j],cm[i,j]) for i,j in zip(*np.where(cm>=min_val))] return sorted(res, key=itemgetter(2), reverse=True)
`k` largest(/smallest) losses and indexes, defaulting to all losses (sorted by `largest`). 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)
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 emphasizes precision and beta > 1 favors recall. 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). beta == 1 places equal weight on precision and recall, b < 1 emphasizes precision and beta > 1 favors recall. """ assert beta > 0, 'beta needs to be greater than 0' beta2 = beta ** 2 rec = recall(log_preds, targs, thresh) prec = precision(log_preds, targs, thresh) return (1 + beta2) * prec * rec / (beta2 * prec + rec + epsilon)
see fbeta 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)
Distributed training of Imagenet. Fastest speed is if you run with: python -m fastai.launch 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.cuda.device_count() n_gpus = num_distrib() or 1 workers = min(12, num_cpus()//n_gpus) data = get_data(path/dirname, size, bs, workers) b_its = len(data.train_dl)//n_gpus # Using bs 256 on single GPU as baseline, scale the LR linearly tot_bs = bs*n_gpus bs_rat = tot_bs/256 lr *= bs_rat ph1 = (TrainingPhase(tot_epochs*0.10*b_its) .schedule_hp('lr', (lr/10,lr), anneal=annealing_cos)) ph2 = (TrainingPhase(tot_epochs*0.90*b_its) .schedule_hp('lr', (lr,lr/1e5), anneal=annealing_cos)) opt_func = partial(optim.Adam, eps=0.1, betas=(0.9,0.99)) learn = Learner(data, models.xresnet50(), metrics=[accuracy,top_k_accuracy], wd=1e-3, opt_func=opt_func, bn_wd=False, true_wd=True, loss_func = LabelSmoothingCrossEntropy()).mixup(alpha=0.2) learn.callback_fns += [ partial(GeneralScheduler, phases=(ph1,ph2)), partial(SaveModelCallback, every='epoch', name='model') ] learn.split(lambda m: (children(m)[-2],)) if gpu is None: learn.model = nn.DataParallel(learn.model) else: learn.to_distributed(gpu) learn.to_fp16(dynamic=True) learn.fit(tot_epochs, 1) if rank_distrib(): time.sleep(1) learn.save('done')
Get the metadata associated with `arch`. def cnn_config(arch): "Get the metadata associated with `arch`." torch.backends.cudnn.benchmark = True return model_meta.get(arch, _default_meta)
Cut off the body of a typically pretrained `model` at `cut` (int) or cut the model as specified by `cut(model)` (function). 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: ll = list(enumerate(model.children())) cut = next(i for i,o in reversed(ll) if has_pool_type(o)) if isinstance(cut, int): return nn.Sequential(*list(model.children())[:cut]) elif isinstance(cut, Callable): return cut(model) else: raise NamedError("cut must be either integer or a function")
Model head that takes `nf` features, runs through `lin_ftrs`, and about `nc` classes. def create_head(nf:int, nc:int, lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, concat_pool:bool=True, bn_final:bool=False): "Model head that takes `nf` features, runs through `lin_ftrs`, and about `nc` classes." lin_ftrs = [nf, 512, nc] if lin_ftrs is None else [nf] + lin_ftrs + [nc] ps = listify(ps) if len(ps) == 1: ps = [ps[0]/2] * (len(lin_ftrs)-2) + ps actns = [nn.ReLU(inplace=True)] * (len(lin_ftrs)-2) + [None] pool = AdaptiveConcatPool2d() if concat_pool else nn.AdaptiveAvgPool2d(1) layers = [pool, Flatten()] for ni,no,p,actn in zip(lin_ftrs[:-1], lin_ftrs[1:], ps, actns): layers += bn_drop_lin(ni, no, True, p, actn) if bn_final: layers.append(nn.BatchNorm1d(lin_ftrs[-1], momentum=0.01)) return nn.Sequential(*layers)
Create custom convnet architecture def create_cnn_model(base_arch:Callable, nc:int, cut:Union[int,Callable]=None, pretrained:bool=True, lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, custom_head:Optional[nn.Module]=None, split_on:Optional[SplitFuncOrIdxList]=None, bn_final:bool=False, concat_pool:bool=True): "Create custom convnet architecture" body = create_body(base_arch, pretrained, cut) if custom_head is None: nf = num_features_model(nn.Sequential(*body.children())) * (2 if concat_pool else 1) head = create_head(nf, nc, lin_ftrs, ps=ps, concat_pool=concat_pool, bn_final=bn_final) else: head = custom_head return nn.Sequential(body, head)
Build convnet style learner. def cnn_learner(data:DataBunch, base_arch:Callable, cut:Union[int,Callable]=None, pretrained:bool=True, lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5, custom_head:Optional[nn.Module]=None, split_on:Optional[SplitFuncOrIdxList]=None, bn_final:bool=False, init=nn.init.kaiming_normal_, concat_pool:bool=True, **kwargs:Any)->Learner: "Build convnet style learner." meta = cnn_config(base_arch) model = create_cnn_model(base_arch, data.c, cut, pretrained, lin_ftrs, ps=ps, custom_head=custom_head, split_on=split_on, bn_final=bn_final, concat_pool=concat_pool) learn = Learner(data, model, **kwargs) learn.split(split_on or meta['split']) if pretrained: learn.freeze() if init: apply_init(model[1], init) return learn
Build Unet learner from `data` and `arch`. def unet_learner(data:DataBunch, arch:Callable, pretrained:bool=True, blur_final:bool=True, norm_type:Optional[NormType]=NormType, split_on:Optional[SplitFuncOrIdxList]=None, blur:bool=False, self_attention:bool=False, y_range:Optional[Tuple[float,float]]=None, last_cross:bool=True, bottle:bool=False, cut:Union[int,Callable]=None, **learn_kwargs:Any)->Learner: "Build Unet learner from `data` and `arch`." meta = cnn_config(arch) body = create_body(arch, pretrained, cut) model = to_device(models.unet.DynamicUnet(body, n_classes=data.c, blur=blur, blur_final=blur_final, self_attention=self_attention, y_range=y_range, norm_type=norm_type, last_cross=last_cross, bottle=bottle), data.device) learn = Learner(data, model, **learn_kwargs) learn.split(ifnone(split_on, meta['split'])) if pretrained: learn.freeze() apply_init(model[2], nn.init.kaiming_normal_) return learn
Create an instance of `ClassificationInterpretation`. `tta` indicates if we want to use Test Time Augmentation. def _cl_int_from_learner(cls, learn:Learner, ds_type:DatasetType=DatasetType.Valid, tta=False): "Create an instance of `ClassificationInterpretation`. `tta` indicates if we want to use Test Time Augmentation." preds = learn.TTA(ds_type=ds_type, with_loss=True) if tta else learn.get_preds(ds_type=ds_type, with_loss=True) return cls(learn, *preds, ds_type=ds_type)
Show images in `top_losses` along with their prediction, actual, loss, and probability of actual class. 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.top_losses(k, largest) classes = self.data.classes cols = math.ceil(math.sqrt(k)) rows = math.ceil(k/cols) fig,axes = plt.subplots(rows, cols, figsize=figsize) fig.suptitle('prediction/actual/loss/probability', weight='bold', size=14) for i,idx in enumerate(tl_idx): im,cl = self.data.dl(self.ds_type).dataset[idx] cl = int(cl) im.show(ax=axes.flat[i], title= f'{classes[self.pred_class[idx]]}/{classes[cl]} / {self.losses[idx]:.2f} / {self.probs[idx][cl]:.2f}') if heatmap: xb,_ = self.data.one_item(im, detach=False, denorm=False) m = self.learn.model.eval() with hook_output(m[0]) as hook_a: with hook_output(m[0], grad= True) as hook_g: preds = m(xb) preds[0,cl].backward() acts = hook_a.stored[0].cpu() if (acts.shape[-1]*acts.shape[-2]) >= heatmap_thresh: grad = hook_g.stored[0][0].cpu() grad_chan = grad.mean(1).mean(1) mult = F.relu(((acts*grad_chan[...,None,None])).sum(0)) sz = list(im.shape[-2:]) axes.flat[i].imshow(mult, alpha=0.6, extent=(0,*sz[::-1],0), interpolation='bilinear', cmap='magma') if ifnone(return_fig, defaults.return_fig): return fig
Show images in `top_losses` along with their prediction, actual, loss, and probability of predicted class in a multilabeled dataset. 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") return losses, idxs = self.top_losses(self.data.c) l_dim = len(losses.size()) if l_dim == 1: losses, idxs = self.top_losses() infolist, ordlosses_idxs, mismatches_idxs, mismatches, losses_mismatches, mismatchescontainer = [],[],[],[],[],[] truthlabels = np.asarray(self.y_true, dtype=int) classes_ids = [k for k in enumerate(self.data.classes)] predclass = np.asarray(self.pred_class) for i,pred in enumerate(predclass): where_truth = np.nonzero((truthlabels[i]>0))[0] mismatch = np.all(pred!=where_truth) if mismatch: mismatches_idxs.append(i) if l_dim > 1 : losses_mismatches.append((losses[i][pred], i)) else: losses_mismatches.append((losses[i], i)) if l_dim > 1: infotup = (i, pred, where_truth, losses[i][pred], np.round(self.probs[i], decimals=3)[pred], mismatch) else: infotup = (i, pred, where_truth, losses[i], np.round(self.probs[i], decimals=3)[pred], mismatch) infolist.append(infotup) ds = self.data.dl(self.ds_type).dataset mismatches = ds[mismatches_idxs] ordlosses = sorted(losses_mismatches, key = lambda x: x[0], reverse=True) for w in ordlosses: ordlosses_idxs.append(w[1]) mismatches_ordered_byloss = ds[ordlosses_idxs] print(f'{str(len(mismatches))} misclassified samples over {str(len(self.data.valid_ds))} samples in the validation set.') samples = min(samples, len(mismatches)) for ima in range(len(mismatches_ordered_byloss)): mismatchescontainer.append(mismatches_ordered_byloss[ima][0]) for sampleN in range(samples): actualclasses = '' for clas in infolist[ordlosses_idxs[sampleN]][2]: actualclasses = f'{actualclasses} -- {str(classes_ids[clas][1])}' imag = mismatches_ordered_byloss[sampleN][0] imag = show_image(imag, figsize=figsize) imag.set_title(f"""Predicted: {classes_ids[infolist[ordlosses_idxs[sampleN]][1]][1]} \nActual: {actualclasses}\nLoss: {infolist[ordlosses_idxs[sampleN]][3]}\nProbability: {infolist[ordlosses_idxs[sampleN]][4]}""", loc='left') plt.show() if save_misclassified: return mismatchescontainer
Gets indices with top losses. 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
Sorts `ds_type` dataset by top losses and returns dataset and sorted indices. def get_toplosses_idxs(cls, learn, n_imgs, **kwargs): "Sorts `ds_type` dataset by top losses and returns dataset and sorted indices." dl = learn.data.fix_dl if not n_imgs: n_imgs = len(dl.dataset) _,_,top_losses = learn.get_preds(ds_type=DatasetType.Fix, with_loss=True) idxs = torch.topk(top_losses, n_imgs)[1] return cls.padded_ds(dl.dataset, **kwargs), idxs
For a LabelList `ll_input`, resize each image to `size` using `resize_method` and `padding_mode`. def padded_ds(ll_input, size=(250, 300), resize_method=ResizeMethod.CROP, padding_mode='zeros', **kwargs): "For a LabelList `ll_input`, resize each image to `size` using `resize_method` and `padding_mode`." return ll_input.transform(tfms=crop_pad(), size=size, resize_method=resize_method, padding_mode=padding_mode)
Gets the indices for the most similar images. 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
Gets the indices for the most similar images in `ds_type` dataset def get_similars_idxs(cls, learn, layer_ls, **kwargs): "Gets the indices for the most similar images in `ds_type` dataset" hook = hook_output(learn.model[layer_ls[0]][layer_ls[1]][layer_ls[2]]) dl = learn.data.fix_dl ds_actns = cls.get_actns(learn, hook=hook, dl=dl, **kwargs) similarities = cls.comb_similarity(ds_actns, ds_actns, **kwargs) idxs = cls.sort_idxs(similarities) return cls.padded_ds(dl, **kwargs), idxs
Gets activations at the layer specified by `hook`, applies `pool` of dim `pool_dim` and concatenates def get_actns(learn, hook:Hook, dl:DataLoader, pool=AdaptiveConcatPool2d, pool_dim:int=4, **kwargs): "Gets activations at the layer specified by `hook`, applies `pool` of dim `pool_dim` and concatenates" print('Getting activations...') actns = [] learn.model.eval() with torch.no_grad(): for (xb,yb) in progress_bar(dl): learn.model(xb) actns.append((hook.stored).cpu()) if pool: pool = pool(pool_dim) return pool(torch.cat(actns)).view(len(dl.x),-1) else: return torch.cat(actns).view(len(dl.x),-1)
Computes the similarity function between each embedding of `t1` and `t2` matrices. def comb_similarity(t1: torch.Tensor, t2: torch.Tensor, **kwargs): # https://github.com/pytorch/pytorch/issues/11202 "Computes the similarity function between each embedding of `t1` and `t2` matrices." print('Computing similarities...') w1 = t1.norm(p=2, dim=1, keepdim=True) w2 = w1 if t2 is t1 else t2.norm(p=2, dim=1, keepdim=True) t = torch.mm(t1, t2.t()) / (w1 * w2.t()).clamp(min=1e-8) return torch.tril(t, diagonal=-1)
Returns the `n` largest indices from a numpy array `arr`. def largest_indices(arr, n): "Returns the `n` largest indices from a numpy array `arr`." #https://stackoverflow.com/questions/6910641/how-do-i-get-indices-of-n-maximum-values-in-a-numpy-array flat = arr.flatten() indices = np.argpartition(flat, -n)[-n:] indices = indices[np.argsort(-flat[indices])] return np.unravel_index(indices, arr.shape)
Sorts `similarities` and return the indexes in pairs ordered by highest similarity. 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]
Returns an image widget for specified file name `img`. 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)
Return a Button widget with specified `handler`. def make_button_widget(cls, label, file_path=None, handler=None, style=None, layout=Layout(width='auto')): "Return a Button widget with specified `handler`." btn = widgets.Button(description=label, layout=layout) if handler is not None: btn.on_click(handler) if style is not None: btn.button_style = style btn.file_path = file_path btn.flagged_for_delete = False return btn
Return a Dropdown widget with specified `handler`. def make_dropdown_widget(cls, description='Description', options=['Label 1', 'Label 2'], value='Label 1', file_path=None, layout=Layout(), handler=None): "Return a Dropdown widget with specified `handler`." dd = widgets.Dropdown(description=description, options=options, value=value, layout=layout) if file_path is not None: dd.file_path = file_path if handler is not None: dd.observe(handler, names=['value']) return dd
Make a horizontal box with `children` and `layout`. def make_horizontal_box(cls, children, layout=Layout()): "Make a horizontal box with `children` and `layout`." return widgets.HBox(children, layout=layout)
Make a vertical box with `children` and `layout`. 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)
Create a list of images, filenames and labels but first removing files that are not supposed to be displayed. def create_image_list(self, dataset, fns_idxs): "Create a list of images, filenames and labels but first removing files that are not supposed to be displayed." items = dataset.x.items if self._duplicates: chunked_idxs = chunks(fns_idxs, 2) chunked_idxs = [chunk for chunk in chunked_idxs if Path(items[chunk[0]]).is_file() and Path(items[chunk[1]]).is_file()] return [(dataset.x[i]._repr_jpeg_(), items[i], self._labels[dataset.y[i].data]) for chunk in chunked_idxs for i in chunk] else: return [(dataset.x[i]._repr_jpeg_(), items[i], self._labels[dataset.y[i].data]) for i in fns_idxs if Path(items[i]).is_file()]
Relabel images by moving from parent dir with old label `class_old` to parent dir with new label `class_new`. def relabel(self, change): "Relabel images by moving from parent dir with old label `class_old` to parent dir with new label `class_new`." class_new,class_old,file_path = change.new,change.old,change.owner.file_path fp = Path(file_path) parent = fp.parents[1] self._csv_dict[fp] = class_new
Handler for 'Next Batch' button click. Delete all flagged images and renders next batch. def next_batch(self, _): "Handler for 'Next Batch' button click. Delete all flagged images and renders next batch." for img_widget, delete_btn, fp, in self._batch: fp = delete_btn.file_path if (delete_btn.flagged_for_delete == True): self.delete_image(fp) self._deleted_fns.append(fp) self._all_images = self._all_images[self._batch_size:] self.empty_batch() self.render()
Flag this image as delete or keep. 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
Create and format widget set. def get_widgets(self, duplicates): "Create and format widget set." widgets = [] for (img,fp,human_readable_label) in self._all_images[:self._batch_size]: img_widget = self.make_img_widget(img, layout=Layout(height='250px', width='300px')) dropdown = self.make_dropdown_widget(description='', options=self._labels, value=human_readable_label, file_path=fp, handler=self.relabel, layout=Layout(width='auto')) delete_btn = self.make_button_widget('Delete', file_path=fp, handler=self.on_delete) widgets.append(self.make_vertical_box([img_widget, dropdown, delete_btn], layout=Layout(width='auto', height='300px', overflow_x="hidden"), duplicates=duplicates)) self._batch.append((img_widget, delete_btn, fp)) return widgets
Check if current batch contains already deleted images. 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)
Re-render Jupyter cell for batch of images. def render(self): "Re-render Jupyter cell for batch of images." clear_output() self.write_csv() if self.empty() and self._skipped>0: return display(f'No images to show :). {self._skipped} pairs were ' f'skipped since at least one of the images was deleted by the user.') elif self.empty(): return display('No images to show :)') if self.batch_contains_deleted(): self.next_batch(None) self._skipped += 1 else: display(self.make_horizontal_box(self.get_widgets(self._duplicates))) display(self.make_button_widget('Next Batch', handler=self.next_batch, style="primary"))
Shift the line i of `x` by p-i elements to the left, is `mask` puts 0s on the diagonal. def _line_shift(x:Tensor, mask:bool=False): "Shift the line i of `x` by p-i elements to the left, is `mask` puts 0s on the diagonal." bs,nh,n,p = x.size() x_pad = torch.cat([x.new_zeros(bs,nh,n,1), x], dim=3) x_shift = x_pad.view(bs,nh,p + 1,n)[:,:,1:].view_as(x) if mask: x_shift.mul_(torch.tril(x.new_ones(n,p), p-n)[None,None,]) return x_shift
Split a RNN `model` in groups for differential learning rates. 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[1]]]
Split a RNN `model` in groups for differential learning rates. 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 groups + [[model[1]]]
Split a RNN `model` in groups for differential learning rates. 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[n:2*n]), list(encoder.layers[2*n:]), [encoder.encoder, model[1]]]
Reset the internal memory. def reset(self): "Reset the internal memory." self.hidden = [next(self.parameters()).data.new(0) for i in range(self.n_layers+1)]
Make report in form of two notebooks. Use nbdime diff-web to present the difference between reference cells and test cells. def make_report(self, outcome): """Make report in form of two notebooks. Use nbdime diff-web to present the difference between reference cells and test cells. """ failures = self.getreports('failed') if not failures: return for rep in failures: # Check if this is a notebook node msg = self._getfailureheadline(rep) lines = rep.longrepr.splitlines() if len(lines) > 1: self.section(msg, lines[1]) self._outrep_summary(rep) tmpdir = tempfile.mkdtemp() try: ref_file = os.path.join(tmpdir, 'reference.ipynb') test_file = os.path.join(tmpdir, 'test_result.ipynb') with io.open(ref_file, "w", encoding="utf8") as f: nbformat.write(self.nb_ref, f) with io.open(test_file, "w", encoding="utf8") as f: nbformat.write(self.nb_test, f) run_server( port=0, # Run on random port cwd=tmpdir, closable=True, on_port=lambda port: browse( port, ref_file, test_file, None)) finally: shutil.rmtree(tmpdir)
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. def batchnorm_to_fp32(module): ''' BatchNorm layers to have parameters in single precision. Find all layers and convert them back to float. This can't be done with built in .apply as that function will apply fn to all modules, parameters, and buffers. Thus we wouldn't be able to guard the float conversion based on the module type. ''' if isinstance(module, nn.modules.batchnorm._BatchNorm): module.float() for child in module.children(): batchnorm_to_fp32(child) return module
Creates a fp32 copy of model parameters and sets optimizer parameters def copy_model_to_fp32(m, optim): """ Creates a fp32 copy of model parameters and sets optimizer parameters """ fp32_params = [m_param.clone().type(torch.cuda.FloatTensor).detach() for m_param in trainable_params_(m)] optim_groups = [group['params'] for group in optim.param_groups] iter_fp32_params = iter(fp32_params) for group_params in optim_groups: for i in range(len(group_params)): if not group_params[i].requires_grad: continue # only update trainable_params_ fp32_param = next(iter_fp32_params) assert(fp32_param.shape == group_params[i].shape) fp32_param.requires_grad = group_params[i].requires_grad group_params[i] = fp32_param return fp32_params
Start coverage reporting in kernel. Currently supported kernel languages are: - Python def setup_coverage(config, kernel, floc, output_loc=None): """Start coverage reporting in kernel. Currently supported kernel languages are: - Python """ language = kernel.language if language.startswith('python'): # Get the pytest-cov coverage object cov = get_cov(config) if cov: # If present, copy the data file location used by pytest-cov data_file = os.path.abspath(cov.config.data_file) else: # Fall back on output_loc and current dir if not data_file = os.path.abspath(os.path.join(output_loc or os.getcwd(), '.coverage')) # Get options from pytest-cov's command line arguments: source = config.option.cov_source config_file = config.option.cov_config if isinstance(config_file, str) and os.path.isfile(config_file): config_file = os.path.abspath(config_file) # Copy the suffix of plugin if available suffix = _make_suffix(cov) if suffix is True: # Cannot merge data with autogen suffix, so turn off warning # for missing data in pytest-cov collector cov._warn_no_data = False # Build setup command and execute in kernel: cmd = _python_setup % (data_file, source, config_file, suffix) msg_id = kernel.kc.execute(cmd, stop_on_error=False) kernel.await_idle(msg_id, 60) # A minute should be plenty to enable coverage else: config.warn( 'C1', 'Coverage currently not supported for language "%s".' % language, floc) return
Finish coverage reporting in kernel. The coverage should previously have been started with setup_coverage. def teardown_coverage(config, kernel, output_loc=None): """Finish coverage reporting in kernel. The coverage should previously have been started with setup_coverage. """ language = kernel.language if language.startswith('python'): # Teardown code does not require any input, simply execute: msg_id = kernel.kc.execute(_python_teardown) kernel.await_idle(msg_id, 60) # A minute should be plenty to write out coverage # Ensure we merge our data into parent data of pytest-cov, if possible cov = get_cov(config) _merge_nbval_coverage_data(cov) else: # Warnings should be given on setup, or there might be no teardown # for a specific language, so do nothing here pass
Returns the coverage object of pytest-cov. def get_cov(config): """Returns the coverage object of pytest-cov.""" # Check with hasplugin to avoid getplugin exception in older pytest. if config.pluginmanager.hasplugin('_cov'): plugin = config.pluginmanager.getplugin('_cov') if plugin.cov_controller: return plugin.cov_controller.cov return None
Create a suffix for nbval data file depending on pytest-cov config. def _make_suffix(cov): """Create a suffix for nbval data file depending on pytest-cov config.""" # Check if coverage object has data_suffix: if cov and cov.data_suffix is not None: # If True, the suffix will be autogenerated by coverage.py. # The suffixed data files will be automatically combined later. if cov.data_suffix is True: return True # Has a suffix, but we add our own extension return cov.data_suffix + '.nbval' return 'nbval'
Merge nbval coverage data into pytest-cov data. def _merge_nbval_coverage_data(cov): """Merge nbval coverage data into pytest-cov data.""" if not cov: return suffix = _make_suffix(cov) if suffix is True: # Note: If suffix is true, we are running in parallel, so several # files will be generated. This will cause some warnings about "no coverage" # but is otherwise OK. Do nothing. return # Get the filename of the nbval coverage: filename = cov.data_files.filename + '.' + suffix # Read coverage generated by nbval in this run: nbval_data = coverage.CoverageData(debug=cov.debug) try: nbval_data.read_file(os.path.abspath(filename)) except coverage.CoverageException: return # Set up aliases (following internal coverage.py code here) aliases = None if cov.config.paths: aliases = coverage.files.PathAliases() for paths in cov.config.paths.values(): result = paths[0] for pattern in paths[1:]: aliases.add(pattern, result) # Merge nbval data into pytest-cov data: cov.data.update(nbval_data, aliases=aliases) # Delete our nbval coverage data coverage.misc.file_be_gone(filename)
Yield successive `n`-sized chunks from `l`. 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]
Convert `b` to an int or list of ints (if `is_listy`); raises exception if not convertible 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)
Return `True` if `a` is one-dimensional def is1d(a:Collection)->bool: "Return `True` if `a` is one-dimensional" return len(a.shape) == 1 if hasattr(a, 'shape') else True
Return sorted unique values of `x`. 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
List of label subdirectories in imagenet-style `folder`. 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)
Given `arrs` is [a,b,...] and `mask`index - return[(a[mask],a[~mask]),(b[mask],b[~mask]),...]. 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[mask],a[~mask]) for a in map(np.array, arrs)]))
Randomly split `arrs` with `valid_pct` ratio. good for creating validation set. def random_split(valid_pct:float, *arrs:NPArrayableList)->SplitArrayList: "Randomly split `arrs` with `valid_pct` ratio. good for creating validation set." assert (valid_pct>=0 and valid_pct<=1), 'Validation set percentage should be between 0 and 1' is_train = np.random.uniform(size=(len(arrs[0]),)) > valid_pct return arrays_split(is_train, *arrs)