partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
_perspective_warp
Apply warp of `magnitude` to `c`.
fastai/vision/transform.py
def _perspective_warp(c, magnitude:partial(uniform,size=8)=0, invert=False): "Apply warp of `magnitude` to `c`." magnitude = magnitude.view(4,2) targ_pts = [[x+m for x,m in zip(xs, ms)] for xs, ms in zip(_orig_pts, magnitude)] return _do_perspective_warp(c, targ_pts, invert)
def _perspective_warp(c, magnitude:partial(uniform,size=8)=0, invert=False): "Apply warp of `magnitude` to `c`." magnitude = magnitude.view(4,2) targ_pts = [[x+m for x,m in zip(xs, ms)] for xs, ms in zip(_orig_pts, magnitude)] return _do_perspective_warp(c, targ_pts, invert)
[ "Apply", "warp", "of", "magnitude", "to", "c", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L267-L271
[ "def", "_perspective_warp", "(", "c", ",", "magnitude", ":", "partial", "(", "uniform", ",", "size", "=", "8", ")", "=", "0", ",", "invert", "=", "False", ")", ":", "magnitude", "=", "magnitude", ".", "view", "(", "4", ",", "2", ")", "targ_pts", "=...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
_symmetric_warp
Apply symmetric warp of `magnitude` to `c`.
fastai/vision/transform.py
def _symmetric_warp(c, magnitude:partial(uniform,size=4)=0, invert=False): "Apply symmetric warp of `magnitude` to `c`." m = listify(magnitude, 4) targ_pts = [[-1-m[3],-1-m[1]], [-1-m[2],1+m[1]], [1+m[3],-1-m[0]], [1+m[2],1+m[0]]] return _do_perspective_warp(c, targ_pts, invert)
def _symmetric_warp(c, magnitude:partial(uniform,size=4)=0, invert=False): "Apply symmetric warp of `magnitude` to `c`." m = listify(magnitude, 4) targ_pts = [[-1-m[3],-1-m[1]], [-1-m[2],1+m[1]], [1+m[3],-1-m[0]], [1+m[2],1+m[0]]] return _do_perspective_warp(c, targ_pts, invert)
[ "Apply", "symmetric", "warp", "of", "magnitude", "to", "c", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L274-L278
[ "def", "_symmetric_warp", "(", "c", ",", "magnitude", ":", "partial", "(", "uniform", ",", "size", "=", "4", ")", "=", "0", ",", "invert", "=", "False", ")", ":", "m", "=", "listify", "(", "magnitude", ",", "4", ")", "targ_pts", "=", "[", "[", "-...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
_tilt
Tilt `c` field with random `direction` and `magnitude`.
fastai/vision/transform.py
def _tilt(c, direction:uniform_int, magnitude:uniform=0, invert=False): "Tilt `c` field with random `direction` and `magnitude`." orig_pts = [[-1,-1], [-1,1], [1,-1], [1,1]] if direction == 0: targ_pts = [[-1,-1], [-1,1], [1,-1-magnitude], [1,1+magnitude]] elif direction == 1: targ_pts = [[-1,-1-magni...
def _tilt(c, direction:uniform_int, magnitude:uniform=0, invert=False): "Tilt `c` field with random `direction` and `magnitude`." orig_pts = [[-1,-1], [-1,1], [1,-1], [1,1]] if direction == 0: targ_pts = [[-1,-1], [-1,1], [1,-1-magnitude], [1,1+magnitude]] elif direction == 1: targ_pts = [[-1,-1-magni...
[ "Tilt", "c", "field", "with", "random", "direction", "and", "magnitude", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L281-L289
[ "def", "_tilt", "(", "c", ",", "direction", ":", "uniform_int", ",", "magnitude", ":", "uniform", "=", "0", ",", "invert", "=", "False", ")", ":", "orig_pts", "=", "[", "[", "-", "1", ",", "-", "1", "]", ",", "[", "-", "1", ",", "1", "]", ","...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
get_transforms
Utility func to easily create a list of flip, rotate, `zoom`, warp, lighting transforms.
fastai/vision/transform.py
def get_transforms(do_flip:bool=True, flip_vert:bool=False, max_rotate:float=10., max_zoom:float=1.1, max_lighting:float=0.2, max_warp:float=0.2, p_affine:float=0.75, p_lighting:float=0.75, xtra_tfms:Optional[Collection[Transform]]=None)->Collection[Transform]: "Utility func to...
def get_transforms(do_flip:bool=True, flip_vert:bool=False, max_rotate:float=10., max_zoom:float=1.1, max_lighting:float=0.2, max_warp:float=0.2, p_affine:float=0.75, p_lighting:float=0.75, xtra_tfms:Optional[Collection[Transform]]=None)->Collection[Transform]: "Utility func to...
[ "Utility", "func", "to", "easily", "create", "a", "list", "of", "flip", "rotate", "zoom", "warp", "lighting", "transforms", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L307-L320
[ "def", "get_transforms", "(", "do_flip", ":", "bool", "=", "True", ",", "flip_vert", ":", "bool", "=", "False", ",", "max_rotate", ":", "float", "=", "10.", ",", "max_zoom", ":", "float", "=", "1.1", ",", "max_lighting", ":", "float", "=", "0.2", ",", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
_compute_zs_mat
Utility routine to compute zoom/squish matrix.
fastai/vision/transform.py
def _compute_zs_mat(sz:TensorImageSize, scale:float, squish:float, invert:bool, row_pct:float, col_pct:float)->AffineMatrix: "Utility routine to compute zoom/squish matrix." orig_ratio = math.sqrt(sz[1]/sz[0]) for s,r,i in zip(scale,squish, invert): s,r = 1/math.sqrt(s),math.sqrt(...
def _compute_zs_mat(sz:TensorImageSize, scale:float, squish:float, invert:bool, row_pct:float, col_pct:float)->AffineMatrix: "Utility routine to compute zoom/squish matrix." orig_ratio = math.sqrt(sz[1]/sz[0]) for s,r,i in zip(scale,squish, invert): s,r = 1/math.sqrt(s),math.sqrt(...
[ "Utility", "routine", "to", "compute", "zoom", "/", "squish", "matrix", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L322-L336
[ "def", "_compute_zs_mat", "(", "sz", ":", "TensorImageSize", ",", "scale", ":", "float", ",", "squish", ":", "float", ",", "invert", ":", "bool", ",", "row_pct", ":", "float", ",", "col_pct", ":", "float", ")", "->", "AffineMatrix", ":", "orig_ratio", "=...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
rand_resize_crop
Randomly resize and crop the image to a ratio in `ratios` after a zoom of `max_scale`.
fastai/vision/transform.py
def rand_resize_crop(size:int, max_scale:float=2., ratios:Tuple[float,float]=(0.75,1.33)): "Randomly resize and crop the image to a ratio in `ratios` after a zoom of `max_scale`." return [zoom_squish(scale=(1.,max_scale,8), squish=(*ratios,8), invert=(0.5,8), row_pct=(0.,1.), col_pct=(0.,1.)), crop(...
def rand_resize_crop(size:int, max_scale:float=2., ratios:Tuple[float,float]=(0.75,1.33)): "Randomly resize and crop the image to a ratio in `ratios` after a zoom of `max_scale`." return [zoom_squish(scale=(1.,max_scale,8), squish=(*ratios,8), invert=(0.5,8), row_pct=(0.,1.), col_pct=(0.,1.)), crop(...
[ "Randomly", "resize", "and", "crop", "the", "image", "to", "a", "ratio", "in", "ratios", "after", "a", "zoom", "of", "max_scale", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L346-L349
[ "def", "rand_resize_crop", "(", "size", ":", "int", ",", "max_scale", ":", "float", "=", "2.", ",", "ratios", ":", "Tuple", "[", "float", ",", "float", "]", "=", "(", "0.75", ",", "1.33", ")", ")", ":", "return", "[", "zoom_squish", "(", "scale", "...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
adjust_learning_rate
Sets the learning rate to the initial LR decayed by 10 every 30 epochs
old/fastai/models/cifar10/main_dxy.py
def adjust_learning_rate(optimizer, epoch, gammas, schedule): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" lr = args.learning_rate assert len(gammas) == len(schedule), "length of gammas and schedule should be equal" for (gamma, step) in zip(gammas, schedule): if (epoch >= ste...
def adjust_learning_rate(optimizer, epoch, gammas, schedule): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" lr = args.learning_rate assert len(gammas) == len(schedule), "length of gammas and schedule should be equal" for (gamma, step) in zip(gammas, schedule): if (epoch >= ste...
[ "Sets", "the", "learning", "rate", "to", "the", "initial", "LR", "decayed", "by", "10", "every", "30", "epochs" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/models/cifar10/main_dxy.py#L254-L265
[ "def", "adjust_learning_rate", "(", "optimizer", ",", "epoch", ",", "gammas", ",", "schedule", ")", ":", "lr", "=", "args", ".", "learning_rate", "assert", "len", "(", "gammas", ")", "==", "len", "(", "schedule", ")", ",", "\"length of gammas and schedule shou...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Learner.fit_gen
Method does some preparation before finally delegating to the 'fit' method for fitting the model. Namely, if cycle_len is defined, it adds a 'Cosine Annealing' scheduler for varying the learning rate across iterations. Method also computes the total number of epochs to fit based on provided 'cy...
old/fastai/learner.py
def fit_gen(self, model, data, layer_opt, n_cycle, cycle_len=None, cycle_mult=1, cycle_save_name=None, best_save_name=None, use_clr=None, use_clr_beta=None, metrics=None, callbacks=None, use_wd_sched=False, norm_wds=False, wds_sched_mult=None, use_swa=False, swa_start=1, swa...
def fit_gen(self, model, data, layer_opt, n_cycle, cycle_len=None, cycle_mult=1, cycle_save_name=None, best_save_name=None, use_clr=None, use_clr_beta=None, metrics=None, callbacks=None, use_wd_sched=False, norm_wds=False, wds_sched_mult=None, use_swa=False, swa_start=1, swa...
[ "Method", "does", "some", "preparation", "before", "finally", "delegating", "to", "the", "fit", "method", "for", "fitting", "the", "model", ".", "Namely", "if", "cycle_len", "is", "defined", "it", "adds", "a", "Cosine", "Annealing", "scheduler", "for", "varyin...
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L127-L249
[ "def", "fit_gen", "(", "self", ",", "model", ",", "data", ",", "layer_opt", ",", "n_cycle", ",", "cycle_len", "=", "None", ",", "cycle_mult", "=", "1", ",", "cycle_save_name", "=", "None", ",", "best_save_name", "=", "None", ",", "use_clr", "=", "None", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Learner.get_layer_opt
Method returns an instance of the LayerOptimizer class, which allows for setting differential learning rates for different parts of the model. An example of how a model maybe differentiated into different parts for application of differential learning rates and weight decays is ...
old/fastai/learner.py
def get_layer_opt(self, lrs, wds): """Method returns an instance of the LayerOptimizer class, which allows for setting differential learning rates for different parts of the model. An example of how a model maybe differentiated into different parts for application of differenti...
def get_layer_opt(self, lrs, wds): """Method returns an instance of the LayerOptimizer class, which allows for setting differential learning rates for different parts of the model. An example of how a model maybe differentiated into different parts for application of differenti...
[ "Method", "returns", "an", "instance", "of", "the", "LayerOptimizer", "class", "which", "allows", "for", "setting", "differential", "learning", "rates", "for", "different", "parts", "of", "the", "model", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L253-L273
[ "def", "get_layer_opt", "(", "self", ",", "lrs", ",", "wds", ")", ":", "return", "LayerOptimizer", "(", "self", ".", "opt_fn", ",", "self", ".", "get_layer_groups", "(", ")", ",", "lrs", ",", "wds", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Learner.fit
Method gets an instance of LayerOptimizer and delegates to self.fit_gen(..) Note that one can specify a list of learning rates which, when appropriately defined, will be applied to different segments of an architecture. This seems mostly relevant to ImageNet-trained models, where we want to alt...
old/fastai/learner.py
def fit(self, lrs, n_cycle, wds=None, **kwargs): """Method gets an instance of LayerOptimizer and delegates to self.fit_gen(..) Note that one can specify a list of learning rates which, when appropriately defined, will be applied to different segments of an architecture. This seems mos...
def fit(self, lrs, n_cycle, wds=None, **kwargs): """Method gets an instance of LayerOptimizer and delegates to self.fit_gen(..) Note that one can specify a list of learning rates which, when appropriately defined, will be applied to different segments of an architecture. This seems mos...
[ "Method", "gets", "an", "instance", "of", "LayerOptimizer", "and", "delegates", "to", "self", ".", "fit_gen", "(", "..", ")" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L275-L302
[ "def", "fit", "(", "self", ",", "lrs", ",", "n_cycle", ",", "wds", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "sched", "=", "None", "layer_opt", "=", "self", ".", "get_layer_opt", "(", "lrs", ",", "wds", ")", "return", "self", "...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Learner.lr_find
Helps you find an optimal learning rate for a model. It uses the technique developed in the 2015 paper `Cyclical Learning Rates for Training Neural Networks`, where we simply keep increasing the learning rate from a very small value, until the loss starts decreasing. Args: ...
old/fastai/learner.py
def lr_find(self, start_lr=1e-5, end_lr=10, wds=None, linear=False, **kwargs): """Helps you find an optimal learning rate for a model. It uses the technique developed in the 2015 paper `Cyclical Learning Rates for Training Neural Networks`, where we simply keep increasing the learnin...
def lr_find(self, start_lr=1e-5, end_lr=10, wds=None, linear=False, **kwargs): """Helps you find an optimal learning rate for a model. It uses the technique developed in the 2015 paper `Cyclical Learning Rates for Training Neural Networks`, where we simply keep increasing the learnin...
[ "Helps", "you", "find", "an", "optimal", "learning", "rate", "for", "a", "model", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L309-L346
[ "def", "lr_find", "(", "self", ",", "start_lr", "=", "1e-5", ",", "end_lr", "=", "10", ",", "wds", "=", "None", ",", "linear", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "save", "(", "'tmp'", ")", "layer_opt", "=", "self", ".",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Learner.lr_find2
A variant of lr_find() that helps find the best learning rate. It doesn't do an epoch but a fixed num of iterations (which may be more or less than an epoch depending on your data). At each step, it computes the validation loss and the metrics on the next batch of the validation data, so...
old/fastai/learner.py
def lr_find2(self, start_lr=1e-5, end_lr=10, num_it = 100, wds=None, linear=False, stop_dv=True, **kwargs): """A variant of lr_find() that helps find the best learning rate. It doesn't do an epoch but a fixed num of iterations (which may be more or less than an epoch depending on your data). ...
def lr_find2(self, start_lr=1e-5, end_lr=10, num_it = 100, wds=None, linear=False, stop_dv=True, **kwargs): """A variant of lr_find() that helps find the best learning rate. It doesn't do an epoch but a fixed num of iterations (which may be more or less than an epoch depending on your data). ...
[ "A", "variant", "of", "lr_find", "()", "that", "helps", "find", "the", "best", "learning", "rate", ".", "It", "doesn", "t", "do", "an", "epoch", "but", "a", "fixed", "num", "of", "iterations", "(", "which", "may", "be", "more", "or", "less", "than", ...
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L348-L367
[ "def", "lr_find2", "(", "self", ",", "start_lr", "=", "1e-5", ",", "end_lr", "=", "10", ",", "num_it", "=", "100", ",", "wds", "=", "None", ",", "linear", "=", "False", ",", "stop_dv", "=", "True", ",", "*", "*", "kwargs", ")", ":", "self", ".", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Learner.predict_array
Args: arr: a numpy array to be used as input to the model for prediction purposes Returns: a numpy array containing the predictions from the model
old/fastai/learner.py
def predict_array(self, arr): """ Args: arr: a numpy array to be used as input to the model for prediction purposes Returns: a numpy array containing the predictions from the model """ if not isinstance(arr, np.ndarray): raise OSError(f'Not valid numpy arr...
def predict_array(self, arr): """ Args: arr: a numpy array to be used as input to the model for prediction purposes Returns: a numpy array containing the predictions from the model """ if not isinstance(arr, np.ndarray): raise OSError(f'Not valid numpy arr...
[ "Args", ":", "arr", ":", "a", "numpy", "array", "to", "be", "used", "as", "input", "to", "the", "model", "for", "prediction", "purposes", "Returns", ":", "a", "numpy", "array", "containing", "the", "predictions", "from", "the", "model" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L381-L390
[ "def", "predict_array", "(", "self", ",", "arr", ")", ":", "if", "not", "isinstance", "(", "arr", ",", "np", ".", "ndarray", ")", ":", "raise", "OSError", "(", "f'Not valid numpy array'", ")", "self", ".", "model", ".", "eval", "(", ")", "return", "to_...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Learner.TTA
Predict with Test Time Augmentation (TTA) Additional to the original test/validation images, apply image augmentation to them (just like for training images) and calculate the mean of predictions. The intent is to increase the accuracy of predictions by examining the images using multiple ...
old/fastai/learner.py
def TTA(self, n_aug=4, is_test=False): """ Predict with Test Time Augmentation (TTA) Additional to the original test/validation images, apply image augmentation to them (just like for training images) and calculate the mean of predictions. The intent is to increase the accuracy of predi...
def TTA(self, n_aug=4, is_test=False): """ Predict with Test Time Augmentation (TTA) Additional to the original test/validation images, apply image augmentation to them (just like for training images) and calculate the mean of predictions. The intent is to increase the accuracy of predi...
[ "Predict", "with", "Test", "Time", "Augmentation", "(", "TTA", ")" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L392-L415
[ "def", "TTA", "(", "self", ",", "n_aug", "=", "4", ",", "is_test", "=", "False", ")", ":", "dl1", "=", "self", ".", "data", ".", "test_dl", "if", "is_test", "else", "self", ".", "data", ".", "val_dl", "dl2", "=", "self", ".", "data", ".", "test_a...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Learner.fit_opt_sched
Wraps us the content of phases to send them to model.fit(..) This will split the training in several parts, each with their own learning rates/ wds/momentums/optimizer detailed in phases. Additionaly we can add a list of different data objets in data_list to train on different datasets...
old/fastai/learner.py
def fit_opt_sched(self, phases, cycle_save_name=None, best_save_name=None, stop_div=False, data_list=None, callbacks=None, cut = None, use_swa=False, swa_start=1, swa_eval_freq=5, **kwargs): """Wraps us the content of phases to send them to model.fit(..) This will split the train...
def fit_opt_sched(self, phases, cycle_save_name=None, best_save_name=None, stop_div=False, data_list=None, callbacks=None, cut = None, use_swa=False, swa_start=1, swa_eval_freq=5, **kwargs): """Wraps us the content of phases to send them to model.fit(..) This will split the train...
[ "Wraps", "us", "the", "content", "of", "phases", "to", "send", "them", "to", "model", ".", "fit", "(", "..", ")" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L417-L466
[ "def", "fit_opt_sched", "(", "self", ",", "phases", ",", "cycle_save_name", "=", "None", ",", "best_save_name", "=", "None", ",", "stop_div", "=", "False", ",", "data_list", "=", "None", ",", "callbacks", "=", "None", ",", "cut", "=", "None", ",", "use_s...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
RNNTrainer.on_loss_begin
Save the extra outputs for later and only returns the true output.
fastai/callbacks/rnn.py
def on_loss_begin(self, last_output:Tuple[Tensor,Tensor,Tensor], **kwargs): "Save the extra outputs for later and only returns the true output." self.raw_out,self.out = last_output[1],last_output[2] return {'last_output': last_output[0]}
def on_loss_begin(self, last_output:Tuple[Tensor,Tensor,Tensor], **kwargs): "Save the extra outputs for later and only returns the true output." self.raw_out,self.out = last_output[1],last_output[2] return {'last_output': last_output[0]}
[ "Save", "the", "extra", "outputs", "for", "later", "and", "only", "returns", "the", "true", "output", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/rnn.py#L19-L22
[ "def", "on_loss_begin", "(", "self", ",", "last_output", ":", "Tuple", "[", "Tensor", ",", "Tensor", ",", "Tensor", "]", ",", "*", "*", "kwargs", ")", ":", "self", ".", "raw_out", ",", "self", ".", "out", "=", "last_output", "[", "1", "]", ",", "la...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
RNNTrainer.on_backward_begin
Apply AR and TAR to `last_loss`.
fastai/callbacks/rnn.py
def on_backward_begin(self, last_loss:Rank0Tensor, last_input:Tensor, **kwargs): "Apply AR and TAR to `last_loss`." #AR and TAR if self.alpha != 0.: last_loss += self.alpha * self.out[-1].float().pow(2).mean() if self.beta != 0.: h = self.raw_out[-1] if len(h)>1:...
def on_backward_begin(self, last_loss:Rank0Tensor, last_input:Tensor, **kwargs): "Apply AR and TAR to `last_loss`." #AR and TAR if self.alpha != 0.: last_loss += self.alpha * self.out[-1].float().pow(2).mean() if self.beta != 0.: h = self.raw_out[-1] if len(h)>1:...
[ "Apply", "AR", "and", "TAR", "to", "last_loss", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/rnn.py#L24-L31
[ "def", "on_backward_begin", "(", "self", ",", "last_loss", ":", "Rank0Tensor", ",", "last_input", ":", "Tensor", ",", "*", "*", "kwargs", ")", ":", "#AR and TAR", "if", "self", ".", "alpha", "!=", "0.", ":", "last_loss", "+=", "self", ".", "alpha", "*", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
convert_weights
Convert the model `wgts` to go with a new vocabulary.
fastai/text/learner.py
def convert_weights(wgts:Weights, stoi_wgts:Dict[str,int], itos_new:Collection[str]) -> Weights: "Convert the model `wgts` to go with a new vocabulary." dec_bias, enc_wgts = wgts.get('1.decoder.bias', None), wgts['0.encoder.weight'] wgts_m = enc_wgts.mean(0) if dec_bias is not None: bias_m = dec_bias.me...
def convert_weights(wgts:Weights, stoi_wgts:Dict[str,int], itos_new:Collection[str]) -> Weights: "Convert the model `wgts` to go with a new vocabulary." dec_bias, enc_wgts = wgts.get('1.decoder.bias', None), wgts['0.encoder.weight'] wgts_m = enc_wgts.mean(0) if dec_bias is not None: bias_m = dec_bias.me...
[ "Convert", "the", "model", "wgts", "to", "go", "with", "a", "new", "vocabulary", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L28-L43
[ "def", "convert_weights", "(", "wgts", ":", "Weights", ",", "stoi_wgts", ":", "Dict", "[", "str", ",", "int", "]", ",", "itos_new", ":", "Collection", "[", "str", "]", ")", "->", "Weights", ":", "dec_bias", ",", "enc_wgts", "=", "wgts", ".", "get", "...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
get_language_model
Create a language model from `arch` and its `config`, maybe `pretrained`.
fastai/text/learner.py
def get_language_model(arch:Callable, vocab_sz:int, config:dict=None, drop_mult:float=1.): "Create a language model from `arch` and its `config`, maybe `pretrained`." meta = _model_meta[arch] config = ifnone(config, meta['config_lm'].copy()) for k in config.keys(): if k.endswith('_p'): config[k...
def get_language_model(arch:Callable, vocab_sz:int, config:dict=None, drop_mult:float=1.): "Create a language model from `arch` and its `config`, maybe `pretrained`." meta = _model_meta[arch] config = ifnone(config, meta['config_lm'].copy()) for k in config.keys(): if k.endswith('_p'): config[k...
[ "Create", "a", "language", "model", "from", "arch", "and", "its", "config", "maybe", "pretrained", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L187-L199
[ "def", "get_language_model", "(", "arch", ":", "Callable", ",", "vocab_sz", ":", "int", ",", "config", ":", "dict", "=", "None", ",", "drop_mult", ":", "float", "=", "1.", ")", ":", "meta", "=", "_model_meta", "[", "arch", "]", "config", "=", "ifnone",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
language_model_learner
Create a `Learner` with a language model from `data` and `arch`.
fastai/text/learner.py
def language_model_learner(data:DataBunch, arch, config:dict=None, drop_mult:float=1., pretrained:bool=True, pretrained_fnames:OptStrTuple=None, **learn_kwargs) -> 'LanguageLearner': "Create a `Learner` with a language model from `data` and `arch`." model = get_language_model(arch, le...
def language_model_learner(data:DataBunch, arch, config:dict=None, drop_mult:float=1., pretrained:bool=True, pretrained_fnames:OptStrTuple=None, **learn_kwargs) -> 'LanguageLearner': "Create a `Learner` with a language model from `data` and `arch`." model = get_language_model(arch, le...
[ "Create", "a", "Learner", "with", "a", "language", "model", "from", "data", "and", "arch", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L201-L219
[ "def", "language_model_learner", "(", "data", ":", "DataBunch", ",", "arch", ",", "config", ":", "dict", "=", "None", ",", "drop_mult", ":", "float", "=", "1.", ",", "pretrained", ":", "bool", "=", "True", ",", "pretrained_fnames", ":", "OptStrTuple", "=",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
get_text_classifier
Create a text classifier from `arch` and its `config`, maybe `pretrained`.
fastai/text/learner.py
def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None, drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None, pad_idx:int=1) -> nn.Module: "Create a text classifier from `arch` and it...
def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None, drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None, pad_idx:int=1) -> nn.Module: "Create a text classifier from `arch` and it...
[ "Create", "a", "text", "classifier", "from", "arch", "and", "its", "config", "maybe", "pretrained", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L269-L284
[ "def", "get_text_classifier", "(", "arch", ":", "Callable", ",", "vocab_sz", ":", "int", ",", "n_class", ":", "int", ",", "bptt", ":", "int", "=", "70", ",", "max_len", ":", "int", "=", "20", "*", "70", ",", "config", ":", "dict", "=", "None", ",",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
text_classifier_learner
Create a `Learner` with a text classifier from `data` and `arch`.
fastai/text/learner.py
def text_classifier_learner(data:DataBunch, arch:Callable, bptt:int=70, max_len:int=70*20, config:dict=None, pretrained:bool=True, drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None, **learn_kwargs) -> 'TextClassifierLearner': "Crea...
def text_classifier_learner(data:DataBunch, arch:Callable, bptt:int=70, max_len:int=70*20, config:dict=None, pretrained:bool=True, drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None, **learn_kwargs) -> 'TextClassifierLearner': "Crea...
[ "Create", "a", "Learner", "with", "a", "text", "classifier", "from", "data", "and", "arch", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L286-L302
[ "def", "text_classifier_learner", "(", "data", ":", "DataBunch", ",", "arch", ":", "Callable", ",", "bptt", ":", "int", "=", "70", ",", "max_len", ":", "int", "=", "70", "*", "20", ",", "config", ":", "dict", "=", "None", ",", "pretrained", ":", "boo...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
RNNLearner.save_encoder
Save the encoder to `name` inside the model directory.
fastai/text/learner.py
def save_encoder(self, name:str): "Save the encoder to `name` inside the model directory." encoder = get_model(self.model)[0] if hasattr(encoder, 'module'): encoder = encoder.module torch.save(encoder.state_dict(), self.path/self.model_dir/f'{name}.pth')
def save_encoder(self, name:str): "Save the encoder to `name` inside the model directory." encoder = get_model(self.model)[0] if hasattr(encoder, 'module'): encoder = encoder.module torch.save(encoder.state_dict(), self.path/self.model_dir/f'{name}.pth')
[ "Save", "the", "encoder", "to", "name", "inside", "the", "model", "directory", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L57-L61
[ "def", "save_encoder", "(", "self", ",", "name", ":", "str", ")", ":", "encoder", "=", "get_model", "(", "self", ".", "model", ")", "[", "0", "]", "if", "hasattr", "(", "encoder", ",", "'module'", ")", ":", "encoder", "=", "encoder", ".", "module", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
RNNLearner.load_encoder
Load the encoder `name` from the model directory.
fastai/text/learner.py
def load_encoder(self, name:str, device:torch.device=None): "Load the encoder `name` from the model directory." encoder = get_model(self.model)[0] if device is None: device = self.data.device if hasattr(encoder, 'module'): encoder = encoder.module encoder.load_state_dict(torch.lo...
def load_encoder(self, name:str, device:torch.device=None): "Load the encoder `name` from the model directory." encoder = get_model(self.model)[0] if device is None: device = self.data.device if hasattr(encoder, 'module'): encoder = encoder.module encoder.load_state_dict(torch.lo...
[ "Load", "the", "encoder", "name", "from", "the", "model", "directory", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L63-L70
[ "def", "load_encoder", "(", "self", ",", "name", ":", "str", ",", "device", ":", "torch", ".", "device", "=", "None", ")", ":", "encoder", "=", "get_model", "(", "self", ".", "model", ")", "[", "0", "]", "if", "device", "is", "None", ":", "device",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
RNNLearner.load_pretrained
Load a pretrained model and adapts it to the data vocabulary.
fastai/text/learner.py
def load_pretrained(self, wgts_fname:str, itos_fname:str, strict:bool=True): "Load a pretrained model and adapts it to the data vocabulary." old_itos = pickle.load(open(itos_fname, 'rb')) old_stoi = {v:k for k,v in enumerate(old_itos)} wgts = torch.load(wgts_fname, map_location=lambda st...
def load_pretrained(self, wgts_fname:str, itos_fname:str, strict:bool=True): "Load a pretrained model and adapts it to the data vocabulary." old_itos = pickle.load(open(itos_fname, 'rb')) old_stoi = {v:k for k,v in enumerate(old_itos)} wgts = torch.load(wgts_fname, map_location=lambda st...
[ "Load", "a", "pretrained", "model", "and", "adapts", "it", "to", "the", "data", "vocabulary", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L72-L79
[ "def", "load_pretrained", "(", "self", ",", "wgts_fname", ":", "str", ",", "itos_fname", ":", "str", ",", "strict", ":", "bool", "=", "True", ")", ":", "old_itos", "=", "pickle", ".", "load", "(", "open", "(", "itos_fname", ",", "'rb'", ")", ")", "ol...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
RNNLearner.get_preds
Return predictions and targets on the valid, train, or test set, depending on `ds_type`.
fastai/text/learner.py
def get_preds(self, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False, n_batch:Optional[int]=None, pbar:Optional[PBar]=None, ordered:bool=False) -> List[Tensor]: "Return predictions and targets on the valid, train, or test set, depending on `ds_type`." self.model.reset() ...
def get_preds(self, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False, n_batch:Optional[int]=None, pbar:Optional[PBar]=None, ordered:bool=False) -> List[Tensor]: "Return predictions and targets on the valid, train, or test set, depending on `ds_type`." self.model.reset() ...
[ "Return", "predictions", "and", "targets", "on", "the", "valid", "train", "or", "test", "set", "depending", "on", "ds_type", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L81-L92
[ "def", "get_preds", "(", "self", ",", "ds_type", ":", "DatasetType", "=", "DatasetType", ".", "Valid", ",", "with_loss", ":", "bool", "=", "False", ",", "n_batch", ":", "Optional", "[", "int", "]", "=", "None", ",", "pbar", ":", "Optional", "[", "PBar"...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LanguageLearner.predict
Return the `n_words` that come after `text`.
fastai/text/learner.py
def predict(self, text:str, n_words:int=1, no_unk:bool=True, temperature:float=1., min_p:float=None, sep:str=' ', decoder=decode_spec_tokens): "Return the `n_words` that come after `text`." ds = self.data.single_dl.dataset self.model.reset() xb,yb = self.data.one_item(tex...
def predict(self, text:str, n_words:int=1, no_unk:bool=True, temperature:float=1., min_p:float=None, sep:str=' ', decoder=decode_spec_tokens): "Return the `n_words` that come after `text`." ds = self.data.single_dl.dataset self.model.reset() xb,yb = self.data.one_item(tex...
[ "Return", "the", "n_words", "that", "come", "after", "text", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L116-L135
[ "def", "predict", "(", "self", ",", "text", ":", "str", ",", "n_words", ":", "int", "=", "1", ",", "no_unk", ":", "bool", "=", "True", ",", "temperature", ":", "float", "=", "1.", ",", "min_p", ":", "float", "=", "None", ",", "sep", ":", "str", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LanguageLearner.beam_search
Return the `n_words` that come after `text` using beam search.
fastai/text/learner.py
def beam_search(self, text:str, n_words:int, no_unk:bool=True, top_k:int=10, beam_sz:int=1000, temperature:float=1., sep:str=' ', decoder=decode_spec_tokens): "Return the `n_words` that come after `text` using beam search." ds = self.data.single_dl.dataset self.model.reset() ...
def beam_search(self, text:str, n_words:int, no_unk:bool=True, top_k:int=10, beam_sz:int=1000, temperature:float=1., sep:str=' ', decoder=decode_spec_tokens): "Return the `n_words` that come after `text` using beam search." ds = self.data.single_dl.dataset self.model.reset() ...
[ "Return", "the", "n_words", "that", "come", "after", "text", "using", "beam", "search", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L137-L163
[ "def", "beam_search", "(", "self", ",", "text", ":", "str", ",", "n_words", ":", "int", ",", "no_unk", ":", "bool", "=", "True", ",", "top_k", ":", "int", "=", "10", ",", "beam_sz", ":", "int", "=", "1000", ",", "temperature", ":", "float", "=", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LanguageLearner.show_results
Show `rows` result of predictions on `ds_type` dataset.
fastai/text/learner.py
def show_results(self, ds_type=DatasetType.Valid, rows:int=5, max_len:int=20): from IPython.display import display, HTML "Show `rows` result of predictions on `ds_type` dataset." ds = self.dl(ds_type).dataset x,y = self.data.one_batch(ds_type, detach=False, denorm=False) preds = ...
def show_results(self, ds_type=DatasetType.Valid, rows:int=5, max_len:int=20): from IPython.display import display, HTML "Show `rows` result of predictions on `ds_type` dataset." ds = self.dl(ds_type).dataset x,y = self.data.one_batch(ds_type, detach=False, denorm=False) preds = ...
[ "Show", "rows", "result", "of", "predictions", "on", "ds_type", "dataset", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L165-L185
[ "def", "show_results", "(", "self", ",", "ds_type", "=", "DatasetType", ".", "Valid", ",", "rows", ":", "int", "=", "5", ",", "max_len", ":", "int", "=", "20", ")", ":", "from", "IPython", ".", "display", "import", "display", ",", "HTML", "ds", "=", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
MultiBatchEncoder.concat
Concatenate the `arrs` along the batch dimension.
fastai/text/learner.py
def concat(self, arrs:Collection[Tensor])->Tensor: "Concatenate the `arrs` along the batch dimension." return [torch.cat([l[si] for l in arrs], dim=1) for si in range_of(arrs[0])]
def concat(self, arrs:Collection[Tensor])->Tensor: "Concatenate the `arrs` along the batch dimension." return [torch.cat([l[si] for l in arrs], dim=1) for si in range_of(arrs[0])]
[ "Concatenate", "the", "arrs", "along", "the", "batch", "dimension", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L250-L252
[ "def", "concat", "(", "self", ",", "arrs", ":", "Collection", "[", "Tensor", "]", ")", "->", "Tensor", ":", "return", "[", "torch", ".", "cat", "(", "[", "l", "[", "si", "]", "for", "l", "in", "arrs", "]", ",", "dim", "=", "1", ")", "for", "s...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
batchnorm_2d
A batchnorm2d layer with `nf` features initialized depending on `norm_type`.
fastai/layers.py
def batchnorm_2d(nf:int, norm_type:NormType=NormType.Batch): "A batchnorm2d layer with `nf` features initialized depending on `norm_type`." bn = nn.BatchNorm2d(nf) with torch.no_grad(): bn.bias.fill_(1e-3) bn.weight.fill_(0. if norm_type==NormType.BatchZero else 1.) return bn
def batchnorm_2d(nf:int, norm_type:NormType=NormType.Batch): "A batchnorm2d layer with `nf` features initialized depending on `norm_type`." bn = nn.BatchNorm2d(nf) with torch.no_grad(): bn.bias.fill_(1e-3) bn.weight.fill_(0. if norm_type==NormType.BatchZero else 1.) return bn
[ "A", "batchnorm2d", "layer", "with", "nf", "features", "initialized", "depending", "on", "norm_type", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L52-L58
[ "def", "batchnorm_2d", "(", "nf", ":", "int", ",", "norm_type", ":", "NormType", "=", "NormType", ".", "Batch", ")", ":", "bn", "=", "nn", ".", "BatchNorm2d", "(", "nf", ")", "with", "torch", ".", "no_grad", "(", ")", ":", "bn", ".", "bias", ".", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
bn_drop_lin
Sequence of batchnorm (if `bn`), dropout (with `p`) and linear (`n_in`,`n_out`) layers followed by `actn`.
fastai/layers.py
def bn_drop_lin(n_in:int, n_out:int, bn:bool=True, p:float=0., actn:Optional[nn.Module]=None): "Sequence of batchnorm (if `bn`), dropout (with `p`) and linear (`n_in`,`n_out`) layers followed by `actn`." layers = [nn.BatchNorm1d(n_in)] if bn else [] if p != 0: layers.append(nn.Dropout(p)) layers.append(...
def bn_drop_lin(n_in:int, n_out:int, bn:bool=True, p:float=0., actn:Optional[nn.Module]=None): "Sequence of batchnorm (if `bn`), dropout (with `p`) and linear (`n_in`,`n_out`) layers followed by `actn`." layers = [nn.BatchNorm1d(n_in)] if bn else [] if p != 0: layers.append(nn.Dropout(p)) layers.append(...
[ "Sequence", "of", "batchnorm", "(", "if", "bn", ")", "dropout", "(", "with", "p", ")", "and", "linear", "(", "n_in", "n_out", ")", "layers", "followed", "by", "actn", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L60-L66
[ "def", "bn_drop_lin", "(", "n_in", ":", "int", ",", "n_out", ":", "int", ",", "bn", ":", "bool", "=", "True", ",", "p", ":", "float", "=", "0.", ",", "actn", ":", "Optional", "[", "nn", ".", "Module", "]", "=", "None", ")", ":", "layers", "=", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
conv1d
Create and initialize a `nn.Conv1d` layer with spectral normalization.
fastai/layers.py
def conv1d(ni:int, no:int, ks:int=1, stride:int=1, padding:int=0, bias:bool=False): "Create and initialize a `nn.Conv1d` layer with spectral normalization." conv = nn.Conv1d(ni, no, ks, stride=stride, padding=padding, bias=bias) nn.init.kaiming_normal_(conv.weight) if bias: conv.bias.data.zero_() re...
def conv1d(ni:int, no:int, ks:int=1, stride:int=1, padding:int=0, bias:bool=False): "Create and initialize a `nn.Conv1d` layer with spectral normalization." conv = nn.Conv1d(ni, no, ks, stride=stride, padding=padding, bias=bias) nn.init.kaiming_normal_(conv.weight) if bias: conv.bias.data.zero_() re...
[ "Create", "and", "initialize", "a", "nn", ".", "Conv1d", "layer", "with", "spectral", "normalization", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L68-L73
[ "def", "conv1d", "(", "ni", ":", "int", ",", "no", ":", "int", ",", "ks", ":", "int", "=", "1", ",", "stride", ":", "int", "=", "1", ",", "padding", ":", "int", "=", "0", ",", "bias", ":", "bool", "=", "False", ")", ":", "conv", "=", "nn", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
conv2d
Create and initialize `nn.Conv2d` layer. `padding` defaults to `ks//2`.
fastai/layers.py
def conv2d(ni:int, nf:int, ks:int=3, stride:int=1, padding:int=None, bias=False, init:LayerFunc=nn.init.kaiming_normal_) -> nn.Conv2d: "Create and initialize `nn.Conv2d` layer. `padding` defaults to `ks//2`." if padding is None: padding = ks//2 return init_default(nn.Conv2d(ni, nf, kernel_size=ks, stride=st...
def conv2d(ni:int, nf:int, ks:int=3, stride:int=1, padding:int=None, bias=False, init:LayerFunc=nn.init.kaiming_normal_) -> nn.Conv2d: "Create and initialize `nn.Conv2d` layer. `padding` defaults to `ks//2`." if padding is None: padding = ks//2 return init_default(nn.Conv2d(ni, nf, kernel_size=ks, stride=st...
[ "Create", "and", "initialize", "nn", ".", "Conv2d", "layer", ".", "padding", "defaults", "to", "ks", "//", "2", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L115-L118
[ "def", "conv2d", "(", "ni", ":", "int", ",", "nf", ":", "int", ",", "ks", ":", "int", "=", "3", ",", "stride", ":", "int", "=", "1", ",", "padding", ":", "int", "=", "None", ",", "bias", "=", "False", ",", "init", ":", "LayerFunc", "=", "nn",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
conv2d_trans
Create `nn.ConvTranspose2d` layer.
fastai/layers.py
def conv2d_trans(ni:int, nf:int, ks:int=2, stride:int=2, padding:int=0, bias=False) -> nn.ConvTranspose2d: "Create `nn.ConvTranspose2d` layer." return nn.ConvTranspose2d(ni, nf, kernel_size=ks, stride=stride, padding=padding, bias=bias)
def conv2d_trans(ni:int, nf:int, ks:int=2, stride:int=2, padding:int=0, bias=False) -> nn.ConvTranspose2d: "Create `nn.ConvTranspose2d` layer." return nn.ConvTranspose2d(ni, nf, kernel_size=ks, stride=stride, padding=padding, bias=bias)
[ "Create", "nn", ".", "ConvTranspose2d", "layer", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L120-L122
[ "def", "conv2d_trans", "(", "ni", ":", "int", ",", "nf", ":", "int", ",", "ks", ":", "int", "=", "2", ",", "stride", ":", "int", "=", "2", ",", "padding", ":", "int", "=", "0", ",", "bias", "=", "False", ")", "->", "nn", ".", "ConvTranspose2d",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
relu
Return a relu activation, maybe `leaky` and `inplace`.
fastai/layers.py
def relu(inplace:bool=False, leaky:float=None): "Return a relu activation, maybe `leaky` and `inplace`." return nn.LeakyReLU(inplace=inplace, negative_slope=leaky) if leaky is not None else nn.ReLU(inplace=inplace)
def relu(inplace:bool=False, leaky:float=None): "Return a relu activation, maybe `leaky` and `inplace`." return nn.LeakyReLU(inplace=inplace, negative_slope=leaky) if leaky is not None else nn.ReLU(inplace=inplace)
[ "Return", "a", "relu", "activation", "maybe", "leaky", "and", "inplace", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L124-L126
[ "def", "relu", "(", "inplace", ":", "bool", "=", "False", ",", "leaky", ":", "float", "=", "None", ")", ":", "return", "nn", ".", "LeakyReLU", "(", "inplace", "=", "inplace", ",", "negative_slope", "=", "leaky", ")", "if", "leaky", "is", "not", "None...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
conv_layer
Create a sequence of convolutional (`ni` to `nf`), ReLU (if `use_activ`) and batchnorm (if `bn`) layers.
fastai/layers.py
def conv_layer(ni:int, nf:int, ks:int=3, stride:int=1, padding:int=None, bias:bool=None, is_1d:bool=False, norm_type:Optional[NormType]=NormType.Batch, use_activ:bool=True, leaky:float=None, transpose:bool=False, init:Callable=nn.init.kaiming_normal_, self_attention:bool=False): "Crea...
def conv_layer(ni:int, nf:int, ks:int=3, stride:int=1, padding:int=None, bias:bool=None, is_1d:bool=False, norm_type:Optional[NormType]=NormType.Batch, use_activ:bool=True, leaky:float=None, transpose:bool=False, init:Callable=nn.init.kaiming_normal_, self_attention:bool=False): "Crea...
[ "Create", "a", "sequence", "of", "convolutional", "(", "ni", "to", "nf", ")", "ReLU", "(", "if", "use_activ", ")", "and", "batchnorm", "(", "if", "bn", ")", "layers", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L128-L143
[ "def", "conv_layer", "(", "ni", ":", "int", ",", "nf", ":", "int", ",", "ks", ":", "int", "=", "3", ",", "stride", ":", "int", "=", "1", ",", "padding", ":", "int", "=", "None", ",", "bias", ":", "bool", "=", "None", ",", "is_1d", ":", "bool"...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
res_block
Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`.
fastai/layers.py
def res_block(nf, dense:bool=False, norm_type:Optional[NormType]=NormType.Batch, bottle:bool=False, **conv_kwargs): "Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`." norm2 = norm_type if not dense and (norm_type==NormType.Batch): norm2 = NormType.BatchZero nf_inner = nf//2 if bo...
def res_block(nf, dense:bool=False, norm_type:Optional[NormType]=NormType.Batch, bottle:bool=False, **conv_kwargs): "Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`." norm2 = norm_type if not dense and (norm_type==NormType.Batch): norm2 = NormType.BatchZero nf_inner = nf//2 if bo...
[ "Resnet", "block", "of", "nf", "features", ".", "conv_kwargs", "are", "passed", "to", "conv_layer", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L174-L181
[ "def", "res_block", "(", "nf", ",", "dense", ":", "bool", "=", "False", ",", "norm_type", ":", "Optional", "[", "NormType", "]", "=", "NormType", ".", "Batch", ",", "bottle", ":", "bool", "=", "False", ",", "*", "*", "conv_kwargs", ")", ":", "norm2",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
sigmoid_range
Sigmoid function with range `(low, high)`
fastai/layers.py
def sigmoid_range(x, low, high): "Sigmoid function with range `(low, high)`" return torch.sigmoid(x) * (high - low) + low
def sigmoid_range(x, low, high): "Sigmoid function with range `(low, high)`" return torch.sigmoid(x) * (high - low) + low
[ "Sigmoid", "function", "with", "range", "(", "low", "high", ")" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L183-L185
[ "def", "sigmoid_range", "(", "x", ",", "low", ",", "high", ")", ":", "return", "torch", ".", "sigmoid", "(", "x", ")", "*", "(", "high", "-", "low", ")", "+", "low" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
icnr
ICNR init of `x`, with `scale` and `init` function.
fastai/layers.py
def icnr(x, scale=2, init=nn.init.kaiming_normal_): "ICNR init of `x`, with `scale` and `init` function." ni,nf,h,w = x.shape ni2 = int(ni/(scale**2)) k = init(torch.zeros([ni2,nf,h,w])).transpose(0, 1) k = k.contiguous().view(ni2, nf, -1) k = k.repeat(1, 1, scale**2) k = k.contiguous().view...
def icnr(x, scale=2, init=nn.init.kaiming_normal_): "ICNR init of `x`, with `scale` and `init` function." ni,nf,h,w = x.shape ni2 = int(ni/(scale**2)) k = init(torch.zeros([ni2,nf,h,w])).transpose(0, 1) k = k.contiguous().view(ni2, nf, -1) k = k.repeat(1, 1, scale**2) k = k.contiguous().view...
[ "ICNR", "init", "of", "x", "with", "scale", "and", "init", "function", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L221-L229
[ "def", "icnr", "(", "x", ",", "scale", "=", "2", ",", "init", "=", "nn", ".", "init", ".", "kaiming_normal_", ")", ":", "ni", ",", "nf", ",", "h", ",", "w", "=", "x", ".", "shape", "ni2", "=", "int", "(", "ni", "/", "(", "scale", "**", "2",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
CrossEntropyFlat
Same as `nn.CrossEntropyLoss`, but flattens input and target.
fastai/layers.py
def CrossEntropyFlat(*args, axis:int=-1, **kwargs): "Same as `nn.CrossEntropyLoss`, but flattens input and target." return FlattenedLoss(nn.CrossEntropyLoss, *args, axis=axis, **kwargs)
def CrossEntropyFlat(*args, axis:int=-1, **kwargs): "Same as `nn.CrossEntropyLoss`, but flattens input and target." return FlattenedLoss(nn.CrossEntropyLoss, *args, axis=axis, **kwargs)
[ "Same", "as", "nn", ".", "CrossEntropyLoss", "but", "flattens", "input", "and", "target", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L269-L271
[ "def", "CrossEntropyFlat", "(", "*", "args", ",", "axis", ":", "int", "=", "-", "1", ",", "*", "*", "kwargs", ")", ":", "return", "FlattenedLoss", "(", "nn", ".", "CrossEntropyLoss", ",", "*", "args", ",", "axis", "=", "axis", ",", "*", "*", "kwarg...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
BCEWithLogitsFlat
Same as `nn.BCEWithLogitsLoss`, but flattens input and target.
fastai/layers.py
def BCEWithLogitsFlat(*args, axis:int=-1, floatify:bool=True, **kwargs): "Same as `nn.BCEWithLogitsLoss`, but flattens input and target." return FlattenedLoss(nn.BCEWithLogitsLoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs)
def BCEWithLogitsFlat(*args, axis:int=-1, floatify:bool=True, **kwargs): "Same as `nn.BCEWithLogitsLoss`, but flattens input and target." return FlattenedLoss(nn.BCEWithLogitsLoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs)
[ "Same", "as", "nn", ".", "BCEWithLogitsLoss", "but", "flattens", "input", "and", "target", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L273-L275
[ "def", "BCEWithLogitsFlat", "(", "*", "args", ",", "axis", ":", "int", "=", "-", "1", ",", "floatify", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "FlattenedLoss", "(", "nn", ".", "BCEWithLogitsLoss", ",", "*", "args", ",",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
BCEFlat
Same as `nn.BCELoss`, but flattens input and target.
fastai/layers.py
def BCEFlat(*args, axis:int=-1, floatify:bool=True, **kwargs): "Same as `nn.BCELoss`, but flattens input and target." return FlattenedLoss(nn.BCELoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs)
def BCEFlat(*args, axis:int=-1, floatify:bool=True, **kwargs): "Same as `nn.BCELoss`, but flattens input and target." return FlattenedLoss(nn.BCELoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs)
[ "Same", "as", "nn", ".", "BCELoss", "but", "flattens", "input", "and", "target", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L277-L279
[ "def", "BCEFlat", "(", "*", "args", ",", "axis", ":", "int", "=", "-", "1", ",", "floatify", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "FlattenedLoss", "(", "nn", ".", "BCELoss", ",", "*", "args", ",", "axis", "=", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
MSELossFlat
Same as `nn.MSELoss`, but flattens input and target.
fastai/layers.py
def MSELossFlat(*args, axis:int=-1, floatify:bool=True, **kwargs): "Same as `nn.MSELoss`, but flattens input and target." return FlattenedLoss(nn.MSELoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs)
def MSELossFlat(*args, axis:int=-1, floatify:bool=True, **kwargs): "Same as `nn.MSELoss`, but flattens input and target." return FlattenedLoss(nn.MSELoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs)
[ "Same", "as", "nn", ".", "MSELoss", "but", "flattens", "input", "and", "target", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L281-L283
[ "def", "MSELossFlat", "(", "*", "args", ",", "axis", ":", "int", "=", "-", "1", ",", "floatify", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "FlattenedLoss", "(", "nn", ".", "MSELoss", ",", "*", "args", ",", "axis", "="...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
simple_cnn
CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`.
fastai/layers.py
def simple_cnn(actns:Collection[int], kernel_szs:Collection[int]=None, strides:Collection[int]=None, bn=False) -> nn.Sequential: "CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`." nl = len(actns)-1 kernel_szs = ifnone(kernel_szs, [3]*nl) stride...
def simple_cnn(actns:Collection[int], kernel_szs:Collection[int]=None, strides:Collection[int]=None, bn=False) -> nn.Sequential: "CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`." nl = len(actns)-1 kernel_szs = ifnone(kernel_szs, [3]*nl) stride...
[ "CNN", "with", "conv_layer", "defined", "by", "actns", "kernel_szs", "and", "strides", "plus", "batchnorm", "if", "bn", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L293-L302
[ "def", "simple_cnn", "(", "actns", ":", "Collection", "[", "int", "]", ",", "kernel_szs", ":", "Collection", "[", "int", "]", "=", "None", ",", "strides", ":", "Collection", "[", "int", "]", "=", "None", ",", "bn", "=", "False", ")", "->", "nn", "....
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
trunc_normal_
Truncated normal initialization.
fastai/layers.py
def trunc_normal_(x:Tensor, mean:float=0., std:float=1.) -> Tensor: "Truncated normal initialization." # From https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/12 return x.normal_().fmod_(2).mul_(std).add_(mean)
def trunc_normal_(x:Tensor, mean:float=0., std:float=1.) -> Tensor: "Truncated normal initialization." # From https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/12 return x.normal_().fmod_(2).mul_(std).add_(mean)
[ "Truncated", "normal", "initialization", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L304-L307
[ "def", "trunc_normal_", "(", "x", ":", "Tensor", ",", "mean", ":", "float", "=", "0.", ",", "std", ":", "float", "=", "1.", ")", "->", "Tensor", ":", "# From https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/12", "return", "x", ".", "nor...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
embedding
Create an embedding layer.
fastai/layers.py
def embedding(ni:int,nf:int) -> nn.Module: "Create an embedding layer." emb = nn.Embedding(ni, nf) # See https://arxiv.org/abs/1711.09160 with torch.no_grad(): trunc_normal_(emb.weight, std=0.01) return emb
def embedding(ni:int,nf:int) -> nn.Module: "Create an embedding layer." emb = nn.Embedding(ni, nf) # See https://arxiv.org/abs/1711.09160 with torch.no_grad(): trunc_normal_(emb.weight, std=0.01) return emb
[ "Create", "an", "embedding", "layer", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L309-L314
[ "def", "embedding", "(", "ni", ":", "int", ",", "nf", ":", "int", ")", "->", "nn", ".", "Module", ":", "emb", "=", "nn", ".", "Embedding", "(", "ni", ",", "nf", ")", "# See https://arxiv.org/abs/1711.09160", "with", "torch", ".", "no_grad", "(", ")", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
MLFlowTracker.on_train_begin
Prepare MLflow experiment and log params
fastai/callbacks/mlflow.py
def on_train_begin(self, **kwargs: Any) -> None: "Prepare MLflow experiment and log params" self.client = mlflow.tracking.MlflowClient(self.uri) exp = self.client.get_experiment_by_name(self.exp_name) self.exp_id = self.client.create_experiment(self.exp_name) if exp is None else exp.expe...
def on_train_begin(self, **kwargs: Any) -> None: "Prepare MLflow experiment and log params" self.client = mlflow.tracking.MlflowClient(self.uri) exp = self.client.get_experiment_by_name(self.exp_name) self.exp_id = self.client.create_experiment(self.exp_name) if exp is None else exp.expe...
[ "Prepare", "MLflow", "experiment", "and", "log", "params" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L16-L24
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "client", "=", "mlflow", ".", "tracking", ".", "MlflowClient", "(", "self", ".", "uri", ")", "exp", "=", "self", ".", "client", ".", "ge...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
MLFlowTracker.on_epoch_end
Send loss and metrics values to MLFlow after each epoch
fastai/callbacks/mlflow.py
def on_epoch_end(self, epoch, **kwargs:Any)->None: "Send loss and metrics values to MLFlow after each epoch" if kwargs['smooth_loss'] is None or kwargs["last_metrics"] is None: return metrics = [kwargs['smooth_loss']] + kwargs["last_metrics"] for name, val in zip(self.metrics_names, metr...
def on_epoch_end(self, epoch, **kwargs:Any)->None: "Send loss and metrics values to MLFlow after each epoch" if kwargs['smooth_loss'] is None or kwargs["last_metrics"] is None: return metrics = [kwargs['smooth_loss']] + kwargs["last_metrics"] for name, val in zip(self.metrics_names, metr...
[ "Send", "loss", "and", "metrics", "values", "to", "MLFlow", "after", "each", "epoch" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L26-L31
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "kwargs", "[", "'smooth_loss'", "]", "is", "None", "or", "kwargs", "[", "\"last_metrics\"", "]", "is", "None", ":", "return", "metrics"...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
MLFlowTracker.on_train_end
Store the notebook and stop run
fastai/callbacks/mlflow.py
def on_train_end(self, **kwargs: Any) -> None: "Store the notebook and stop run" self.client.log_artifact(run_id=self.run, local_path=self.nb_path) self.client.set_terminated(run_id=self.run)
def on_train_end(self, **kwargs: Any) -> None: "Store the notebook and stop run" self.client.log_artifact(run_id=self.run, local_path=self.nb_path) self.client.set_terminated(run_id=self.run)
[ "Store", "the", "notebook", "and", "stop", "run" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L33-L36
[ "def", "on_train_end", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "client", ".", "log_artifact", "(", "run_id", "=", "self", ".", "run", ",", "local_path", "=", "self", ".", "nb_path", ")", "self", ".", "...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
pil2tensor
Convert PIL style `image` array to torch style image tensor.
fastai/vision/image.py
def pil2tensor(image:Union[NPImage,NPArray],dtype:np.dtype)->TensorImage: "Convert PIL style `image` array to torch style image tensor." a = np.asarray(image) if a.ndim==2 : a = np.expand_dims(a,2) a = np.transpose(a, (1, 0, 2)) a = np.transpose(a, (2, 1, 0)) return torch.from_numpy(a.astype(dty...
def pil2tensor(image:Union[NPImage,NPArray],dtype:np.dtype)->TensorImage: "Convert PIL style `image` array to torch style image tensor." a = np.asarray(image) if a.ndim==2 : a = np.expand_dims(a,2) a = np.transpose(a, (1, 0, 2)) a = np.transpose(a, (2, 1, 0)) return torch.from_numpy(a.astype(dty...
[ "Convert", "PIL", "style", "image", "array", "to", "torch", "style", "image", "tensor", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L14-L20
[ "def", "pil2tensor", "(", "image", ":", "Union", "[", "NPImage", ",", "NPArray", "]", ",", "dtype", ":", "np", ".", "dtype", ")", "->", "TensorImage", ":", "a", "=", "np", ".", "asarray", "(", "image", ")", "if", "a", ".", "ndim", "==", "2", ":",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
image2np
Convert from torch style `image` to numpy/matplotlib style.
fastai/vision/image.py
def image2np(image:Tensor)->np.ndarray: "Convert from torch style `image` to numpy/matplotlib style." res = image.cpu().permute(1,2,0).numpy() return res[...,0] if res.shape[2]==1 else res
def image2np(image:Tensor)->np.ndarray: "Convert from torch style `image` to numpy/matplotlib style." res = image.cpu().permute(1,2,0).numpy() return res[...,0] if res.shape[2]==1 else res
[ "Convert", "from", "torch", "style", "image", "to", "numpy", "/", "matplotlib", "style", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L22-L25
[ "def", "image2np", "(", "image", ":", "Tensor", ")", "->", "np", ".", "ndarray", ":", "res", "=", "image", ".", "cpu", "(", ")", ".", "permute", "(", "1", ",", "2", ",", "0", ")", ".", "numpy", "(", ")", "return", "res", "[", "...", ",", "0",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
bb2hw
Convert bounding box points from (width,height,center) to (height,width,top,left).
fastai/vision/image.py
def bb2hw(a:Collection[int])->np.ndarray: "Convert bounding box points from (width,height,center) to (height,width,top,left)." return np.array([a[1],a[0],a[3]-a[1],a[2]-a[0]])
def bb2hw(a:Collection[int])->np.ndarray: "Convert bounding box points from (width,height,center) to (height,width,top,left)." return np.array([a[1],a[0],a[3]-a[1],a[2]-a[0]])
[ "Convert", "bounding", "box", "points", "from", "(", "width", "height", "center", ")", "to", "(", "height", "width", "top", "left", ")", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L27-L29
[ "def", "bb2hw", "(", "a", ":", "Collection", "[", "int", "]", ")", "->", "np", ".", "ndarray", ":", "return", "np", ".", "array", "(", "[", "a", "[", "1", "]", ",", "a", "[", "0", "]", ",", "a", "[", "3", "]", "-", "a", "[", "1", "]", "...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
tis2hw
Convert `int` or `TensorImageSize` to (height,width) of an image.
fastai/vision/image.py
def tis2hw(size:Union[int,TensorImageSize]) -> Tuple[int,int]: "Convert `int` or `TensorImageSize` to (height,width) of an image." if type(size) is str: raise RuntimeError("Expected size to be an int or a tuple, got a string.") return listify(size, 2) if isinstance(size, int) else listify(size[-2:],2)
def tis2hw(size:Union[int,TensorImageSize]) -> Tuple[int,int]: "Convert `int` or `TensorImageSize` to (height,width) of an image." if type(size) is str: raise RuntimeError("Expected size to be an int or a tuple, got a string.") return listify(size, 2) if isinstance(size, int) else listify(size[-2:],2)
[ "Convert", "int", "or", "TensorImageSize", "to", "(", "height", "width", ")", "of", "an", "image", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L31-L34
[ "def", "tis2hw", "(", "size", ":", "Union", "[", "int", ",", "TensorImageSize", "]", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "if", "type", "(", "size", ")", "is", "str", ":", "raise", "RuntimeError", "(", "\"Expected size to be an int or a ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
_draw_outline
Outline bounding box onto image `Patch`.
fastai/vision/image.py
def _draw_outline(o:Patch, lw:int): "Outline bounding box onto image `Patch`." o.set_path_effects([patheffects.Stroke( linewidth=lw, foreground='black'), patheffects.Normal()])
def _draw_outline(o:Patch, lw:int): "Outline bounding box onto image `Patch`." o.set_path_effects([patheffects.Stroke( linewidth=lw, foreground='black'), patheffects.Normal()])
[ "Outline", "bounding", "box", "onto", "image", "Patch", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L36-L39
[ "def", "_draw_outline", "(", "o", ":", "Patch", ",", "lw", ":", "int", ")", ":", "o", ".", "set_path_effects", "(", "[", "patheffects", ".", "Stroke", "(", "linewidth", "=", "lw", ",", "foreground", "=", "'black'", ")", ",", "patheffects", ".", "Normal...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
_draw_rect
Draw bounding box on `ax`.
fastai/vision/image.py
def _draw_rect(ax:plt.Axes, b:Collection[int], color:str='white', text=None, text_size=14): "Draw bounding box on `ax`." patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor=color, lw=2)) _draw_outline(patch, 4) if text is not None: patch = ax.text(*b[:2], text, verticala...
def _draw_rect(ax:plt.Axes, b:Collection[int], color:str='white', text=None, text_size=14): "Draw bounding box on `ax`." patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor=color, lw=2)) _draw_outline(patch, 4) if text is not None: patch = ax.text(*b[:2], text, verticala...
[ "Draw", "bounding", "box", "on", "ax", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L41-L47
[ "def", "_draw_rect", "(", "ax", ":", "plt", ".", "Axes", ",", "b", ":", "Collection", "[", "int", "]", ",", "color", ":", "str", "=", "'white'", ",", "text", "=", "None", ",", "text_size", "=", "14", ")", ":", "patch", "=", "ax", ".", "add_patch"...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
open_image
Return `Image` object created from image in file `fn`.
fastai/vision/image.py
def open_image(fn:PathOrStr, div:bool=True, convert_mode:str='RGB', cls:type=Image, after_open:Callable=None)->Image: "Return `Image` object created from image in file `fn`." with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) # EXIF warning from TiffPlugin x = P...
def open_image(fn:PathOrStr, div:bool=True, convert_mode:str='RGB', cls:type=Image, after_open:Callable=None)->Image: "Return `Image` object created from image in file `fn`." with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) # EXIF warning from TiffPlugin x = P...
[ "Return", "Image", "object", "created", "from", "image", "in", "file", "fn", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L388-L397
[ "def", "open_image", "(", "fn", ":", "PathOrStr", ",", "div", ":", "bool", "=", "True", ",", "convert_mode", ":", "str", "=", "'RGB'", ",", "cls", ":", "type", "=", "Image", ",", "after_open", ":", "Callable", "=", "None", ")", "->", "Image", ":", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
open_mask
Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255.
fastai/vision/image.py
def open_mask(fn:PathOrStr, div=False, convert_mode='L', after_open:Callable=None)->ImageSegment: "Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255." return open_image(fn, div=div, convert_mode=convert_mode, cls=ImageSegment, after_open=after_open)
def open_mask(fn:PathOrStr, div=False, convert_mode='L', after_open:Callable=None)->ImageSegment: "Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255." return open_image(fn, div=div, convert_mode=convert_mode, cls=ImageSegment, after_open=after_open)
[ "Return", "ImageSegment", "object", "create", "from", "mask", "in", "file", "fn", ".", "If", "div", "divides", "pixel", "values", "by", "255", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L399-L401
[ "def", "open_mask", "(", "fn", ":", "PathOrStr", ",", "div", "=", "False", ",", "convert_mode", "=", "'L'", ",", "after_open", ":", "Callable", "=", "None", ")", "->", "ImageSegment", ":", "return", "open_image", "(", "fn", ",", "div", "=", "div", ",",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
open_mask_rle
Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`.
fastai/vision/image.py
def open_mask_rle(mask_rle:str, shape:Tuple[int, int])->ImageSegment: "Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`." x = FloatTensor(rle_decode(str(mask_rle), shape).astype(np.uint8)) x = x.view(shape[1], shape[0], -1) return ImageSegment(x.permu...
def open_mask_rle(mask_rle:str, shape:Tuple[int, int])->ImageSegment: "Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`." x = FloatTensor(rle_decode(str(mask_rle), shape).astype(np.uint8)) x = x.view(shape[1], shape[0], -1) return ImageSegment(x.permu...
[ "Return", "ImageSegment", "object", "create", "from", "run", "-", "length", "encoded", "string", "in", "mask_lre", "with", "size", "in", "shape", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L403-L407
[ "def", "open_mask_rle", "(", "mask_rle", ":", "str", ",", "shape", ":", "Tuple", "[", "int", ",", "int", "]", ")", "->", "ImageSegment", ":", "x", "=", "FloatTensor", "(", "rle_decode", "(", "str", "(", "mask_rle", ")", ",", "shape", ")", ".", "astyp...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
rle_encode
Return run-length encoding string from `img`.
fastai/vision/image.py
def rle_encode(img:NPArrayMask)->str: "Return run-length encoding string from `img`." pixels = np.concatenate([[0], img.flatten() , [0]]) runs = np.where(pixels[1:] != pixels[:-1])[0] + 1 runs[1::2] -= runs[::2] return ' '.join(str(x) for x in runs)
def rle_encode(img:NPArrayMask)->str: "Return run-length encoding string from `img`." pixels = np.concatenate([[0], img.flatten() , [0]]) runs = np.where(pixels[1:] != pixels[:-1])[0] + 1 runs[1::2] -= runs[::2] return ' '.join(str(x) for x in runs)
[ "Return", "run", "-", "length", "encoding", "string", "from", "img", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L409-L414
[ "def", "rle_encode", "(", "img", ":", "NPArrayMask", ")", "->", "str", ":", "pixels", "=", "np", ".", "concatenate", "(", "[", "[", "0", "]", ",", "img", ".", "flatten", "(", ")", ",", "[", "0", "]", "]", ")", "runs", "=", "np", ".", "where", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
rle_decode
Return an image array from run-length encoded string `mask_rle` with `shape`.
fastai/vision/image.py
def rle_decode(mask_rle:str, shape:Tuple[int,int])->NPArrayMask: "Return an image array from run-length encoded string `mask_rle` with `shape`." s = mask_rle.split() starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])] starts -= 1 ends = starts + lengths img = np.zeros(...
def rle_decode(mask_rle:str, shape:Tuple[int,int])->NPArrayMask: "Return an image array from run-length encoded string `mask_rle` with `shape`." s = mask_rle.split() starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])] starts -= 1 ends = starts + lengths img = np.zeros(...
[ "Return", "an", "image", "array", "from", "run", "-", "length", "encoded", "string", "mask_rle", "with", "shape", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L416-L424
[ "def", "rle_decode", "(", "mask_rle", ":", "str", ",", "shape", ":", "Tuple", "[", "int", ",", "int", "]", ")", "->", "NPArrayMask", ":", "s", "=", "mask_rle", ".", "split", "(", ")", "starts", ",", "lengths", "=", "[", "np", ".", "asarray", "(", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
show_image
Display `Image` in notebook.
fastai/vision/image.py
def show_image(img:Image, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True, cmap:str='binary', alpha:float=None, **kwargs)->plt.Axes: "Display `Image` in notebook." if ax is None: fig,ax = plt.subplots(figsize=figsize) ax.imshow(image2np(img.data), cmap=cmap, alpha=alpha, **kwargs)...
def show_image(img:Image, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True, cmap:str='binary', alpha:float=None, **kwargs)->plt.Axes: "Display `Image` in notebook." if ax is None: fig,ax = plt.subplots(figsize=figsize) ax.imshow(image2np(img.data), cmap=cmap, alpha=alpha, **kwargs)...
[ "Display", "Image", "in", "notebook", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L426-L432
[ "def", "show_image", "(", "img", ":", "Image", ",", "ax", ":", "plt", ".", "Axes", "=", "None", ",", "figsize", ":", "tuple", "=", "(", "3", ",", "3", ")", ",", "hide_axis", ":", "bool", "=", "True", ",", "cmap", ":", "str", "=", "'binary'", ",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
scale_flow
Scale the coords in `flow` to -1/1 or the image size depending on `to_unit`.
fastai/vision/image.py
def scale_flow(flow, to_unit=True): "Scale the coords in `flow` to -1/1 or the image size depending on `to_unit`." s = tensor([flow.size[0]/2,flow.size[1]/2])[None] if to_unit: flow.flow = flow.flow/s-1 else: flow.flow = (flow.flow+1)*s return flow
def scale_flow(flow, to_unit=True): "Scale the coords in `flow` to -1/1 or the image size depending on `to_unit`." s = tensor([flow.size[0]/2,flow.size[1]/2])[None] if to_unit: flow.flow = flow.flow/s-1 else: flow.flow = (flow.flow+1)*s return flow
[ "Scale", "the", "coords", "in", "flow", "to", "-", "1", "/", "1", "or", "the", "image", "size", "depending", "on", "to_unit", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L434-L439
[ "def", "scale_flow", "(", "flow", ",", "to_unit", "=", "True", ")", ":", "s", "=", "tensor", "(", "[", "flow", ".", "size", "[", "0", "]", "/", "2", ",", "flow", ".", "size", "[", "1", "]", "/", "2", "]", ")", "[", "None", "]", "if", "to_un...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
_grid_sample
Resample pixels in `coords` from `x` by `mode`, with `padding_mode` in ('reflection','border','zeros').
fastai/vision/image.py
def _grid_sample(x:TensorImage, coords:FlowField, mode:str='bilinear', padding_mode:str='reflection', remove_out:bool=True)->TensorImage: "Resample pixels in `coords` from `x` by `mode`, with `padding_mode` in ('reflection','border','zeros')." coords = coords.flow.permute(0, 3, 1, 2).contiguous().permute(0, 2, ...
def _grid_sample(x:TensorImage, coords:FlowField, mode:str='bilinear', padding_mode:str='reflection', remove_out:bool=True)->TensorImage: "Resample pixels in `coords` from `x` by `mode`, with `padding_mode` in ('reflection','border','zeros')." coords = coords.flow.permute(0, 3, 1, 2).contiguous().permute(0, 2, ...
[ "Resample", "pixels", "in", "coords", "from", "x", "by", "mode", "with", "padding_mode", "in", "(", "reflection", "border", "zeros", ")", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L524-L535
[ "def", "_grid_sample", "(", "x", ":", "TensorImage", ",", "coords", ":", "FlowField", ",", "mode", ":", "str", "=", "'bilinear'", ",", "padding_mode", ":", "str", "=", "'reflection'", ",", "remove_out", ":", "bool", "=", "True", ")", "->", "TensorImage", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
_affine_mult
Multiply `c` by `m` - can adjust for rectangular shaped `c`.
fastai/vision/image.py
def _affine_mult(c:FlowField,m:AffineMatrix)->FlowField: "Multiply `c` by `m` - can adjust for rectangular shaped `c`." if m is None: return c size = c.flow.size() h,w = c.size m[0,1] *= h/w m[1,0] *= w/h c.flow = c.flow.view(-1,2) c.flow = torch.addmm(m[:2,2], c.flow, m[:2,:2].t()).vie...
def _affine_mult(c:FlowField,m:AffineMatrix)->FlowField: "Multiply `c` by `m` - can adjust for rectangular shaped `c`." if m is None: return c size = c.flow.size() h,w = c.size m[0,1] *= h/w m[1,0] *= w/h c.flow = c.flow.view(-1,2) c.flow = torch.addmm(m[:2,2], c.flow, m[:2,:2].t()).vie...
[ "Multiply", "c", "by", "m", "-", "can", "adjust", "for", "rectangular", "shaped", "c", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L547-L556
[ "def", "_affine_mult", "(", "c", ":", "FlowField", ",", "m", ":", "AffineMatrix", ")", "->", "FlowField", ":", "if", "m", "is", "None", ":", "return", "c", "size", "=", "c", ".", "flow", ".", "size", "(", ")", "h", ",", "w", "=", "c", ".", "siz...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
_affine_inv_mult
Applies the inverse affine transform described in `m` to `c`.
fastai/vision/image.py
def _affine_inv_mult(c, m): "Applies the inverse affine transform described in `m` to `c`." size = c.flow.size() h,w = c.size m[0,1] *= h/w m[1,0] *= w/h c.flow = c.flow.view(-1,2) a = torch.inverse(m[:2,:2].t()) c.flow = torch.mm(c.flow - m[:2,2], a).view(size) return c
def _affine_inv_mult(c, m): "Applies the inverse affine transform described in `m` to `c`." size = c.flow.size() h,w = c.size m[0,1] *= h/w m[1,0] *= w/h c.flow = c.flow.view(-1,2) a = torch.inverse(m[:2,:2].t()) c.flow = torch.mm(c.flow - m[:2,2], a).view(size) return c
[ "Applies", "the", "inverse", "affine", "transform", "described", "in", "m", "to", "c", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L558-L567
[ "def", "_affine_inv_mult", "(", "c", ",", "m", ")", ":", "size", "=", "c", ".", "flow", ".", "size", "(", ")", "h", ",", "w", "=", "c", ".", "size", "m", "[", "0", ",", "1", "]", "*=", "h", "/", "w", "m", "[", "1", ",", "0", "]", "*=", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
_round_multiple
Calc `x` to nearest multiple of `mult`.
fastai/vision/image.py
def _round_multiple(x:int, mult:int=None)->int: "Calc `x` to nearest multiple of `mult`." return (int(x/mult+0.5)*mult) if mult is not None else x
def _round_multiple(x:int, mult:int=None)->int: "Calc `x` to nearest multiple of `mult`." return (int(x/mult+0.5)*mult) if mult is not None else x
[ "Calc", "x", "to", "nearest", "multiple", "of", "mult", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L585-L587
[ "def", "_round_multiple", "(", "x", ":", "int", ",", "mult", ":", "int", "=", "None", ")", "->", "int", ":", "return", "(", "int", "(", "x", "/", "mult", "+", "0.5", ")", "*", "mult", ")", "if", "mult", "is", "not", "None", "else", "x" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
_get_crop_target
Calc crop shape of `target_px` to nearest multiple of `mult`.
fastai/vision/image.py
def _get_crop_target(target_px:Union[int,TensorImageSize], mult:int=None)->Tuple[int,int]: "Calc crop shape of `target_px` to nearest multiple of `mult`." target_r,target_c = tis2hw(target_px) return _round_multiple(target_r,mult),_round_multiple(target_c,mult)
def _get_crop_target(target_px:Union[int,TensorImageSize], mult:int=None)->Tuple[int,int]: "Calc crop shape of `target_px` to nearest multiple of `mult`." target_r,target_c = tis2hw(target_px) return _round_multiple(target_r,mult),_round_multiple(target_c,mult)
[ "Calc", "crop", "shape", "of", "target_px", "to", "nearest", "multiple", "of", "mult", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L589-L592
[ "def", "_get_crop_target", "(", "target_px", ":", "Union", "[", "int", ",", "TensorImageSize", "]", ",", "mult", ":", "int", "=", "None", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "target_r", ",", "target_c", "=", "tis2hw", "(", "target_px"...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
_get_resize_target
Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`.
fastai/vision/image.py
def _get_resize_target(img, crop_target, do_crop=False)->TensorImageSize: "Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`." if crop_target is None: return None ch,r,c = img.shape target_r,target_c = crop_target ratio = (min if do_crop else max)(r/target_r, c/target_c) ret...
def _get_resize_target(img, crop_target, do_crop=False)->TensorImageSize: "Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`." if crop_target is None: return None ch,r,c = img.shape target_r,target_c = crop_target ratio = (min if do_crop else max)(r/target_r, c/target_c) ret...
[ "Calc", "size", "of", "img", "to", "fit", "in", "crop_target", "-", "adjust", "based", "on", "do_crop", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L594-L600
[ "def", "_get_resize_target", "(", "img", ",", "crop_target", ",", "do_crop", "=", "False", ")", "->", "TensorImageSize", ":", "if", "crop_target", "is", "None", ":", "return", "None", "ch", ",", "r", ",", "c", "=", "img", ".", "shape", "target_r", ",", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
plot_flat
Shortcut for `enumerate(subplots.flatten())`
fastai/vision/image.py
def plot_flat(r, c, figsize): "Shortcut for `enumerate(subplots.flatten())`" return enumerate(plt.subplots(r, c, figsize=figsize)[1].flatten())
def plot_flat(r, c, figsize): "Shortcut for `enumerate(subplots.flatten())`" return enumerate(plt.subplots(r, c, figsize=figsize)[1].flatten())
[ "Shortcut", "for", "enumerate", "(", "subplots", ".", "flatten", "()", ")" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L602-L604
[ "def", "plot_flat", "(", "r", ",", "c", ",", "figsize", ")", ":", "return", "enumerate", "(", "plt", ".", "subplots", "(", "r", ",", "c", ",", "figsize", "=", "figsize", ")", "[", "1", "]", ".", "flatten", "(", ")", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
plot_multi
Call `func` for every combination of `r,c` on a subplot
fastai/vision/image.py
def plot_multi(func:Callable[[int,int,plt.Axes],None], r:int=1, c:int=1, figsize:Tuple=(12,6)): "Call `func` for every combination of `r,c` on a subplot" axes = plt.subplots(r, c, figsize=figsize)[1] for i in range(r): for j in range(c): func(i,j,axes[i,j])
def plot_multi(func:Callable[[int,int,plt.Axes],None], r:int=1, c:int=1, figsize:Tuple=(12,6)): "Call `func` for every combination of `r,c` on a subplot" axes = plt.subplots(r, c, figsize=figsize)[1] for i in range(r): for j in range(c): func(i,j,axes[i,j])
[ "Call", "func", "for", "every", "combination", "of", "r", "c", "on", "a", "subplot" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L606-L610
[ "def", "plot_multi", "(", "func", ":", "Callable", "[", "[", "int", ",", "int", ",", "plt", ".", "Axes", "]", ",", "None", "]", ",", "r", ":", "int", "=", "1", ",", "c", ":", "int", "=", "1", ",", "figsize", ":", "Tuple", "=", "(", "12", ",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
show_multi
Call `func(i,j).show(ax)` for every combination of `r,c`
fastai/vision/image.py
def show_multi(func:Callable[[int,int],Image], r:int=1, c:int=1, figsize:Tuple=(9,9)): "Call `func(i,j).show(ax)` for every combination of `r,c`" plot_multi(lambda i,j,ax: func(i,j).show(ax), r, c, figsize=figsize)
def show_multi(func:Callable[[int,int],Image], r:int=1, c:int=1, figsize:Tuple=(9,9)): "Call `func(i,j).show(ax)` for every combination of `r,c`" plot_multi(lambda i,j,ax: func(i,j).show(ax), r, c, figsize=figsize)
[ "Call", "func", "(", "i", "j", ")", ".", "show", "(", "ax", ")", "for", "every", "combination", "of", "r", "c" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L612-L614
[ "def", "show_multi", "(", "func", ":", "Callable", "[", "[", "int", ",", "int", "]", ",", "Image", "]", ",", "r", ":", "int", "=", "1", ",", "c", ":", "int", "=", "1", ",", "figsize", ":", "Tuple", "=", "(", "9", ",", "9", ")", ")", ":", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
show_all
Show all `imgs` using `r` rows
fastai/vision/image.py
def show_all(imgs:Collection[Image], r:int=1, c:Optional[int]=None, figsize=(12,6)): "Show all `imgs` using `r` rows" imgs = listify(imgs) if c is None: c = len(imgs)//r for i,ax in plot_flat(r,c,figsize): imgs[i].show(ax)
def show_all(imgs:Collection[Image], r:int=1, c:Optional[int]=None, figsize=(12,6)): "Show all `imgs` using `r` rows" imgs = listify(imgs) if c is None: c = len(imgs)//r for i,ax in plot_flat(r,c,figsize): imgs[i].show(ax)
[ "Show", "all", "imgs", "using", "r", "rows" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L616-L620
[ "def", "show_all", "(", "imgs", ":", "Collection", "[", "Image", "]", ",", "r", ":", "int", "=", "1", ",", "c", ":", "Optional", "[", "int", "]", "=", "None", ",", "figsize", "=", "(", "12", ",", "6", ")", ")", ":", "imgs", "=", "listify", "(...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.apply_tfms
Apply all `tfms` to the `Image`, if `do_resolve` picks value for random args.
fastai/vision/image.py
def apply_tfms(self, tfms:TfmList, do_resolve:bool=True, xtra:Optional[Dict[Callable,dict]]=None, size:Optional[Union[int,TensorImageSize]]=None, resize_method:ResizeMethod=None, mult:int=None, padding_mode:str='reflection', mode:str='bilinear', remove_out:bool=True)->TensorImage: ...
def apply_tfms(self, tfms:TfmList, do_resolve:bool=True, xtra:Optional[Dict[Callable,dict]]=None, size:Optional[Union[int,TensorImageSize]]=None, resize_method:ResizeMethod=None, mult:int=None, padding_mode:str='reflection', mode:str='bilinear', remove_out:bool=True)->TensorImage: ...
[ "Apply", "all", "tfms", "to", "the", "Image", "if", "do_resolve", "picks", "value", "for", "random", "args", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L96-L124
[ "def", "apply_tfms", "(", "self", ",", "tfms", ":", "TfmList", ",", "do_resolve", ":", "bool", "=", "True", ",", "xtra", ":", "Optional", "[", "Dict", "[", "Callable", ",", "dict", "]", "]", "=", "None", ",", "size", ":", "Optional", "[", "Union", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.refresh
Apply any logit, flow, or affine transfers that have been sent to the `Image`.
fastai/vision/image.py
def refresh(self)->None: "Apply any logit, flow, or affine transfers that have been sent to the `Image`." if self._logit_px is not None: self._px = self._logit_px.sigmoid_() self._logit_px = None if self._affine_mat is not None or self._flow is not None: self....
def refresh(self)->None: "Apply any logit, flow, or affine transfers that have been sent to the `Image`." if self._logit_px is not None: self._px = self._logit_px.sigmoid_() self._logit_px = None if self._affine_mat is not None or self._flow is not None: self....
[ "Apply", "any", "logit", "flow", "or", "affine", "transfers", "that", "have", "been", "sent", "to", "the", "Image", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L126-L135
[ "def", "refresh", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_logit_px", "is", "not", "None", ":", "self", ".", "_px", "=", "self", ".", "_logit_px", ".", "sigmoid_", "(", ")", "self", ".", "_logit_px", "=", "None", "if", "self", ".",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.save
Save the image to `fn`.
fastai/vision/image.py
def save(self, fn:PathOrStr): "Save the image to `fn`." x = image2np(self.data*255).astype(np.uint8) PIL.Image.fromarray(x).save(fn)
def save(self, fn:PathOrStr): "Save the image to `fn`." x = image2np(self.data*255).astype(np.uint8) PIL.Image.fromarray(x).save(fn)
[ "Save", "the", "image", "to", "fn", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L137-L140
[ "def", "save", "(", "self", ",", "fn", ":", "PathOrStr", ")", ":", "x", "=", "image2np", "(", "self", ".", "data", "*", "255", ")", ".", "astype", "(", "np", ".", "uint8", ")", "PIL", ".", "Image", ".", "fromarray", "(", "x", ")", ".", "save", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.flow
Access the flow-field grid after applying queued affine transforms.
fastai/vision/image.py
def flow(self)->FlowField: "Access the flow-field grid after applying queued affine transforms." if self._flow is None: self._flow = _affine_grid(self.shape) if self._affine_mat is not None: self._flow = _affine_mult(self._flow,self._affine_mat) self._affine_m...
def flow(self)->FlowField: "Access the flow-field grid after applying queued affine transforms." if self._flow is None: self._flow = _affine_grid(self.shape) if self._affine_mat is not None: self._flow = _affine_mult(self._flow,self._affine_mat) self._affine_m...
[ "Access", "the", "flow", "-", "field", "grid", "after", "applying", "queued", "affine", "transforms", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L153-L160
[ "def", "flow", "(", "self", ")", "->", "FlowField", ":", "if", "self", ".", "_flow", "is", "None", ":", "self", ".", "_flow", "=", "_affine_grid", "(", "self", ".", "shape", ")", "if", "self", ".", "_affine_mat", "is", "not", "None", ":", "self", "...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.lighting
Equivalent to `image = sigmoid(func(logit(image)))`.
fastai/vision/image.py
def lighting(self, func:LightingFunc, *args:Any, **kwargs:Any): "Equivalent to `image = sigmoid(func(logit(image)))`." self.logit_px = func(self.logit_px, *args, **kwargs) return self
def lighting(self, func:LightingFunc, *args:Any, **kwargs:Any): "Equivalent to `image = sigmoid(func(logit(image)))`." self.logit_px = func(self.logit_px, *args, **kwargs) return self
[ "Equivalent", "to", "image", "=", "sigmoid", "(", "func", "(", "logit", "(", "image", ")))", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L165-L168
[ "def", "lighting", "(", "self", ",", "func", ":", "LightingFunc", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", ":", "self", ".", "logit_px", "=", "func", "(", "self", ".", "logit_px", ",", "*", "args", ",", "*", "*", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.pixel
Equivalent to `image.px = func(image.px)`.
fastai/vision/image.py
def pixel(self, func:PixelFunc, *args, **kwargs)->'Image': "Equivalent to `image.px = func(image.px)`." self.px = func(self.px, *args, **kwargs) return self
def pixel(self, func:PixelFunc, *args, **kwargs)->'Image': "Equivalent to `image.px = func(image.px)`." self.px = func(self.px, *args, **kwargs) return self
[ "Equivalent", "to", "image", ".", "px", "=", "func", "(", "image", ".", "px", ")", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L170-L173
[ "def", "pixel", "(", "self", ",", "func", ":", "PixelFunc", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "'Image'", ":", "self", ".", "px", "=", "func", "(", "self", ".", "px", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.coord
Equivalent to `image.flow = func(image.flow, image.size)`.
fastai/vision/image.py
def coord(self, func:CoordFunc, *args, **kwargs)->'Image': "Equivalent to `image.flow = func(image.flow, image.size)`." self.flow = func(self.flow, *args, **kwargs) return self
def coord(self, func:CoordFunc, *args, **kwargs)->'Image': "Equivalent to `image.flow = func(image.flow, image.size)`." self.flow = func(self.flow, *args, **kwargs) return self
[ "Equivalent", "to", "image", ".", "flow", "=", "func", "(", "image", ".", "flow", "image", ".", "size", ")", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L175-L178
[ "def", "coord", "(", "self", ",", "func", ":", "CoordFunc", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "'Image'", ":", "self", ".", "flow", "=", "func", "(", "self", ".", "flow", ",", "*", "args", ",", "*", "*", "kwargs", ")", "retur...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.affine
Equivalent to `image.affine_mat = image.affine_mat @ func()`.
fastai/vision/image.py
def affine(self, func:AffineFunc, *args, **kwargs)->'Image': "Equivalent to `image.affine_mat = image.affine_mat @ func()`." m = tensor(func(*args, **kwargs)).to(self.device) self.affine_mat = self.affine_mat @ m return self
def affine(self, func:AffineFunc, *args, **kwargs)->'Image': "Equivalent to `image.affine_mat = image.affine_mat @ func()`." m = tensor(func(*args, **kwargs)).to(self.device) self.affine_mat = self.affine_mat @ m return self
[ "Equivalent", "to", "image", ".", "affine_mat", "=", "image", ".", "affine_mat" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L180-L184
[ "def", "affine", "(", "self", ",", "func", ":", "AffineFunc", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "'Image'", ":", "m", "=", "tensor", "(", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", ".", "to", "(", "self", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.resize
Resize the image to `size`, size can be a single int.
fastai/vision/image.py
def resize(self, size:Union[int,TensorImageSize])->'Image': "Resize the image to `size`, size can be a single int." assert self._flow is None if isinstance(size, int): size=(self.shape[0], size, size) if tuple(size)==tuple(self.shape): return self self.flow = _affine_grid(size) ...
def resize(self, size:Union[int,TensorImageSize])->'Image': "Resize the image to `size`, size can be a single int." assert self._flow is None if isinstance(size, int): size=(self.shape[0], size, size) if tuple(size)==tuple(self.shape): return self self.flow = _affine_grid(size) ...
[ "Resize", "the", "image", "to", "size", "size", "can", "be", "a", "single", "int", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L186-L192
[ "def", "resize", "(", "self", ",", "size", ":", "Union", "[", "int", ",", "TensorImageSize", "]", ")", "->", "'Image'", ":", "assert", "self", ".", "_flow", "is", "None", "if", "isinstance", "(", "size", ",", "int", ")", ":", "size", "=", "(", "sel...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.affine_mat
Get the affine matrix that will be applied by `refresh`.
fastai/vision/image.py
def affine_mat(self)->AffineMatrix: "Get the affine matrix that will be applied by `refresh`." if self._affine_mat is None: self._affine_mat = torch.eye(3).to(self.device) return self._affine_mat
def affine_mat(self)->AffineMatrix: "Get the affine matrix that will be applied by `refresh`." if self._affine_mat is None: self._affine_mat = torch.eye(3).to(self.device) return self._affine_mat
[ "Get", "the", "affine", "matrix", "that", "will", "be", "applied", "by", "refresh", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L195-L199
[ "def", "affine_mat", "(", "self", ")", "->", "AffineMatrix", ":", "if", "self", ".", "_affine_mat", "is", "None", ":", "self", ".", "_affine_mat", "=", "torch", ".", "eye", "(", "3", ")", ".", "to", "(", "self", ".", "device", ")", "return", "self", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.logit_px
Get logit(image.px).
fastai/vision/image.py
def logit_px(self)->LogitTensorImage: "Get logit(image.px)." if self._logit_px is None: self._logit_px = logit_(self.px) return self._logit_px
def logit_px(self)->LogitTensorImage: "Get logit(image.px)." if self._logit_px is None: self._logit_px = logit_(self.px) return self._logit_px
[ "Get", "logit", "(", "image", ".", "px", ")", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L204-L207
[ "def", "logit_px", "(", "self", ")", "->", "LogitTensorImage", ":", "if", "self", ".", "_logit_px", "is", "None", ":", "self", ".", "_logit_px", "=", "logit_", "(", "self", ".", "px", ")", "return", "self", ".", "_logit_px" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Image.show
Show image on `ax` with `title`, using `cmap` if single-channel, overlaid with optional `y`
fastai/vision/image.py
def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, cmap:str=None, y:Any=None, **kwargs): "Show image on `ax` with `title`, using `cmap` if single-channel, overlaid with optional `y`" cmap = ifnone(cmap, defaults.cmap) ax = show_imag...
def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, cmap:str=None, y:Any=None, **kwargs): "Show image on `ax` with `title`, using `cmap` if single-channel, overlaid with optional `y`" cmap = ifnone(cmap, defaults.cmap) ax = show_imag...
[ "Show", "image", "on", "ax", "with", "title", "using", "cmap", "if", "single", "-", "channel", "overlaid", "with", "optional", "y" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L216-L222
[ "def", "show", "(", "self", ",", "ax", ":", "plt", ".", "Axes", "=", "None", ",", "figsize", ":", "tuple", "=", "(", "3", ",", "3", ")", ",", "title", ":", "Optional", "[", "str", "]", "=", "None", ",", "hide_axis", ":", "bool", "=", "True", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageSegment.show
Show the `ImageSegment` on `ax`.
fastai/vision/image.py
def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, cmap:str='tab20', alpha:float=0.5, **kwargs): "Show the `ImageSegment` on `ax`." ax = show_image(self, ax=ax, hide_axis=hide_axis, cmap=cmap, figsize=figsize, interpolatio...
def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, cmap:str='tab20', alpha:float=0.5, **kwargs): "Show the `ImageSegment` on `ax`." ax = show_image(self, ax=ax, hide_axis=hide_axis, cmap=cmap, figsize=figsize, interpolatio...
[ "Show", "the", "ImageSegment", "on", "ax", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L237-L242
[ "def", "show", "(", "self", ",", "ax", ":", "plt", ".", "Axes", "=", "None", ",", "figsize", ":", "tuple", "=", "(", "3", ",", "3", ")", ",", "title", ":", "Optional", "[", "str", "]", "=", "None", ",", "hide_axis", ":", "bool", "=", "True", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImagePoints.clone
Mimic the behavior of torch.clone for `ImagePoints` objects.
fastai/vision/image.py
def clone(self): "Mimic the behavior of torch.clone for `ImagePoints` objects." return self.__class__(FlowField(self.size, self.flow.flow.clone()), scale=False, y_first=False)
def clone(self): "Mimic the behavior of torch.clone for `ImagePoints` objects." return self.__class__(FlowField(self.size, self.flow.flow.clone()), scale=False, y_first=False)
[ "Mimic", "the", "behavior", "of", "torch", ".", "clone", "for", "ImagePoints", "objects", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L258-L260
[ "def", "clone", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "FlowField", "(", "self", ".", "size", ",", "self", ".", "flow", ".", "flow", ".", "clone", "(", ")", ")", ",", "scale", "=", "False", ",", "y_first", "=", "False", "...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImagePoints.flow
Access the flow-field grid after applying queued affine and coord transforms.
fastai/vision/image.py
def flow(self)->FlowField: "Access the flow-field grid after applying queued affine and coord transforms." if self._affine_mat is not None: self._flow = _affine_inv_mult(self._flow, self._affine_mat) self._affine_mat = None self.transformed = True if len(self....
def flow(self)->FlowField: "Access the flow-field grid after applying queued affine and coord transforms." if self._affine_mat is not None: self._flow = _affine_inv_mult(self._flow, self._affine_mat) self._affine_mat = None self.transformed = True if len(self....
[ "Access", "the", "flow", "-", "field", "grid", "after", "applying", "queued", "affine", "and", "coord", "transforms", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L275-L285
[ "def", "flow", "(", "self", ")", "->", "FlowField", ":", "if", "self", ".", "_affine_mat", "is", "not", "None", ":", "self", ".", "_flow", "=", "_affine_inv_mult", "(", "self", ".", "_flow", ",", "self", ".", "_affine_mat", ")", "self", ".", "_affine_m...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImagePoints.coord
Put `func` with `args` and `kwargs` in `self.flow_func` for later.
fastai/vision/image.py
def coord(self, func:CoordFunc, *args, **kwargs)->'ImagePoints': "Put `func` with `args` and `kwargs` in `self.flow_func` for later." if 'invert' in kwargs: kwargs['invert'] = True else: warn(f"{func.__name__} isn't implemented for {self.__class__}.") self.flow_func.append(partial(func, ...
def coord(self, func:CoordFunc, *args, **kwargs)->'ImagePoints': "Put `func` with `args` and `kwargs` in `self.flow_func` for later." if 'invert' in kwargs: kwargs['invert'] = True else: warn(f"{func.__name__} isn't implemented for {self.__class__}.") self.flow_func.append(partial(func, ...
[ "Put", "func", "with", "args", "and", "kwargs", "in", "self", ".", "flow_func", "for", "later", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L290-L295
[ "def", "coord", "(", "self", ",", "func", ":", "CoordFunc", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "'ImagePoints'", ":", "if", "'invert'", "in", "kwargs", ":", "kwargs", "[", "'invert'", "]", "=", "True", "else", ":", "warn", "(", "f...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImagePoints.pixel
Equivalent to `self = func_flow(self)`.
fastai/vision/image.py
def pixel(self, func:PixelFunc, *args, **kwargs)->'ImagePoints': "Equivalent to `self = func_flow(self)`." self = func(self, *args, **kwargs) self.transformed=True return self
def pixel(self, func:PixelFunc, *args, **kwargs)->'ImagePoints': "Equivalent to `self = func_flow(self)`." self = func(self, *args, **kwargs) self.transformed=True return self
[ "Equivalent", "to", "self", "=", "func_flow", "(", "self", ")", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L299-L303
[ "def", "pixel", "(", "self", ",", "func", ":", "PixelFunc", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "'ImagePoints'", ":", "self", "=", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "transformed", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImagePoints.resize
Resize the image to `size`, size can be a single int.
fastai/vision/image.py
def resize(self, size:Union[int,TensorImageSize]) -> 'ImagePoints': "Resize the image to `size`, size can be a single int." if isinstance(size, int): size=(1, size, size) self._flow.size = size[1:] return self
def resize(self, size:Union[int,TensorImageSize]) -> 'ImagePoints': "Resize the image to `size`, size can be a single int." if isinstance(size, int): size=(1, size, size) self._flow.size = size[1:] return self
[ "Resize", "the", "image", "to", "size", "size", "can", "be", "a", "single", "int", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L308-L312
[ "def", "resize", "(", "self", ",", "size", ":", "Union", "[", "int", ",", "TensorImageSize", "]", ")", "->", "'ImagePoints'", ":", "if", "isinstance", "(", "size", ",", "int", ")", ":", "size", "=", "(", "1", ",", "size", ",", "size", ")", "self", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImagePoints.data
Return the points associated to this object.
fastai/vision/image.py
def data(self)->Tensor: "Return the points associated to this object." flow = self.flow #This updates flow before we test if some transforms happened if self.transformed: if 'remove_out' not in self.sample_kwargs or self.sample_kwargs['remove_out']: flow = _remove_poi...
def data(self)->Tensor: "Return the points associated to this object." flow = self.flow #This updates flow before we test if some transforms happened if self.transformed: if 'remove_out' not in self.sample_kwargs or self.sample_kwargs['remove_out']: flow = _remove_poi...
[ "Return", "the", "points", "associated", "to", "this", "object", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L315-L322
[ "def", "data", "(", "self", ")", "->", "Tensor", ":", "flow", "=", "self", ".", "flow", "#This updates flow before we test if some transforms happened", "if", "self", ".", "transformed", ":", "if", "'remove_out'", "not", "in", "self", ".", "sample_kwargs", "or", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImagePoints.show
Show the `ImagePoints` on `ax`.
fastai/vision/image.py
def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, **kwargs): "Show the `ImagePoints` on `ax`." if ax is None: _,ax = plt.subplots(figsize=figsize) pnt = scale_flow(FlowField(self.size, self.data), to_unit=False).flow.flip(1) params = {'s...
def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, **kwargs): "Show the `ImagePoints` on `ax`." if ax is None: _,ax = plt.subplots(figsize=figsize) pnt = scale_flow(FlowField(self.size, self.data), to_unit=False).flow.flip(1) params = {'s...
[ "Show", "the", "ImagePoints", "on", "ax", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L324-L331
[ "def", "show", "(", "self", ",", "ax", ":", "plt", ".", "Axes", "=", "None", ",", "figsize", ":", "tuple", "=", "(", "3", ",", "3", ")", ",", "title", ":", "Optional", "[", "str", "]", "=", "None", ",", "hide_axis", ":", "bool", "=", "True", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageBBox.clone
Mimic the behavior of torch.clone for `Image` objects.
fastai/vision/image.py
def clone(self) -> 'ImageBBox': "Mimic the behavior of torch.clone for `Image` objects." flow = FlowField(self.size, self.flow.flow.clone()) return self.__class__(flow, scale=False, y_first=False, labels=self.labels, pad_idx=self.pad_idx)
def clone(self) -> 'ImageBBox': "Mimic the behavior of torch.clone for `Image` objects." flow = FlowField(self.size, self.flow.flow.clone()) return self.__class__(flow, scale=False, y_first=False, labels=self.labels, pad_idx=self.pad_idx)
[ "Mimic", "the", "behavior", "of", "torch", ".", "clone", "for", "Image", "objects", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L343-L346
[ "def", "clone", "(", "self", ")", "->", "'ImageBBox'", ":", "flow", "=", "FlowField", "(", "self", ".", "size", ",", "self", ".", "flow", ".", "flow", ".", "clone", "(", ")", ")", "return", "self", ".", "__class__", "(", "flow", ",", "scale", "=", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageBBox.create
Create an ImageBBox object from `bboxes`.
fastai/vision/image.py
def create(cls, h:int, w:int, bboxes:Collection[Collection[int]], labels:Collection=None, classes:dict=None, pad_idx:int=0, scale:bool=True)->'ImageBBox': "Create an ImageBBox object from `bboxes`." if isinstance(bboxes, np.ndarray) and bboxes.dtype == np.object: bboxes = np.array([bb for...
def create(cls, h:int, w:int, bboxes:Collection[Collection[int]], labels:Collection=None, classes:dict=None, pad_idx:int=0, scale:bool=True)->'ImageBBox': "Create an ImageBBox object from `bboxes`." if isinstance(bboxes, np.ndarray) and bboxes.dtype == np.object: bboxes = np.array([bb for...
[ "Create", "an", "ImageBBox", "object", "from", "bboxes", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L349-L358
[ "def", "create", "(", "cls", ",", "h", ":", "int", ",", "w", ":", "int", ",", "bboxes", ":", "Collection", "[", "Collection", "[", "int", "]", "]", ",", "labels", ":", "Collection", "=", "None", ",", "classes", ":", "dict", "=", "None", ",", "pad...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageBBox.show
Show the `ImageBBox` on `ax`.
fastai/vision/image.py
def show(self, y:Image=None, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, color:str='white', **kwargs): "Show the `ImageBBox` on `ax`." if ax is None: _,ax = plt.subplots(figsize=figsize) bboxes, lbls = self._compute_boxes() h,w = self.flo...
def show(self, y:Image=None, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, color:str='white', **kwargs): "Show the `ImageBBox` on `ax`." if ax is None: _,ax = plt.subplots(figsize=figsize) bboxes, lbls = self._compute_boxes() h,w = self.flo...
[ "Show", "the", "ImageBBox", "on", "ax", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L376-L386
[ "def", "show", "(", "self", ",", "y", ":", "Image", "=", "None", ",", "ax", ":", "plt", ".", "Axes", "=", "None", ",", "figsize", ":", "tuple", "=", "(", "3", ",", "3", ")", ",", "title", ":", "Optional", "[", "str", "]", "=", "None", ",", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Transform.calc
Apply to image `x`, wrapping it if necessary.
fastai/vision/image.py
def calc(self, x:Image, *args:Any, **kwargs:Any)->Image: "Apply to image `x`, wrapping it if necessary." if self._wrap: return getattr(x, self._wrap)(self.func, *args, **kwargs) else: return self.func(x, *args, **kwargs)
def calc(self, x:Image, *args:Any, **kwargs:Any)->Image: "Apply to image `x`, wrapping it if necessary." if self._wrap: return getattr(x, self._wrap)(self.func, *args, **kwargs) else: return self.func(x, *args, **kwargs)
[ "Apply", "to", "image", "x", "wrapping", "it", "if", "necessary", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L467-L470
[ "def", "calc", "(", "self", ",", "x", ":", "Image", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Image", ":", "if", "self", ".", "_wrap", ":", "return", "getattr", "(", "x", ",", "self", ".", "_wrap", ")", "(...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
url2path
Change `url` to a path.
fastai/datasets.py
def url2path(url, data=True, ext:str='.tgz'): "Change `url` to a path." name = url2name(url) return datapath4file(name, ext=ext, archive=False) if data else modelpath4file(name, ext=ext)
def url2path(url, data=True, ext:str='.tgz'): "Change `url` to a path." name = url2name(url) return datapath4file(name, ext=ext, archive=False) if data else modelpath4file(name, ext=ext)
[ "Change", "url", "to", "a", "path", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L186-L189
[ "def", "url2path", "(", "url", ",", "data", "=", "True", ",", "ext", ":", "str", "=", "'.tgz'", ")", ":", "name", "=", "url2name", "(", "url", ")", "return", "datapath4file", "(", "name", ",", "ext", "=", "ext", ",", "archive", "=", "False", ")", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
modelpath4file
Return model path to `filename`, checking locally first then in the config file.
fastai/datasets.py
def modelpath4file(filename, ext:str='.tgz'): "Return model path to `filename`, checking locally first then in the config file." local_path = URLs.LOCAL_PATH/'models'/filename if local_path.exists() or local_path.with_suffix(ext).exists(): return local_path else: return Config.model_path()/filename
def modelpath4file(filename, ext:str='.tgz'): "Return model path to `filename`, checking locally first then in the config file." local_path = URLs.LOCAL_PATH/'models'/filename if local_path.exists() or local_path.with_suffix(ext).exists(): return local_path else: return Config.model_path()/filename
[ "Return", "model", "path", "to", "filename", "checking", "locally", "first", "then", "in", "the", "config", "file", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L193-L197
[ "def", "modelpath4file", "(", "filename", ",", "ext", ":", "str", "=", "'.tgz'", ")", ":", "local_path", "=", "URLs", ".", "LOCAL_PATH", "/", "'models'", "/", "filename", "if", "local_path", ".", "exists", "(", ")", "or", "local_path", ".", "with_suffix", ...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
datapath4file
Return data path to `filename`, checking locally first then in the config file.
fastai/datasets.py
def datapath4file(filename, ext:str='.tgz', archive=True): "Return data path to `filename`, checking locally first then in the config file." local_path = URLs.LOCAL_PATH/'data'/filename if local_path.exists() or local_path.with_suffix(ext).exists(): return local_path elif archive: return Config.data_arc...
def datapath4file(filename, ext:str='.tgz', archive=True): "Return data path to `filename`, checking locally first then in the config file." local_path = URLs.LOCAL_PATH/'data'/filename if local_path.exists() or local_path.with_suffix(ext).exists(): return local_path elif archive: return Config.data_arc...
[ "Return", "data", "path", "to", "filename", "checking", "locally", "first", "then", "in", "the", "config", "file", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L199-L204
[ "def", "datapath4file", "(", "filename", ",", "ext", ":", "str", "=", "'.tgz'", ",", "archive", "=", "True", ")", ":", "local_path", "=", "URLs", ".", "LOCAL_PATH", "/", "'data'", "/", "filename", "if", "local_path", ".", "exists", "(", ")", "or", "loc...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67