INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Subclass this method if you want to customize the way this ItemBase is shown on ax. | def show(self, ax:plt.Axes, **kwargs):
"Subclass this method if you want to customize the way this `ItemBase` is shown on `ax`."
ax.set_title(str(self)) |
Init layer parameters. | def init_params(net):
'''Init layer parameters.'''
for m in net.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal(m.weight, mode='fan_out')
if m.bias:
init.constant(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
init.constant(m.weight... |
Create a seuence Conv2d - > BatchNorm2d - > LeakyReLu layer. | def conv_bn_lrelu(ni:int, nf:int, ks:int=3, stride:int=1)->nn.Sequential:
"Create a seuence Conv2d->BatchNorm2d->LeakyReLu layer."
return nn.Sequential(
nn.Conv2d(ni, nf, kernel_size=ks, bias=False, stride=stride, padding=ks//2),
nn.BatchNorm2d(nf),
nn.LeakyReLU(negative_slope=0.1, inpla... |
starts with conv layer - ch_in channels in - then has num_blocks ResLayer | def make_group_layer(self, ch_in:int, num_blocks:int, stride:int=1):
"starts with conv layer - `ch_in` channels in - then has `num_blocks` `ResLayer`"
return [conv_bn_lrelu(ch_in, ch_in*2,stride=stride)
] + [(ResLayer(ch_in*2)) for i in range(num_blocks)] |
Create a Learner for collaborative filtering on data. | def collab_learner(data, n_factors:int=None, use_nn:bool=False, emb_szs:Dict[str,int]=None, layers:Collection[int]=None,
ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True,
bn_final:bool=False, **learn_kwargs)->Learner:
"Create a Learner for... |
Create a DataBunch suitable for collaborative filtering from ratings. | def from_df(cls, ratings:DataFrame, valid_pct:float=0.2, user_name:Optional[str]=None, item_name:Optional[str]=None,
rating_name:Optional[str]=None, test:DataFrame=None, seed:int=None, path:PathOrStr='.', bs:int=64,
val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collec... |
Fetch item or user ( based on is_item ) for all in arr. ( Set model to cpu and no grad. ) | def get_idx(self, arr:Collection, is_item:bool=True):
"Fetch item or user (based on `is_item`) for all in `arr`. (Set model to `cpu` and no grad.)"
m = self.model.eval().cpu()
requires_grad(m,False)
u_class,i_class = self.data.train_ds.x.classes.values()
classes = i_class if is_i... |
Bias for item or user ( based on is_item ) for all in arr. ( Set model to cpu and no grad. ) | def bias(self, arr:Collection, is_item:bool=True):
"Bias for item or user (based on `is_item`) for all in `arr`. (Set model to `cpu` and no grad.)"
idx = self.get_idx(arr, is_item)
m = self.model
layer = m.i_bias if is_item else m.u_bias
return layer(idx).squeeze() |
Bias for item or user ( based on is_item ) for all in arr. ( Set model to cpu and no grad. ) | def weight(self, arr:Collection, is_item:bool=True):
"Bias for item or user (based on `is_item`) for all in `arr`. (Set model to `cpu` and no grad.)"
idx = self.get_idx(arr, is_item)
m = self.model
layer = m.i_weight if is_item else m.u_weight
return layer(idx) |
Draws a representation of a random forest in IPython. Parameters: ----------- t: The tree you wish to draw df: The data used to train the tree. This is used to get the names of the features. | def draw_tree(t, df, size=10, ratio=0.6, precision=0):
""" Draws a representation of a random forest in IPython.
Parameters:
-----------
t: The tree you wish to draw
df: The data used to train the tree. This is used to get the names of the features.
"""
s=export_graphviz(t, out_file=None, fe... |
Gets a random sample of n rows from df without replacement. Parameters: ----------- df: A pandas data frame that you wish to sample from. n: The number of rows you wish to sample. Returns: -------- return value: A random sample of n rows of df. Examples: --------- >>> df = pd. DataFrame ( { col1: [ 1 2 3 ] col2: [ a b ... | def get_sample(df,n):
""" Gets a random sample of n rows from df, without replacement.
Parameters:
-----------
df: A pandas data frame, that you wish to sample from.
n: The number of rows you wish to sample.
Returns:
--------
return value: A random sample of n rows of df.
Examples:
... |
add_datepart converts a column of df from a datetime64 to many columns containing the information from the date. This applies changes inplace. Parameters: ----------- df: A pandas data frame. df gain several new columns. fldname: A string that is the name of the date column you wish to expand. If it is not a datetime64... | def add_datepart(df, fldname, drop=True, time=False, errors="raise"):
"""add_datepart converts a column of df from a datetime64 to many columns containing
the information from the date. This applies changes inplace.
Parameters:
-----------
df: A pandas data frame. df gain several new columns.
f... |
Change any columns of strings in a panda s dataframe to a column of categorical values. This applies the changes inplace. Parameters: ----------- df: A pandas dataframe. Any columns of strings will be changed to categorical values. Examples: --------- >>> df = pd. DataFrame ( { col1: [ 1 2 3 ] col2: [ a b a ] } ) >>> d... | def train_cats(df):
"""Change any columns of strings in a panda's dataframe to a column of
categorical values. This applies the changes inplace.
Parameters:
-----------
df: A pandas dataframe. Any columns of strings will be changed to
categorical values.
Examples:
---------
>>> d... |
Changes any columns of strings in df into categorical variables using trn as a template for the category codes. Parameters: ----------- df: A pandas dataframe. Any columns of strings will be changed to categorical values. The category codes are determined by trn. trn: A pandas dataframe. When creating a category for df... | def apply_cats(df, trn):
"""Changes any columns of strings in df into categorical variables using trn as
a template for the category codes.
Parameters:
-----------
df: A pandas dataframe. Any columns of strings will be changed to
categorical values. The category codes are determined by trn.
... |
Fill missing data in a column of df with the median and add a { name } _na column which specifies if the data was missing. Parameters: ----------- df: The data frame that will be changed. col: The column of data to fix by filling in missing data. name: The name of the new filled column in df. na_dict: A dictionary of v... | def fix_missing(df, col, name, na_dict):
""" Fill missing data in a column of df with the median, and add a {name}_na column
which specifies if the data was missing.
Parameters:
-----------
df: The data frame that will be changed.
col: The column of data to fix by filling in missing data.
na... |
Changes the column col from a categorical type to it s integer codes. Parameters: ----------- df: A pandas dataframe. df [ name ] will be filled with the integer codes from col. col: The column you wish to change into the categories. name: The column name you wish to insert into df. This column will hold the integer co... | def numericalize(df, col, name, max_n_cat):
""" Changes the column col from a categorical type to it's integer codes.
Parameters:
-----------
df: A pandas dataframe. df[name] will be filled with the integer codes from
col.
col: The column you wish to change into the categories.
name: The... |
proc_df takes a data frame df and splits off the response variable and changes the df into an entirely numeric dataframe. For each column of df which is not in skip_flds nor in ignore_flds na values are replaced by the median value of the column. Parameters: ----------- df: The data frame you wish to process. y_fld: Th... | def proc_df(df, y_fld=None, skip_flds=None, ignore_flds=None, do_scale=False, na_dict=None,
preproc_fn=None, max_n_cat=None, subset=None, mapper=None):
""" proc_df takes a data frame df and splits off the response variable, and
changes the df into an entirely numeric dataframe. For each column of df... |
Changes Scikit learn s random forests to give each tree a random sample of n random rows. | def set_rf_samples(n):
""" Changes Scikit learn's random forests to give each tree a random sample of
n random rows.
"""
forest._generate_sample_indices = (lambda rs, n_samples:
forest.check_random_state(rs).randint(0, n_samples, n)) |
Undoes the changes produced by set_rf_samples. | def reset_rf_samples():
""" Undoes the changes produced by set_rf_samples.
"""
forest._generate_sample_indices = (lambda rs, n_samples:
forest.check_random_state(rs).randint(0, n_samples, n_samples)) |
Return globally assigned variables. | def get_global_vars(mod):
"Return globally assigned variables."
# https://stackoverflow.com/questions/8820276/docstring-for-variable/31764368#31764368
import ast,re
with open(mod.__file__, 'r') as f: fstr = f.read()
flines = fstr.splitlines()
d = {}
for node in ast.walk(ast.parse(fstr)):
... |
Execute notebook fname with metadata for preprocessing. | def execute_nb(fname, metadata=None, save=True, show_doc_only=False):
"Execute notebook `fname` with `metadata` for preprocessing."
# Any module used in the notebook that isn't inside must be in the same directory as this script
with open(fname) as f: nb = nbformat.read(f, as_version=4)
ep_class = Execu... |
Create the documentation notebook for module mod_name in path dest_path | def create_module_page(mod, dest_path, force=False):
"Create the documentation notebook for module `mod_name` in path `dest_path`"
nb = get_empty_notebook()
mod_name = mod.__name__
strip_name = strip_fastai(mod_name)
init_cell = [get_md_cell(f'## Title for {strip_name} (use plain english, not module... |
Search a given path_dir and return all the modules contained inside except those in exclude | def get_module_names(path_dir, exclude=None):
if exclude is None: exclude = _default_exclude
"Search a given `path_dir` and return all the modules contained inside except those in `exclude`"
files = sorted(path_dir.glob('*'), key=lambda x: (x.is_dir(), x.name), reverse=True) # directories first
res = [f... |
Read a notebook in fname and return its corresponding json | def read_nb(fname):
"Read a notebook in `fname` and return its corresponding json"
with open(fname,'r') as f: return nbformat.reads(f.read(), as_version=4) |
Build a dictionary containing the position of the cells. | def read_nb_content(cells, mod_name):
"Build a dictionary containing the position of the `cells`."
doc_fns = {}
for i, cell in enumerate(cells):
if cell['cell_type'] == 'code':
for match in SHOW_DOC_RE.findall(cell['source']):
doc_fns[match] = i
return doc_fns |
Create documentation links for all cells in markdown with backticks. | def link_markdown_cells(cells, modules):
"Create documentation links for all cells in markdown with backticks."
for i, cell in enumerate(cells):
if cell['cell_type'] == 'markdown':
cell['source'] = link_docstring(modules, cell['source']) |
Return the position to insert a given function doc in a notebook. | def get_insert_idx(pos_dict, name):
"Return the position to insert a given function doc in a notebook."
keys,i = list(pos_dict.keys()),0
while i < len(keys) and str.lower(keys[i]) < str.lower(name): i+=1
if i == len(keys): return -1
else: return pos_dict[keys[i]] |
Update the pos_dict by moving all positions after start_key by nbr. | def update_pos(pos_dict, start_key, nbr=2):
"Update the `pos_dict` by moving all positions after `start_key` by `nbr`."
for key,idx in pos_dict.items():
if str.lower(key) >= str.lower(start_key): pos_dict[key] += nbr
return pos_dict |
Insert the function doc cells at their correct position and updates pos_dict. | def insert_cells(cells, pos_dict, ft_name, append=False):
"Insert the function doc `cells` at their correct position and updates `pos_dict`."
idx = get_insert_idx(pos_dict, ft_name)
if append or idx == -1: cells += [get_doc_cell(ft_name), get_empty_cell()]
else:
cells.insert(idx, get_doc_cell(ft... |
Creates jekyll metadata for given notebook path. | def update_nb_metadata(nb_path=None, title=None, summary=None, keywords='fastai', overwrite=True, **kwargs):
"Creates jekyll metadata for given notebook path."
nb = read_nb(nb_path)
data = {'title': title, 'summary': summary, 'keywords': keywords, **kwargs}
data = {k:v for (k,v) in data.items() if v is ... |
Finds all submodules of notebook - sorted by submodules > top level modules > manual imports. This gives notebook imports priority | def get_imported_modules(cells, nb_module_name=''):
"Finds all submodules of notebook - sorted by submodules > top level modules > manual imports. This gives notebook imports priority"
module_names = get_top_level_modules()
nb_imports = [match.group(1) for cell in cells for match in IMPORT_RE.finditer(cell[... |
Update the documentation notebook of a given module. | def update_module_page(mod, dest_path='.'):
"Update the documentation notebook of a given module."
doc_path = get_doc_path(mod, dest_path)
strip_name = strip_fastai(mod.__name__)
nb = read_nb(doc_path)
cells = nb['cells']
link_markdown_cells(cells, get_imported_modules(cells, mod.__name__))
... |
source_path can be a directory or a file. Assume all modules reside in the fastai directory. | def update_notebooks(source_path, dest_path=None, update_html=True, document_new_fns=False,
update_nb_links=True, html_path=None, force=False):
"`source_path` can be a directory or a file. Assume all modules reside in the fastai directory."
from .convert2html import convert_nb
source_pa... |
Return a dropout mask of the same type as x size sz with probability p to cancel an element. | def dropout_mask(x:Tensor, sz:Collection[int], p:float):
"Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element."
return x.new(*sz).bernoulli_(1-p).div_(1-p) |
Split a RNN model in groups for differential learning rates. | def awd_lstm_lm_split(model:nn.Module) -> List[nn.Module]:
"Split a RNN `model` in groups for differential learning rates."
groups = [[rnn, dp] for rnn, dp in zip(model[0].rnns, model[0].hidden_dps)]
return groups + [[model[0].encoder, model[0].encoder_dp, model[1]]] |
Convert a value x from 0 to 1 ( inclusive ) to an RGBA tuple according to cmap times transparency alpha_mult. | def value2rgba(x:float, cmap:Callable=cm.RdYlGn, alpha_mult:float=1.0)->Tuple:
"Convert a value `x` from 0 to 1 (inclusive) to an RGBA tuple according to `cmap` times transparency `alpha_mult`."
c = cmap(x)
rgb = (np.array(c[:-1]) * 255).astype(int)
a = c[-1] * alpha_mult
return tuple(rgb.tolist() +... |
Apply dropout to the raw weights. | def _setweights(self):
"Apply dropout to the raw weights."
for layer in self.layer_names:
raw_w = getattr(self, f'{layer}_raw')
self.module._parameters[layer] = F.dropout(raw_w, p=self.weight_p, training=self.training) |
Return one hidden state. | def _one_hidden(self, l:int)->Tensor:
"Return one hidden state."
nh = (self.n_hid if l != self.n_layers - 1 else self.emb_sz) // self.n_dir
return one_param(self).new(1, self.bs, nh).zero_() |
Reset the hidden states. | def reset(self):
"Reset the hidden states."
[r.reset() for r in self.rnns if hasattr(r, 'reset')]
if self.qrnn: self.hidden = [self._one_hidden(l) for l in range(self.n_layers)]
else: self.hidden = [(self._one_hidden(l), self._one_hidden(l)) for l in range(self.n_layers)] |
Calculate the intrinsic attention of the input w. r. t to an output class_id or the classification given by the model if None. For reference see the Sequential Jacobian session at https:// www. cs. toronto. edu/ ~graves/ preprint. pdf | def intrinsic_attention(self, text:str, class_id:int=None):
"""Calculate the intrinsic attention of the input w.r.t to an output `class_id`, or the classification given by the model if `None`.
For reference, see the Sequential Jacobian session at https://www.cs.toronto.edu/~graves/preprint.pdf
"... |
Create a tabulation showing the first k texts in top_losses along with their prediction actual loss and probability of actual class. max_len is the maximum number of tokens displayed. | def show_top_losses(self, k:int, max_len:int=70)->None:
"""
Create a tabulation showing the first `k` texts in top_losses along with their prediction, actual,loss, and probability of
actual class. `max_len` is the maximum number of tokens displayed.
"""
from IPython.display impor... |
Initialize the schedulers for training. | def on_train_begin(self, epoch:int, **kwargs:Any)->None:
"Initialize the schedulers for training."
res = {'epoch':self.start_epoch} if self.start_epoch is not None else None
self.start_epoch = ifnone(self.start_epoch, epoch)
self.scheds = [p.scheds for p in self.phases]
self.opt ... |
Take a step in lr mom sched start next stepper when the current one is complete. | def on_batch_end(self, train, **kwargs:Any)->None:
"Take a step in lr,mom sched, start next stepper when the current one is complete."
if train:
if self.idx_s >= len(self.scheds): return {'stop_training': True, 'stop_epoch': True}
sched = self.scheds[self.idx_s]
for k... |
Like torch. as_tensor but handle lists too and can pass multiple vector elements directly. | def tensor(x:Any, *rest)->Tensor:
"Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly."
if len(rest): x = (x,)+rest
# XXX: Pytorch bug in dataloader using num_workers>0; TODO: create repro and report
if is_listy(x) and len(x)==0: return tensor(0)
res = torch... |
Recursively detach lists of tensors in b ; put them on the CPU if cpu = True. | def to_detach(b:Tensors, cpu:bool=True):
"Recursively detach lists of tensors in `b `; put them on the CPU if `cpu=True`."
if is_listy(b): return [to_detach(o, cpu) for o in b]
if not isinstance(b,Tensor): return b
b = b.detach()
return b.cpu() if cpu else b |
Recursively map lists of items in b to their wrapped data. | def to_data(b:ItemsList):
"Recursively map lists of items in `b ` to their wrapped data."
if is_listy(b): return [to_data(o) for o in b]
return b.data if isinstance(b,ItemBase) else b |
Recursively map lists of tensors in b to the cpu. | def to_cpu(b:ItemsList):
"Recursively map lists of tensors in `b ` to the cpu."
if is_listy(b): return [to_cpu(o) for o in b]
return b.cpu() if isinstance(b,Tensor) else b |
Recursively map lists of tensors in b to FP16. | def to_half(b:Collection[Tensor])->Collection[Tensor]:
"Recursively map lists of tensors in `b ` to FP16."
if is_listy(b): return [to_half(o) for o in b]
return b.half() if b.dtype not in [torch.int64, torch.int32, torch.int16] else b |
Recursively map lists of tensors in b to FP16. | def to_float(b:Collection[Tensor])->Collection[Tensor]:
"Recursively map lists of tensors in `b ` to FP16."
if is_listy(b): return [to_float(o) for o in b]
return b.float() if b.dtype not in [torch.int64, torch.int32, torch.int16] else b |
Recursively put b on device. | def to_device(b:Tensors, device:torch.device):
"Recursively put `b` on `device`."
device = ifnone(device, defaults.device)
if is_listy(b): return [to_device(o, device) for o in b]
if is_dict(b): return {k: to_device(v, device) for k, v in b.items()}
return b.to(device, non_blocking=True) |
Convert batch items to tensor data. | def data_collate(batch:ItemsList)->Tensor:
"Convert `batch` items to tensor data."
return torch.utils.data.dataloader.default_collate(to_data(batch)) |
If b is not set return requires_grad of first param else set requires_grad on all params as b | def requires_grad(m:nn.Module, b:Optional[bool]=None)->Optional[bool]:
"If `b` is not set return `requires_grad` of first param, else set `requires_grad` on all params as `b`"
ps = list(m.parameters())
if not ps: return None
if b is None: return ps[0].requires_grad
for p in ps: p.requires_grad=b |
Return list of trainable params in m. | def trainable_params(m:nn.Module)->ParamList:
"Return list of trainable params in `m`."
res = filter(lambda p: p.requires_grad, m.parameters())
return res |
Return the children of m and its direct parameters not registered in modules. | def children_and_parameters(m:nn.Module):
"Return the children of `m` and its direct parameters not registered in modules."
children = list(m.children())
children_p = sum([[id(p) for p in c.parameters()] for c in m.children()],[])
for p in m.parameters():
if id(p) not in children_p: children.app... |
Split model according to the indexes in idxs. | def split_model_idx(model:nn.Module, idxs:Collection[int])->ModuleList:
"Split `model` according to the indexes in `idxs`."
layers = flatten_model(model)
if idxs[0] != 0: idxs = [0] + idxs
if idxs[-1] != len(layers): idxs.append(len(layers))
return [nn.Sequential(*layers[i:j]) for i,j in zip(idxs[:-... |
Split model according to the layers in splits. | def split_model(model:nn.Module=None, splits:Collection[Union[nn.Module,ModuleList]]=None):
"Split `model` according to the layers in `splits`."
splits = listify(splits)
if isinstance(splits[0], nn.Module):
layers = flatten_model(model)
idxs = [layers.index(first_layer(s)) for s in splits]
... |
Separate the parameters in layer_groups between no_wd_types and bias ( bias_types ) from the rest. | def split_no_wd_params(layer_groups:Collection[nn.Module])->List[List[nn.Parameter]]:
"Separate the parameters in `layer_groups` between `no_wd_types` and bias (`bias_types`) from the rest."
split_params = []
for l in layer_groups:
l1,l2 = [],[]
for c in l.children():
if isinsta... |
Set bn layers in eval mode for all recursive children of m. | def set_bn_eval(m:nn.Module)->None:
"Set bn layers in eval mode for all recursive children of `m`."
for l in m.children():
if isinstance(l, bn_types) and not next(l.parameters()).requires_grad:
l.eval()
set_bn_eval(l) |
If module is batchnorm don t use half precision. | def bn2float(module:nn.Module)->nn.Module:
"If `module` is batchnorm don't use half precision."
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): module.float()
for child in module.children(): bn2float(child)
return module |
Initialize m weights with func and set bias to 0. | def init_default(m:nn.Module, func:LayerFunc=nn.init.kaiming_normal_)->None:
"Initialize `m` weights with `func` and set `bias` to 0."
if func:
if hasattr(m, 'weight'): func(m.weight)
if hasattr(m, 'bias') and hasattr(m.bias, 'data'): m.bias.data.fill_(0.)
return m |
Initialize the non - batchnorm layers of m with init_func. | def cond_init(m:nn.Module, init_func:LayerFunc):
"Initialize the non-batchnorm layers of `m` with `init_func`."
if (not isinstance(m, bn_types)) and requires_grad(m): init_default(m, init_func) |
Initialize all non - batchnorm layers of m with init_func. | def apply_init(m, init_func:LayerFunc):
"Initialize all non-batchnorm layers of `m` with `init_func`."
apply_leaf(m, partial(cond_init, init_func=init_func)) |
Return the shape of the first weight layer in m. | def in_channels(m:nn.Module) -> List[int]:
"Return the shape of the first weight layer in `m`."
for l in flatten_model(m):
if hasattr(l, 'weight'): return l.weight.shape[1]
raise Exception('No weight layer') |
Return the torch type corresponding to dtype. | def model_type(dtype):
"Return the torch type corresponding to `dtype`."
return (torch.float32 if np.issubdtype(dtype, np.floating) else
torch.int64 if np.issubdtype(dtype, np.integer)
else None) |
Tranform numpy array a to a tensor of the same type. | def np2model_tensor(a):
"Tranform numpy array `a` to a tensor of the same type."
dtype = model_type(a.dtype)
res = as_tensor(a)
if not dtype: return res
return res.type(dtype) |
Compute PCA of x with k dimensions. | def _pca(x, k=2):
"Compute PCA of `x` with `k` dimensions."
x = x-torch.mean(x,0)
U,S,V = torch.svd(x.t())
return torch.mm(x,U[:,:k]) |
Grab the i - th batch in x batch_first stating the batch dimension. | def grab_idx(x,i,batch_first:bool=True):
"Grab the `i`-th batch in `x`, `batch_first` stating the batch dimension."
if batch_first: return ([o[i].cpu() for o in x] if is_listy(x) else x[i].cpu())
else: return ([o[:,i].cpu() for o in x] if is_listy(x) else x[:,i].cpu()) |
Inplace logit of x clamped to avoid inf | def logit_(x:Tensor)->Tensor:
"Inplace logit of `x`, clamped to avoid inf"
x.clamp_(1e-7, 1-1e-7)
return (x.reciprocal_().sub_(1)).log_().neg_() |
Draw 1 or shape = size random floats from uniform dist: min = low max = high. | def uniform(low:Number, high:Number=None, size:Optional[List[int]]=None)->FloatOrTensor:
"Draw 1 or shape=`size` random floats from uniform dist: min=`low`, max=`high`."
if high is None: high=low
return random.uniform(low,high) if size is None else torch.FloatTensor(*listify(size)).uniform_(low,high) |
Draw 1 or shape = size random floats from uniform dist: min = log ( low ) max = log ( high ). | def log_uniform(low, high, size:Optional[List[int]]=None)->FloatOrTensor:
"Draw 1 or shape=`size` random floats from uniform dist: min=log(`low`), max=log(`high`)."
res = uniform(log(low), log(high), size)
return exp(res) if size is None else res.exp_() |
Draw 1 or shape = size random booleans ( True occuring with probability p ). | def rand_bool(p:float, size:Optional[List[int]]=None)->BoolOrTensor:
"Draw 1 or shape=`size` random booleans (`True` occuring with probability `p`)."
return uniform(0,1,size)<p |
Generate int or tensor size of ints between low and high ( included ). | def uniform_int(low:int, high:int, size:Optional[List[int]]=None)->IntOrTensor:
"Generate int or tensor `size` of ints between `low` and `high` (included)."
return random.randint(low,high) if size is None else torch.randint(low,high+1,size) |
Try to convert o to int default to o if not possible. | def try_int(o:Any)->Any:
"Try to convert `o` to int, default to `o` if not possible."
# NB: single-item rank-1 array/tensor can be converted to int, but we don't want to do this
if isinstance(o, (np.ndarray,Tensor)): return o if o.ndim else int(o)
if isinstance(o, collections.Sized) or getattr(o,'__arra... |
Return the model maybe wrapped inside model. | def get_model(model:nn.Module):
"Return the model maybe wrapped inside `model`."
return model.module if isinstance(model, (DistributedDataParallel, nn.DataParallel)) else model |
Check that out and targ have the same number of elements and flatten them. | def flatten_check(out:Tensor, targ:Tensor) -> Tensor:
"Check that `out` and `targ` have the same number of elements and flatten them."
out,targ = out.contiguous().view(-1),targ.contiguous().view(-1)
assert len(out) == len(targ), f"Expected output and target to have the same number of elements but got {len(o... |
create new OrderedDict that does not contain module. | def remove_module_load(state_dict):
"""create new OrderedDict that does not contain `module.`"""
new_state_dict = OrderedDict()
for k, v in state_dict.items(): new_state_dict[k[7:]] = v
return new_state_dict |
Return a dictionary for updating last_metrics with mets. | def add_metrics(last_metrics:Collection[Rank0Tensor], mets:Union[Rank0Tensor, Collection[Rank0Tensor]]):
"Return a dictionary for updating `last_metrics` with `mets`."
last_metrics,mets = listify(last_metrics),listify(mets)
return {'last_metrics': last_metrics + mets} |
Collects iterables lazily rather than immediately. Docstring same as parent: https:// docs. python. org/ 3/ library/ concurrent. futures. html#concurrent. futures. Executor Implmentation taken from this PR: https:// github. com/ python/ cpython/ pull/ 707 | def map(self, fn, *iterables, timeout=None, chunksize=1, prefetch=None):
"""
Collects iterables lazily, rather than immediately.
Docstring same as parent: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor
Implmentation taken from this PR: https://githu... |
Generate documentation for fastai library in HTML ( asciidoctor required ): param str src: The absolute/ relative path of source file/ dir | def gen_ascii_docs(src='fastai'):
"""Generate documentation for fastai library in HTML (asciidoctor required)
:param str src: The absolute/relative path of source file/dir
"""
os.chdir(Path(__file__).absolute().parent)
with working_directory('..'):
path = Path(src)
if path.is_dir():
... |
Retrieves new batch of DatasetType and detaches it. | def _get_new_batch(self, ds_type:DatasetType)->Collection[Tensor]:
"Retrieves new batch of DatasetType, and detaches it."
return self.learn.data.one_batch(ds_type=ds_type, detach=True, denorm=False, cpu=False) |
one_batch function is extremely slow with large datasets. This is caching the result as an optimization. | def _update_batches_if_needed(self)->None:
"one_batch function is extremely slow with large datasets. This is caching the result as an optimization."
if self.learn.data.valid_dl is None: return # Running learning rate finder, so return
update_batches = self.data is not self.learn.data
i... |
Writes gradient statistics to Tensorboard. | def _write_model_stats(self, iteration:int)->None:
"Writes gradient statistics to Tensorboard."
self.stats_writer.write(model=self.learn.model, iteration=iteration, tbwriter=self.tbwriter) |
Writes training loss to Tensorboard. | def _write_training_loss(self, iteration:int, last_loss:Tensor)->None:
"Writes training loss to Tensorboard."
scalar_value = to_np(last_loss)
tag = self.metrics_root + 'train_loss'
self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration) |
Writes model weight histograms to Tensorboard. | def _write_weight_histograms(self, iteration:int)->None:
"Writes model weight histograms to Tensorboard."
self.hist_writer.write(model=self.learn.model, iteration=iteration, tbwriter=self.tbwriter) |
Writes single scalar value to Tensorboard. | def _write_scalar(self, name:str, scalar_value, iteration:int)->None:
"Writes single scalar value to Tensorboard."
tag = self.metrics_root + name
self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration) |
Writes training metrics to Tensorboard. | def _write_metrics(self, iteration:int, last_metrics:MetricsList, start_idx:int=2)->None:
"Writes training metrics to Tensorboard."
recorder = self.learn.recorder
for i, name in enumerate(recorder.names[start_idx:]):
if last_metrics is None or len(last_metrics) < i+1: return
... |
Callback function that writes batch end appropriate data to Tensorboard. | def on_batch_end(self, last_loss:Tensor, iteration:int, **kwargs)->None:
"Callback function that writes batch end appropriate data to Tensorboard."
if iteration == 0: return
self._update_batches_if_needed()
if iteration % self.loss_iters == 0: self._write_training_loss(iteration=iteratio... |
Callback function that writes backward end appropriate data to Tensorboard. | def on_backward_end(self, iteration:int, **kwargs)->None:
"Callback function that writes backward end appropriate data to Tensorboard."
if iteration == 0: return
self._update_batches_if_needed()
if iteration % self.stats_iters == 0: self._write_model_stats(iteration=iteration) |
Callback function that writes epoch end appropriate data to Tensorboard. | def on_epoch_end(self, last_metrics:MetricsList, iteration:int, **kwargs)->None:
"Callback function that writes epoch end appropriate data to Tensorboard."
self._write_metrics(iteration=iteration, last_metrics=last_metrics) |
Writes model weight histograms to Tensorboard. | def _write_weight_histograms(self, iteration:int)->None:
"Writes model weight histograms to Tensorboard."
generator, critic = self.learn.gan_trainer.generator, self.learn.gan_trainer.critic
self.hist_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='generator')
... |
Writes gradient statistics for generator to Tensorboard. | def _write_gen_model_stats(self, iteration:int)->None:
"Writes gradient statistics for generator to Tensorboard."
generator = self.learn.gan_trainer.generator
self.stats_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='gen_model_stats')
self.gen_stats_upda... |
Writes gradient statistics for critic to Tensorboard. | def _write_critic_model_stats(self, iteration:int)->None:
"Writes gradient statistics for critic to Tensorboard."
critic = self.learn.gan_trainer.critic
self.stats_writer.write(model=critic, iteration=iteration, tbwriter=self.tbwriter, name='crit_model_stats')
self.crit_stats_updated = T... |
Writes gradient statistics to Tensorboard. | def _write_model_stats(self, iteration:int)->None:
"Writes gradient statistics to Tensorboard."
# We don't want to write stats when model is not iterated on and hence has zeroed out gradients
gen_mode = self.learn.gan_trainer.gen_mode
if gen_mode and not self.gen_stats_updated: self._wri... |
Writes training loss to Tensorboard. | def _write_training_loss(self, iteration:int, last_loss:Tensor)->None:
"Writes training loss to Tensorboard."
recorder = self.learn.gan_trainer.recorder
if len(recorder.losses) == 0: return
scalar_value = to_np((recorder.losses[-1:])[0])
tag = self.metrics_root + 'train_loss'
... |
Writes model generated original and real images to Tensorboard. | def _write_images(self, iteration:int)->None:
"Writes model generated, original and real images to Tensorboard."
trainer = self.learn.gan_trainer
#TODO: Switching gen_mode temporarily seems a bit hacky here. Certainly not a good side-effect. Is there a better way?
gen_mode = trainer.g... |
Callback function that writes batch end appropriate data to Tensorboard. | def on_batch_end(self, iteration:int, **kwargs)->None:
"Callback function that writes batch end appropriate data to Tensorboard."
super().on_batch_end(iteration=iteration, **kwargs)
if iteration == 0: return
if iteration % self.visual_iters == 0: self._write_images(iteration=iteration) |
Callback function that writes backward end appropriate data to Tensorboard. | def on_backward_end(self, iteration:int, **kwargs)->None:
"Callback function that writes backward end appropriate data to Tensorboard."
if iteration == 0: return
self._update_batches_if_needed()
#TODO: This could perhaps be implemented as queues of requests instead but that seemed like ... |
Writes model generated original and real images to Tensorboard | def _write_images(self, iteration:int)->None:
"Writes model generated, original and real images to Tensorboard"
self.img_gen_vis.write(learn=self.learn, trn_batch=self.trn_batch, val_batch=self.val_batch, iteration=iteration,
tbwriter=self.tbwriter) |
Queues up an asynchronous write request to Tensorboard. | def request_write(self, request: TBWriteRequest)->None:
"Queues up an asynchronous write request to Tensorboard."
if self.stop_request.isSet(): return
self.queue.put(request) |
Processes queued up write requests asynchronously to Tensorboard. | def _queue_processor(self)->None:
"Processes queued up write requests asynchronously to Tensorboard."
while not self.stop_request.isSet():
while not self.queue.empty():
if self.stop_request.isSet(): return
request = self.queue.get()
request.wri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.