text stringlengths 81 112k |
|---|
Pass a `dummy_batch` in evaluation mode in `m` with `size`.
def dummy_eval(m:nn.Module, size:tuple=(64,64)):
"Pass a `dummy_batch` in evaluation mode in `m` with `size`."
return m.eval()(dummy_batch(m, size)) |
Pass a dummy input through the model `m` to get the various sizes of activations.
def model_sizes(m:nn.Module, size:tuple=(64,64))->Tuple[Sizes,Tensor,Hooks]:
"Pass a dummy input through the model `m` to get the various sizes of activations."
with hook_outputs(m) as hooks:
x = dummy_eval(m, size)
... |
Return the number of output features for `model`.
def num_features_model(m:nn.Module)->int:
"Return the number of output features for `model`."
sz = 64
while True:
try: return model_sizes(m, size=(sz,sz))[-1][1]
except Exception as e:
sz *= 2
if sz > 2048: raise |
Pass a dummy input through the model to get the various sizes. Returns (res,x,hooks) if `full`
def params_size(m: Union[nn.Module,Learner], size: tuple = (3, 64, 64))->Tuple[Sizes, Tensor, Hooks]:
"Pass a dummy input through the model to get the various sizes. Returns (res,x,hooks) if `full`"
if isinstance(m, ... |
Print a summary of `m` using a output text width of `n` chars
def model_summary(m:Learner, n:int=70):
"Print a summary of `m` using a output text width of `n` chars"
info = layers_info(m)
header = ["Layer (type)", "Output Shape", "Param #", "Trainable"]
res = "=" * n + "\n"
res += f"{header[0]:<20}... |
Applies `hook_func` to `module`, `input`, `output`.
def hook_fn(self, module:nn.Module, input:Tensors, output:Tensors):
"Applies `hook_func` to `module`, `input`, `output`."
if self.detach:
input = (o.detach() for o in input ) if is_listy(input ) else input.detach()
output = (o... |
Remove the hook from the model.
def remove(self):
"Remove the hook from the model."
if not self.removed:
self.hook.remove()
self.removed=True |
Register the `Hooks` on `self.modules`.
def on_train_begin(self, **kwargs):
"Register the `Hooks` on `self.modules`."
if not self.modules:
self.modules = [m for m in flatten_model(self.learn.model)
if hasattr(m, 'weight')]
self.hooks = Hooks(self.modules,... |
Take the mean and std of `o`.
def hook(self, m:nn.Module, i:Tensors, o:Tensors)->Tuple[Rank0Tensor,Rank0Tensor]:
"Take the mean and std of `o`."
return o.mean().item(),o.std().item() |
Take the stored results and puts it in `self.stats`
def on_batch_end(self, train, **kwargs):
"Take the stored results and puts it in `self.stats`"
if train: self.stats.append(self.hooks.stored) |
Plots images given image files.
Arguments:
im_paths (list): list of paths
figsize (tuple): figure size
rows (int): number of rows
titles (list): list of titles
maintitle (string): main title
def plots_from_files(imspaths, figsize=(10,5), rows=1, titles=None, maintitle=None)... |
Displays the images and their probabilities of belonging to a certain class
Arguments:
idxs (numpy.ndarray): indexes of the image samples from the dataset
y (int): the selected class
Returns:
Plots the images in n rows [rows = n]
def plot_val_wi... |
Extracts the first 4 most correct/incorrect indexes from the ordered list of probabilities
Arguments:
mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False every... |
Extracts the first 4 most uncertain indexes from the ordered list of probabilities
Arguments:
mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False everywhere el... |
Extracts the predicted classes which correspond to the selected class (y) and to the specific case (prediction is correct - is_true=True, prediction is wrong - is_true=False)
Arguments:
y (int): the selected class
is_correct (boolean): a boolean flag (True, False) which spec... |
Plots the images which correspond to the selected class (y) and to the specific case (prediction is correct - is_true=True, prediction is wrong - is_true=False)
Arguments:
y (int): the selected class
is_correct (boolean): a boolean flag (True, False) which specify the what t... |
Extracts the predicted classes which correspond to the selected class (y) and have probabilities nearest to 1/number_of_classes (eg. 0.5 for 2 classes, 0.33 for 3 classes) for the selected class.
Arguments:
y (int): the selected class
Returns:
idxs (numpy.ndarra... |
PyTorch distributed training launch helper that spawns multiple distributed processes
def main(
gpus:Param("The GPUs to use for distributed training", str)='all',
script:Param("Script to run", str, opt=False)='',
args:Param("Args to pass to script", nargs='...', opt=False)=''
):
"PyTorch distributed tr... |
Add the metrics names to the `Recorder`.
def on_train_begin(self, **kwargs):
"Add the metrics names to the `Recorder`."
self.names = ifnone(self.learn.loss_func.metric_names, [])
if not self.names: warn('LossMetrics requested but no loss_func.metric_names provided')
self.learn.recorder.... |
Initialize the metrics for this epoch.
def on_epoch_begin(self, **kwargs):
"Initialize the metrics for this epoch."
self.metrics = {name:0. for name in self.names}
self.nums = 0 |
Update the metrics if not `train`
def on_batch_end(self, last_target, train, **kwargs):
"Update the metrics if not `train`"
if train: return
bs = last_target.size(0)
for name in self.names:
self.metrics[name] += bs * self.learn.loss_func.metrics[name].detach().cpu()
... |
Finish the computation and sends the result to the Recorder.
def on_epoch_end(self, last_metrics, **kwargs):
"Finish the computation and sends the result to the Recorder."
if not self.nums: return
metrics = [self.metrics[name]/self.nums for name in self.names]
return {'last_metrics': la... |
Create the various optimizers.
def on_train_begin(self, **kwargs):
"Create the various optimizers."
self.G_A,self.G_B = self.learn.model.G_A,self.learn.model.G_B
self.D_A,self.D_B = self.learn.model.D_A,self.learn.model.D_B
self.crit = self.learn.loss_func.crit
self.opt_G = self... |
Steps through the generators then each of the critics.
def on_batch_end(self, last_input, last_output, **kwargs):
"Steps through the generators then each of the critics."
self.G_A.zero_grad(); self.G_B.zero_grad()
fake_A, fake_B = last_output[0].detach(), last_output[1].detach()
real_A,... |
Put the various losses in the recorder.
def on_epoch_end(self, last_metrics, **kwargs):
"Put the various losses in the recorder."
return add_metrics(last_metrics, [s.smooth for k,s in self.smootheners.items()]) |
Prepare file with metric names.
def on_train_begin(self, **kwargs: Any) -> None:
"Prepare file with metric names."
self.path.parent.mkdir(parents=True, exist_ok=True)
self.file = self.path.open('a') if self.append else self.path.open('w')
self.file.write(','.join(self.learn.record... |
Add a line with `epoch` number, `smooth_loss` and `last_metrics`.
def on_epoch_end(self, epoch: int, smooth_loss: Tensor, last_metrics: MetricsList, **kwargs: Any) -> bool:
"Add a line with `epoch` number, `smooth_loss` and `last_metrics`."
last_metrics = ifnone(last_metrics, [])
stats = [str(s... |
Return two lists, one for the model parameters in FP16 and one for the master parameters in FP32.
def get_master(layer_groups:ModuleList, flat_master:bool=False) -> Tuple[List[List[Tensor]], List[List[Tensor]]]:
"Return two lists, one for the model parameters in FP16 and one for the master parameters in FP32."
... |
Copy the `model_params` gradients to `master_params` for the optimizer step.
def model_g2master_g(model_params:Sequence[Tensor], master_params:Sequence[Tensor], flat_master:bool=False)->None:
"Copy the `model_params` gradients to `master_params` for the optimizer step."
if flat_master:
for model_group,... |
Copy `master_params` to `model_params`.
def master2model(model_params:Sequence[Tensor], master_params:Sequence[Tensor], flat_master:bool=False)->None:
"Copy `master_params` to `model_params`."
if flat_master:
for model_group,master_group in zip(model_params,master_params):
if len(model_grou... |
Prepare the master model.
def on_train_begin(self, **kwargs:Any)->None:
"Prepare the master model."
#Get a copy of the model params in FP32
self.model_params, self.master_params = get_master(self.learn.layer_groups, self.flat_master)
#Changes the optimizer so that the optimization step ... |
Scale gradients up by `self.loss_scale` to prevent underflow.
def on_backward_begin(self, last_loss:Rank0Tensor, **kwargs:Any) -> Rank0Tensor:
"Scale gradients up by `self.loss_scale` to prevent underflow."
#To avoid gradient underflow, we scale the gradients
ret_loss = last_loss * self.loss_sc... |
Convert the gradients back to FP32 and divide them by the scale.
def on_backward_end(self, **kwargs:Any)->None:
"Convert the gradients back to FP32 and divide them by the scale."
if self.dynamic and grad_overflow(self.model_params) and self.loss_scale > 1:
self.loss_scale /= 2
s... |
Update the params from master to model and zero grad.
def on_step_end(self, **kwargs:Any)->None:
"Update the params from master to model and zero grad."
#Zeros the gradients of the model since the optimizer is disconnected.
self.learn.model.zero_grad()
#Update the params from master to ... |
Scale the image so that the smallest axis is of size targ.
Arguments:
im (array): image
targ (int): target size
def scale_min(im, targ, interpolation=cv2.INTER_AREA):
""" Scale the image so that the smallest axis is of size targ.
Arguments:
im (array): image
targ (int): ta... |
Zoom the center of image x by a factor of z+1 while retaining the original image size and proportion.
def zoom_cv(x,z):
""" Zoom the center of image x by a factor of z+1 while retaining the original image size and proportion. """
if z==0: return x
r,c,*_ = x.shape
M = cv2.getRotationMatrix2D((c/2,r/2),... |
Stretches image x horizontally by sr+1, and vertically by sc+1 while retaining the original image size and proportion.
def stretch_cv(x,sr,sc,interpolation=cv2.INTER_AREA):
""" Stretches image x horizontally by sr+1, and vertically by sc+1 while retaining the original image size and proportion. """
if sr==0 an... |
Perform any of 8 permutations of 90-degrees rotations or flips for image x.
def dihedral(x, dih):
""" Perform any of 8 permutations of 90-degrees rotations or flips for image x. """
x = np.rot90(x, dih%4)
return x if dih<4 else np.fliplr(x) |
Adjust image balance and contrast
def lighting(im, b, c):
""" Adjust image balance and contrast """
if b==0 and c==1: return im
mu = np.average(im)
return np.clip((im-mu)*c+mu+b,0.,1.).astype(np.float32) |
Return a squared resized image
def no_crop(im, min_sz=None, interpolation=cv2.INTER_AREA):
""" Return a squared resized image """
r,c,*_ = im.shape
if min_sz is None: min_sz = min(r,c)
return cv2.resize(im, (min_sz, min_sz), interpolation=interpolation) |
Return a center crop of an image
def center_crop(im, min_sz=None):
""" Return a center crop of an image """
r,c,*_ = im.shape
if min_sz is None: min_sz = min(r,c)
start_r = math.ceil((r-min_sz)/2)
start_c = math.ceil((c-min_sz)/2)
return crop(im, start_r, start_c, min_sz) |
Randomly crop an image with an aspect ratio and returns a squared resized image of size targ
References:
1. https://arxiv.org/pdf/1409.4842.pdf
2. https://arxiv.org/pdf/1802.07888.pdf
def googlenet_resize(im, targ, min_area_frac, min_aspect_ratio, max_aspect_ratio, flip_hw_p, interpolation=cv2.INTER_A... |
Cut out n_holes number of square holes of size length in image at random locations. Holes may overlap.
def cutout(im, n_holes, length):
""" Cut out n_holes number of square holes of size length in image at random locations. Holes may overlap. """
r,c,*_ = im.shape
mask = np.ones((r, c), np.int32)
for n... |
Calculate dimension of an image during scaling with aspect ratio
def scale_to(x, ratio, targ):
'''Calculate dimension of an image during scaling with aspect ratio'''
return max(math.floor(x*ratio), targ) |
crop image into a square of size sz,
def crop(im, r, c, sz):
'''
crop image into a square of size sz,
'''
return im[r:r+sz, c:c+sz] |
Convert mask YY to a bounding box, assumes 0 as background nonzero object
def to_bb(YY, y="deprecated"):
"""Convert mask YY to a bounding box, assumes 0 as background nonzero object"""
cols,rows = np.nonzero(YY)
if len(cols)==0: return np.zeros(4, dtype=np.float32)
top_row = np.min(rows)
left_col =... |
Transforming coordinates to pixels.
Arguments:
y : np array
vector in which (y[0], y[1]) and (y[2], y[3]) are the
the corners of a bounding box.
x : image
an image
Returns:
Y : image
of shape x.shape
def coords2px(y, x):
""" Transform... |
Apply a collection of transformation functions :fns: to images
def compose(im, y, fns):
""" Apply a collection of transformation functions :fns: to images """
for fn in fns:
#pdb.set_trace()
im, y =fn(im, y)
return im if y is None else (im, y) |
Generate a standard set of transformations
Arguments
---------
normalizer :
image normalizing function
denorm :
image denormalizing function
sz :
size, sz_y = sz if not specified.
tfms :
iterable collection of transformation functions
max_zoom : floa... |
Given the statistics of the training image sets, returns separate training and validation transform functions
def tfms_from_stats(stats, sz, aug_tfms=None, max_zoom=None, pad=0, crop_type=CropType.RANDOM,
tfm_y=None, sz_y=None, pad_mode=cv2.BORDER_REFLECT, norm_y=True, scale=None):
""" Given th... |
Returns separate transformers of images for training and validation.
Transformers are constructed according to the image statistics given by the model. (See tfms_from_stats)
Arguments:
f_model: model, pretrained or not pretrained
def tfms_from_model(f_model, sz, aug_tfms=None, max_zoom=None, pad=0, cr... |
Return list of files in `c` that are images. `check_ext` will filter to `image_extensions`.
def get_image_files(c:PathOrStr, check_ext:bool=True, recurse=False)->FilePathList:
"Return list of files in `c` that are images. `check_ext` will filter to `image_extensions`."
return get_files(c, extensions=(image_ext... |
Open a COCO style json in `fname` and returns the lists of filenames (with maybe `prefix`) and labelled bboxes.
def get_annotations(fname, prefix=None):
"Open a COCO style json in `fname` and returns the lists of filenames (with maybe `prefix`) and labelled bboxes."
annot_dict = json.load(open(fname))
id2i... |
Function that collect `samples` of labelled bboxes and adds padding with `pad_idx`.
def bb_pad_collate(samples:BatchSamples, pad_idx:int=0) -> Tuple[FloatTensor, Tuple[LongTensor, LongTensor]]:
"Function that collect `samples` of labelled bboxes and adds padding with `pad_idx`."
if isinstance(samples[0][1], in... |
Normalize `x` with `mean` and `std`.
def normalize(x:TensorImage, mean:FloatTensor,std:FloatTensor)->TensorImage:
"Normalize `x` with `mean` and `std`."
return (x-mean[...,None,None]) / std[...,None,None] |
Denormalize `x` with `mean` and `std`.
def denormalize(x:TensorImage, mean:FloatTensor,std:FloatTensor, do_x:bool=True)->TensorImage:
"Denormalize `x` with `mean` and `std`."
return x.cpu().float()*std[...,None,None] + mean[...,None,None] if do_x else x.cpu() |
`b` = `x`,`y` - normalize `x` array of imgs and `do_y` optionally `y`.
def _normalize_batch(b:Tuple[Tensor,Tensor], mean:FloatTensor, std:FloatTensor, do_x:bool=True, do_y:bool=False)->Tuple[Tensor,Tensor]:
"`b` = `x`,`y` - normalize `x` array of imgs and `do_y` optionally `y`."
x,y = b
mean,std = mean.to(... |
Create normalize/denormalize func using `mean` and `std`, can specify `do_y` and `device`.
def normalize_funcs(mean:FloatTensor, std:FloatTensor, do_x:bool=True, do_y:bool=False)->Tuple[Callable,Callable]:
"Create normalize/denormalize func using `mean` and `std`, can specify `do_y` and `device`."
mean,std = t... |
Make channel the first axis of `x` and flatten remaining axes
def channel_view(x:Tensor)->Tensor:
"Make channel the first axis of `x` and flatten remaining axes"
return x.transpose(0,1).contiguous().view(x.shape[1],-1) |
Download images listed in text file `urls` to path `dest`, at most `max_pics`
def download_images(urls:Collection[str], dest:PathOrStr, max_pics:int=1000, max_workers:int=8, timeout=4):
"Download images listed in text file `urls` to path `dest`, at most `max_pics`"
urls = open(urls).read().strip().split("\n")[... |
Size to resize to, to hit `targ_sz` at same aspect ratio, in PIL coords (i.e w*h)
def resize_to(img, targ_sz:int, use_min:bool=False):
"Size to resize to, to hit `targ_sz` at same aspect ratio, in PIL coords (i.e w*h)"
w,h = img.size
min_sz = (min if use_min else max)(w,h)
ratio = targ_sz/min_sz
re... |
Check if the image in `file` exists, maybe resize it and copy it in `dest`.
def verify_image(file:Path, idx:int, delete:bool, max_size:Union[int,Tuple[int,int]]=None, dest:Path=None, n_channels:int=3,
interp=PIL.Image.BILINEAR, ext:str=None, img_format:str=None, resume:bool=False, **kwargs):
"Chec... |
Check if the images in `path` aren't broken, maybe resize them and copy it in `dest`.
def verify_images(path:PathOrStr, delete:bool=True, max_workers:int=4, max_size:Union[int]=None, recurse:bool=False,
dest:PathOrStr='.', n_channels:int=3, interp=PIL.Image.BILINEAR, ext:str=None, img_format:str=None... |
Call `train_tfm` and `valid_tfm` after opening image, before converting from `PIL.Image`
def _ll_pre_transform(self, train_tfm:List[Callable], valid_tfm:List[Callable]):
"Call `train_tfm` and `valid_tfm` after opening image, before converting from `PIL.Image`"
self.train.x.after_open = compose(train_tfm)
s... |
Call `train_tfm` and `valid_tfm` after opening image, before converting from `PIL.Image`
def _db_pre_transform(self, train_tfm:List[Callable], valid_tfm:List[Callable]):
"Call `train_tfm` and `valid_tfm` after opening image, before converting from `PIL.Image`"
self.train_ds.x.after_open = compose(train_tfm)
... |
Resize images to `size` using `RandomResizedCrop`, passing along `kwargs` to train transform
def _presize(self, size:int, val_xtra_size:int=32, scale:Tuple[float]=(0.08, 1.0), ratio:Tuple[float]=(0.75, 4./3.),
interpolation:int=2):
"Resize images to `size` using `RandomResizedCrop`, passing along `kwa... |
Create an `ImageDataBunch` from `LabelLists` `lls` with potential `ds_tfms`.
def create_from_ll(cls, lls:LabelLists, bs:int=64, val_bs:int=None, ds_tfms:Optional[TfmList]=None,
num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callable]]=None, device:torch.device=None,
test:Opt... |
Create from imagenet style dataset in `path` with `train`,`valid`,`test` subfolders (or provide `valid_pct`).
def from_folder(cls, path:PathOrStr, train:PathOrStr='train', valid:PathOrStr='valid',
valid_pct=None, classes:Collection=None, **kwargs:Any)->'ImageDataBunch':
"Create from imagene... |
Create from a `DataFrame` `df`.
def from_df(cls, path:PathOrStr, df:pd.DataFrame, folder:PathOrStr=None, label_delim:str=None, valid_pct:float=0.2,
fn_col:IntsOrStrs=0, label_col:IntsOrStrs=1, suffix:str='', **kwargs:Any)->'ImageDataBunch':
"Create from a `DataFrame` `df`."
src = (Image... |
Create from a csv file in `path/csv_labels`.
def from_csv(cls, path:PathOrStr, folder:PathOrStr=None, label_delim:str=None, csv_labels:PathOrStr='labels.csv',
valid_pct:float=0.2, fn_col:int=0, label_col:int=1, suffix:str='', delimiter:str=None,
header:Optional[Union[int,str]]='infer'... |
Create from list of `fnames` in `path`.
def from_lists(cls, path:PathOrStr, fnames:FilePathList, labels:Collection[str], valid_pct:float=0.2,
item_cls:Callable=None, **kwargs):
"Create from list of `fnames` in `path`."
item_cls = ifnone(item_cls, ImageList)
fname2label = {f:l... |
Create from list of `fnames` in `path` with `label_func`.
def from_name_func(cls, path:PathOrStr, fnames:FilePathList, label_func:Callable, valid_pct:float=0.2, **kwargs):
"Create from list of `fnames` in `path` with `label_func`."
src = ImageList(fnames, path=path).split_by_rand_pct(valid_pct)
... |
Create from list of `fnames` in `path` with re expression `pat`.
def from_name_re(cls, path:PathOrStr, fnames:FilePathList, pat:str, valid_pct:float=0.2, **kwargs):
"Create from list of `fnames` in `path` with re expression `pat`."
pat = re.compile(pat)
def _get_label(fn):
if isinst... |
Create an empty `ImageDataBunch` in `path` with `classes`. Typically used for inference.
def single_from_classes(path:Union[Path, str], classes:Collection[str], ds_tfms:TfmList=None, **kwargs):
"Create an empty `ImageDataBunch` in `path` with `classes`. Typically used for inference."
warn("""This metho... |
Grab a batch of data and call reduction function `func` per channel
def batch_stats(self, funcs:Collection[Callable]=None, ds_type:DatasetType=DatasetType.Train)->Tensor:
"Grab a batch of data and call reduction function `func` per channel"
funcs = ifnone(funcs, [torch.mean,torch.std])
x = self... |
Add normalize transform using `stats` (defaults to `DataBunch.batch_stats`)
def normalize(self, stats:Collection[Tensor]=None, do_x:bool=True, do_y:bool=False)->None:
"Add normalize transform using `stats` (defaults to `DataBunch.batch_stats`)"
if getattr(self,'norm',False): raise Exception('Can not ca... |
Open image in `fn`, subclass and overwrite for custom behavior.
def open(self, fn):
"Open image in `fn`, subclass and overwrite for custom behavior."
return open_image(fn, convert_mode=self.convert_mode, after_open=self.after_open) |
Get the list of files in `path` that have an image suffix. `recurse` determines if we search subfolders.
def from_folder(cls, path:PathOrStr='.', extensions:Collection[str]=None, **kwargs)->ItemList:
"Get the list of files in `path` that have an image suffix. `recurse` determines if we search subfolders."
... |
Get the filenames in `cols` of `df` with `folder` in front of them, `suffix` at the end.
def from_df(cls, df:DataFrame, path:PathOrStr, cols:IntsOrStrs=0, folder:PathOrStr=None, suffix:str='', **kwargs)->'ItemList':
"Get the filenames in `cols` of `df` with `folder` in front of them, `suffix` at the end."
... |
Get the filenames in `path/csv_name` opened with `header`.
def from_csv(cls, path:PathOrStr, csv_name:str, header:str='infer', **kwargs)->'ItemList':
"Get the filenames in `path/csv_name` opened with `header`."
path = Path(path)
df = pd.read_csv(path/csv_name, header=header)
return cls.... |
Show the `xs` (inputs) and `ys` (targets) on a figure of `figsize`.
def show_xys(self, xs, ys, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs):
"Show the `xs` (inputs) and `ys` (targets) on a figure of `figsize`."
rows = int(np.ceil(math.sqrt(len(xs))))
axs = subplots(rows, rows... |
Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`.
def show_xyzs(self, xs, ys, zs, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs):
"Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`."
if self._square_show_res:
... |
Generate classes from unique `items` and add `background`.
def generate_classes(self, items):
"Generate classes from unique `items` and add `background`."
classes = super().generate_classes([o[1] for o in items])
classes = ['background'] + list(classes)
return classes |
Show the `xs` (inputs) and `ys`(targets) on a figure of `figsize`.
def show_xys(self, xs, ys, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs):
"Show the `xs` (inputs) and `ys`(targets) on a figure of `figsize`."
axs = subplots(len(xs), 2, imgsize=imgsize, figsize=figsize)
for ... |
Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`.
def show_xyzs(self, xs, ys, zs, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs):
"Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`."
title = 'Input / Prediction / Target... |
get total, used and free memory (in MBs) for gpu `id`. if `id` is not passed, currently selected torch device is used
def gpu_mem_get(id=None):
"get total, used and free memory (in MBs) for gpu `id`. if `id` is not passed, currently selected torch device is used"
if not use_gpu: return GPUMemory(0, 0, 0)
i... |
get [gpu_id, its_free_ram] for the first gpu with highest available RAM
def gpu_with_max_free_mem():
"get [gpu_id, its_free_ram] for the first gpu with highest available RAM"
mem_all = gpu_mem_get_all()
if not len(mem_all): return None, 0
free_all = np.array([x.free for x in mem_all])
id = np.argma... |
A decorator that runs `GPUMemTrace` w/ report on func
def gpu_mem_trace(func):
"A decorator that runs `GPUMemTrace` w/ report on func"
@functools.wraps(func)
def wrapper(*args, **kwargs):
with GPUMemTrace(ctx=func.__qualname__, on_exit_report=True):
return func(*args, **kwargs)
retu... |
iterate through all the columns of a dataframe and modify the data type
to reduce memory usage.
def reduce_mem_usage(df):
""" iterate through all the columns of a dataframe and modify the data type
to reduce memory usage.
"""
start_mem = df.memory_usage().sum() / 1024**2
print('Memory u... |
Return ' (ctx: subctx)' or ' (ctx)' or ' (subctx)' or '' depending on this and constructor arguments
def _get_ctx(self, subctx=None):
"Return ' (ctx: subctx)' or ' (ctx)' or ' (subctx)' or '' depending on this and constructor arguments"
l = []
if self.ctx is not None: l.append(self.ctx)
... |
Put `learn` on distributed training with `cuda_id`.
def _learner_distributed(learn:Learner, cuda_id:int, cache_dir:PathOrStr='tmp'):
"Put `learn` on distributed training with `cuda_id`."
learn.callbacks.append(DistributedTrainer(learn, cuda_id))
learn.callbacks.append(DistributedRecorder(learn, cuda_id, ca... |
Constructs a XResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
def xresnet18(pretrained=False, **kwargs):
"""Constructs a XResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = XResNet(Basic... |
Constructs a XResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
def xresnet50_2(pretrained=False, **kwargs):
"""Constructs a XResNet-50 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = XResNet(Bot... |
Calculate loss and metrics for a batch, call out to callbacks as necessary.
def loss_batch(model:nn.Module, xb:Tensor, yb:Tensor, loss_func:OptLossFunc=None, opt:OptOptimizer=None,
cb_handler:Optional[CallbackHandler]=None)->Tuple[Union[Tensor,int,float,str]]:
"Calculate loss and metrics for a batch... |
Tuple of predictions and targets, and optional losses (if `loss_func`) using `dl`, max batches `n_batch`.
def get_preds(model:nn.Module, dl:DataLoader, pbar:Optional[PBar]=None, cb_handler:Optional[CallbackHandler]=None,
activ:nn.Module=None, loss_func:OptLossFunc=None, n_batch:Optional[int]=None) -> Lis... |
Calculate `loss_func` of `model` on `dl` in evaluation mode.
def validate(model:nn.Module, dl:DataLoader, loss_func:OptLossFunc=None, cb_handler:Optional[CallbackHandler]=None,
pbar:Optional[PBar]=None, average=True, n_batch:Optional[int]=None)->Iterator[Tuple[Union[Tensor,int],...]]:
"Calculate `loss... |
Simple training of `model` for 1 epoch of `dl` using optim `opt` and loss function `loss_func`.
def train_epoch(model:nn.Module, dl:DataLoader, opt:optim.Optimizer, loss_func:LossFunction)->None:
"Simple training of `model` for 1 epoch of `dl` using optim `opt` and loss function `loss_func`."
model.train()
... |
Fit the `model` on `data` and learn using `loss_func` and `opt`.
def fit(epochs:int, learn:BasicLearner, callbacks:Optional[CallbackList]=None, metrics:OptMetrics=None)->None:
"Fit the `model` on `data` and learn using `loss_func` and `opt`."
assert len(learn.data.train_dl) != 0, f"""Your training dataloader i... |
Load a `Learner` object saved with `export_state` in `path/file` with empty data, optionally add `test` and load on `cpu`. `file` can be file-like (file or buffer)
def load_learner(path:PathOrStr, file:PathLikeOrBinaryStream='export.pkl', test:ItemList=None, **db_kwargs):
"Load a `Learner` object saved with `expor... |
Initialize recording status at beginning of training.
def on_train_begin(self, pbar:PBar, metrics_names:Collection[str], **kwargs:Any)->None:
"Initialize recording status at beginning of training."
self.pbar = pbar
self.names = ['epoch', 'train_loss'] if self.no_val else ['epoch', 'train_loss',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.