repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
fastai/fastai
old/fastai/core.py
split_by_idxs
def split_by_idxs(seq, idxs): '''A generator that returns sequence pieces, seperated by indexes specified in idxs. ''' last = 0 for idx in idxs: if not (-len(seq) <= idx < len(seq)): raise KeyError(f'Idx {idx} is out-of-bounds') yield seq[last:idx] last = idx yield seq[last:]
python
def split_by_idxs(seq, idxs): '''A generator that returns sequence pieces, seperated by indexes specified in idxs. ''' last = 0 for idx in idxs: if not (-len(seq) <= idx < len(seq)): raise KeyError(f'Idx {idx} is out-of-bounds') yield seq[last:idx] last = idx yield seq[last:]
[ "def", "split_by_idxs", "(", "seq", ",", "idxs", ")", ":", "last", "=", "0", "for", "idx", "in", "idxs", ":", "if", "not", "(", "-", "len", "(", "seq", ")", "<=", "idx", "<", "len", "(", "seq", ")", ")", ":", "raise", "KeyError", "(", "f'Idx {idx} is out-of-bounds'", ")", "yield", "seq", "[", "last", ":", "idx", "]", "last", "=", "idx", "yield", "seq", "[", "last", ":", "]" ]
A generator that returns sequence pieces, seperated by indexes specified in idxs.
[ "A", "generator", "that", "returns", "sequence", "pieces", "seperated", "by", "indexes", "specified", "in", "idxs", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L94-L102
train
fastai/fastai
old/fastai/core.py
partition
def partition(a, sz): """splits iterables a in equal parts of size sz""" return [a[i:i+sz] for i in range(0, len(a), sz)]
python
def partition(a, sz): """splits iterables a in equal parts of size sz""" return [a[i:i+sz] for i in range(0, len(a), sz)]
[ "def", "partition", "(", "a", ",", "sz", ")", ":", "return", "[", "a", "[", "i", ":", "i", "+", "sz", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "a", ")", ",", "sz", ")", "]" ]
splits iterables a in equal parts of size sz
[ "splits", "iterables", "a", "in", "equal", "parts", "of", "size", "sz" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L131-L133
train
fastai/fastai
old/fastai/core.py
chunk_iter
def chunk_iter(iterable, chunk_size): '''A generator that yields chunks of iterable, chunk_size at a time. ''' while True: chunk = [] try: for _ in range(chunk_size): chunk.append(next(iterable)) yield chunk except StopIteration: if chunk: yield chunk break
python
def chunk_iter(iterable, chunk_size): '''A generator that yields chunks of iterable, chunk_size at a time. ''' while True: chunk = [] try: for _ in range(chunk_size): chunk.append(next(iterable)) yield chunk except StopIteration: if chunk: yield chunk break
[ "def", "chunk_iter", "(", "iterable", ",", "chunk_size", ")", ":", "while", "True", ":", "chunk", "=", "[", "]", "try", ":", "for", "_", "in", "range", "(", "chunk_size", ")", ":", "chunk", ".", "append", "(", "next", "(", "iterable", ")", ")", "yield", "chunk", "except", "StopIteration", ":", "if", "chunk", ":", "yield", "chunk", "break" ]
A generator that yields chunks of iterable, chunk_size at a time.
[ "A", "generator", "that", "yields", "chunks", "of", "iterable", "chunk_size", "at", "a", "time", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L184-L193
train
fastai/fastai
fastai/vision/transform.py
_brightness
def _brightness(x, change:uniform): "Apply `change` in brightness of image `x`." return x.add_(scipy.special.logit(change))
python
def _brightness(x, change:uniform): "Apply `change` in brightness of image `x`." return x.add_(scipy.special.logit(change))
[ "def", "_brightness", "(", "x", ",", "change", ":", "uniform", ")", ":", "return", "x", ".", "add_", "(", "scipy", ".", "special", ".", "logit", "(", "change", ")", ")" ]
Apply `change` in brightness of image `x`.
[ "Apply", "change", "in", "brightness", "of", "image", "x", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L15-L17
train
fastai/fastai
fastai/vision/transform.py
_rotate
def _rotate(degrees:uniform): "Rotate image by `degrees`." angle = degrees * math.pi / 180 return [[cos(angle), -sin(angle), 0.], [sin(angle), cos(angle), 0.], [0. , 0. , 1.]]
python
def _rotate(degrees:uniform): "Rotate image by `degrees`." angle = degrees * math.pi / 180 return [[cos(angle), -sin(angle), 0.], [sin(angle), cos(angle), 0.], [0. , 0. , 1.]]
[ "def", "_rotate", "(", "degrees", ":", "uniform", ")", ":", "angle", "=", "degrees", "*", "math", ".", "pi", "/", "180", "return", "[", "[", "cos", "(", "angle", ")", ",", "-", "sin", "(", "angle", ")", ",", "0.", "]", ",", "[", "sin", "(", "angle", ")", ",", "cos", "(", "angle", ")", ",", "0.", "]", ",", "[", "0.", ",", "0.", ",", "1.", "]", "]" ]
Rotate image by `degrees`.
[ "Rotate", "image", "by", "degrees", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L25-L30
train
fastai/fastai
fastai/vision/transform.py
_get_zoom_mat
def _get_zoom_mat(sw:float, sh:float, c:float, r:float)->AffineMatrix: "`sw`,`sh` scale width,height - `c`,`r` focus col,row." return [[sw, 0, c], [0, sh, r], [0, 0, 1.]]
python
def _get_zoom_mat(sw:float, sh:float, c:float, r:float)->AffineMatrix: "`sw`,`sh` scale width,height - `c`,`r` focus col,row." return [[sw, 0, c], [0, sh, r], [0, 0, 1.]]
[ "def", "_get_zoom_mat", "(", "sw", ":", "float", ",", "sh", ":", "float", ",", "c", ":", "float", ",", "r", ":", "float", ")", "->", "AffineMatrix", ":", "return", "[", "[", "sw", ",", "0", ",", "c", "]", ",", "[", "0", ",", "sh", ",", "r", "]", ",", "[", "0", ",", "0", ",", "1.", "]", "]" ]
`sw`,`sh` scale width,height - `c`,`r` focus col,row.
[ "sw", "sh", "scale", "width", "height", "-", "c", "r", "focus", "col", "row", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L33-L37
train
fastai/fastai
fastai/vision/transform.py
_zoom
def _zoom(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5): "Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom." s = 1-1/scale col_c = s * (2*col_pct - 1) row_c = s * (2*row_pct - 1) return _get_zoom_mat(1/scale, 1/scale, col_c, row_c)
python
def _zoom(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5): "Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom." s = 1-1/scale col_c = s * (2*col_pct - 1) row_c = s * (2*row_pct - 1) return _get_zoom_mat(1/scale, 1/scale, col_c, row_c)
[ "def", "_zoom", "(", "scale", ":", "uniform", "=", "1.0", ",", "row_pct", ":", "uniform", "=", "0.5", ",", "col_pct", ":", "uniform", "=", "0.5", ")", ":", "s", "=", "1", "-", "1", "/", "scale", "col_c", "=", "s", "*", "(", "2", "*", "col_pct", "-", "1", ")", "row_c", "=", "s", "*", "(", "2", "*", "row_pct", "-", "1", ")", "return", "_get_zoom_mat", "(", "1", "/", "scale", ",", "1", "/", "scale", ",", "col_c", ",", "row_c", ")" ]
Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom.
[ "Zoom", "image", "by", "scale", ".", "row_pct", "col_pct", "select", "focal", "point", "of", "zoom", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L39-L44
train
fastai/fastai
fastai/vision/transform.py
_squish
def _squish(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5): "Squish image by `scale`. `row_pct`,`col_pct` select focal point of zoom." if scale <= 1: col_c = (1-scale) * (2*col_pct - 1) return _get_zoom_mat(scale, 1, col_c, 0.) else: row_c = (1-1/scale) * (2*row_pct - 1) return _get_zoom_mat(1, 1/scale, 0., row_c)
python
def _squish(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5): "Squish image by `scale`. `row_pct`,`col_pct` select focal point of zoom." if scale <= 1: col_c = (1-scale) * (2*col_pct - 1) return _get_zoom_mat(scale, 1, col_c, 0.) else: row_c = (1-1/scale) * (2*row_pct - 1) return _get_zoom_mat(1, 1/scale, 0., row_c)
[ "def", "_squish", "(", "scale", ":", "uniform", "=", "1.0", ",", "row_pct", ":", "uniform", "=", "0.5", ",", "col_pct", ":", "uniform", "=", "0.5", ")", ":", "if", "scale", "<=", "1", ":", "col_c", "=", "(", "1", "-", "scale", ")", "*", "(", "2", "*", "col_pct", "-", "1", ")", "return", "_get_zoom_mat", "(", "scale", ",", "1", ",", "col_c", ",", "0.", ")", "else", ":", "row_c", "=", "(", "1", "-", "1", "/", "scale", ")", "*", "(", "2", "*", "row_pct", "-", "1", ")", "return", "_get_zoom_mat", "(", "1", ",", "1", "/", "scale", ",", "0.", ",", "row_c", ")" ]
Squish image by `scale`. `row_pct`,`col_pct` select focal point of zoom.
[ "Squish", "image", "by", "scale", ".", "row_pct", "col_pct", "select", "focal", "point", "of", "zoom", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L47-L54
train
fastai/fastai
fastai/vision/transform.py
_jitter
def _jitter(c, magnitude:uniform): "Replace pixels by random neighbors at `magnitude`." c.flow.add_((torch.rand_like(c.flow)-0.5)*magnitude*2) return c
python
def _jitter(c, magnitude:uniform): "Replace pixels by random neighbors at `magnitude`." c.flow.add_((torch.rand_like(c.flow)-0.5)*magnitude*2) return c
[ "def", "_jitter", "(", "c", ",", "magnitude", ":", "uniform", ")", ":", "c", ".", "flow", ".", "add_", "(", "(", "torch", ".", "rand_like", "(", "c", ".", "flow", ")", "-", "0.5", ")", "*", "magnitude", "*", "2", ")", "return", "c" ]
Replace pixels by random neighbors at `magnitude`.
[ "Replace", "pixels", "by", "random", "neighbors", "at", "magnitude", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L57-L60
train
fastai/fastai
fastai/vision/transform.py
_flip_lr
def _flip_lr(x): "Flip `x` horizontally." #return x.flip(2) if isinstance(x, ImagePoints): x.flow.flow[...,0] *= -1 return x return tensor(np.ascontiguousarray(np.array(x)[...,::-1]))
python
def _flip_lr(x): "Flip `x` horizontally." #return x.flip(2) if isinstance(x, ImagePoints): x.flow.flow[...,0] *= -1 return x return tensor(np.ascontiguousarray(np.array(x)[...,::-1]))
[ "def", "_flip_lr", "(", "x", ")", ":", "#return x.flip(2)", "if", "isinstance", "(", "x", ",", "ImagePoints", ")", ":", "x", ".", "flow", ".", "flow", "[", "...", ",", "0", "]", "*=", "-", "1", "return", "x", "return", "tensor", "(", "np", ".", "ascontiguousarray", "(", "np", ".", "array", "(", "x", ")", "[", "...", ",", ":", ":", "-", "1", "]", ")", ")" ]
Flip `x` horizontally.
[ "Flip", "x", "horizontally", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L63-L69
train
fastai/fastai
fastai/vision/transform.py
_dihedral
def _dihedral(x, k:partial(uniform_int,0,7)): "Randomly flip `x` image based on `k`." flips=[] if k&1: flips.append(1) if k&2: flips.append(2) if flips: x = torch.flip(x,flips) if k&4: x = x.transpose(1,2) return x.contiguous()
python
def _dihedral(x, k:partial(uniform_int,0,7)): "Randomly flip `x` image based on `k`." flips=[] if k&1: flips.append(1) if k&2: flips.append(2) if flips: x = torch.flip(x,flips) if k&4: x = x.transpose(1,2) return x.contiguous()
[ "def", "_dihedral", "(", "x", ",", "k", ":", "partial", "(", "uniform_int", ",", "0", ",", "7", ")", ")", ":", "flips", "=", "[", "]", "if", "k", "&", "1", ":", "flips", ".", "append", "(", "1", ")", "if", "k", "&", "2", ":", "flips", ".", "append", "(", "2", ")", "if", "flips", ":", "x", "=", "torch", ".", "flip", "(", "x", ",", "flips", ")", "if", "k", "&", "4", ":", "x", "=", "x", ".", "transpose", "(", "1", ",", "2", ")", "return", "x", ".", "contiguous", "(", ")" ]
Randomly flip `x` image based on `k`.
[ "Randomly", "flip", "x", "image", "based", "on", "k", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L79-L86
train
fastai/fastai
fastai/vision/transform.py
_dihedral_affine
def _dihedral_affine(k:partial(uniform_int,0,7)): "Randomly flip `x` image based on `k`." x = -1 if k&1 else 1 y = -1 if k&2 else 1 if k&4: return [[0, x, 0.], [y, 0, 0], [0, 0, 1.]] return [[x, 0, 0.], [0, y, 0], [0, 0, 1.]]
python
def _dihedral_affine(k:partial(uniform_int,0,7)): "Randomly flip `x` image based on `k`." x = -1 if k&1 else 1 y = -1 if k&2 else 1 if k&4: return [[0, x, 0.], [y, 0, 0], [0, 0, 1.]] return [[x, 0, 0.], [0, y, 0], [0, 0, 1.]]
[ "def", "_dihedral_affine", "(", "k", ":", "partial", "(", "uniform_int", ",", "0", ",", "7", ")", ")", ":", "x", "=", "-", "1", "if", "k", "&", "1", "else", "1", "y", "=", "-", "1", "if", "k", "&", "2", "else", "1", "if", "k", "&", "4", ":", "return", "[", "[", "0", ",", "x", ",", "0.", "]", ",", "[", "y", ",", "0", ",", "0", "]", ",", "[", "0", ",", "0", ",", "1.", "]", "]", "return", "[", "[", "x", ",", "0", ",", "0.", "]", ",", "[", "0", ",", "y", ",", "0", "]", ",", "[", "0", ",", "0", ",", "1.", "]", "]" ]
Randomly flip `x` image based on `k`.
[ "Randomly", "flip", "x", "image", "based", "on", "k", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L89-L98
train
fastai/fastai
fastai/vision/transform.py
_pad_default
def _pad_default(x, padding:int, mode='reflection'): "Pad `x` with `padding` pixels. `mode` fills in space ('zeros','reflection','border')." mode = _pad_mode_convert[mode] return F.pad(x[None], (padding,)*4, mode=mode)[0]
python
def _pad_default(x, padding:int, mode='reflection'): "Pad `x` with `padding` pixels. `mode` fills in space ('zeros','reflection','border')." mode = _pad_mode_convert[mode] return F.pad(x[None], (padding,)*4, mode=mode)[0]
[ "def", "_pad_default", "(", "x", ",", "padding", ":", "int", ",", "mode", "=", "'reflection'", ")", ":", "mode", "=", "_pad_mode_convert", "[", "mode", "]", "return", "F", ".", "pad", "(", "x", "[", "None", "]", ",", "(", "padding", ",", ")", "*", "4", ",", "mode", "=", "mode", ")", "[", "0", "]" ]
Pad `x` with `padding` pixels. `mode` fills in space ('zeros','reflection','border').
[ "Pad", "x", "with", "padding", "pixels", ".", "mode", "fills", "in", "space", "(", "zeros", "reflection", "border", ")", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L108-L111
train
fastai/fastai
fastai/vision/transform.py
_cutout
def _cutout(x, n_holes:uniform_int=1, length:uniform_int=40): "Cut out `n_holes` number of square holes of size `length` in image at random locations." h,w = x.shape[1:] for n in range(n_holes): h_y = np.random.randint(0, h) h_x = np.random.randint(0, w) y1 = int(np.clip(h_y - length / 2, 0, h)) y2 = int(np.clip(h_y + length / 2, 0, h)) x1 = int(np.clip(h_x - length / 2, 0, w)) x2 = int(np.clip(h_x + length / 2, 0, w)) x[:, y1:y2, x1:x2] = 0 return x
python
def _cutout(x, n_holes:uniform_int=1, length:uniform_int=40): "Cut out `n_holes` number of square holes of size `length` in image at random locations." h,w = x.shape[1:] for n in range(n_holes): h_y = np.random.randint(0, h) h_x = np.random.randint(0, w) y1 = int(np.clip(h_y - length / 2, 0, h)) y2 = int(np.clip(h_y + length / 2, 0, h)) x1 = int(np.clip(h_x - length / 2, 0, w)) x2 = int(np.clip(h_x + length / 2, 0, w)) x[:, y1:y2, x1:x2] = 0 return x
[ "def", "_cutout", "(", "x", ",", "n_holes", ":", "uniform_int", "=", "1", ",", "length", ":", "uniform_int", "=", "40", ")", ":", "h", ",", "w", "=", "x", ".", "shape", "[", "1", ":", "]", "for", "n", "in", "range", "(", "n_holes", ")", ":", "h_y", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "h", ")", "h_x", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "w", ")", "y1", "=", "int", "(", "np", ".", "clip", "(", "h_y", "-", "length", "/", "2", ",", "0", ",", "h", ")", ")", "y2", "=", "int", "(", "np", ".", "clip", "(", "h_y", "+", "length", "/", "2", ",", "0", ",", "h", ")", ")", "x1", "=", "int", "(", "np", ".", "clip", "(", "h_x", "-", "length", "/", "2", ",", "0", ",", "w", ")", ")", "x2", "=", "int", "(", "np", ".", "clip", "(", "h_x", "+", "length", "/", "2", ",", "0", ",", "w", ")", ")", "x", "[", ":", ",", "y1", ":", "y2", ",", "x1", ":", "x2", "]", "=", "0", "return", "x" ]
Cut out `n_holes` number of square holes of size `length` in image at random locations.
[ "Cut", "out", "n_holes", "number", "of", "square", "holes", "of", "size", "length", "in", "image", "at", "random", "locations", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L122-L133
train
fastai/fastai
fastai/vision/transform.py
_rgb_randomize
def _rgb_randomize(x, channel:int=None, thresh:float=0.3): "Randomize one of the channels of the input image" if channel is None: channel = np.random.randint(0, x.shape[0] - 1) x[channel] = torch.rand(x.shape[1:]) * np.random.uniform(0, thresh) return x
python
def _rgb_randomize(x, channel:int=None, thresh:float=0.3): "Randomize one of the channels of the input image" if channel is None: channel = np.random.randint(0, x.shape[0] - 1) x[channel] = torch.rand(x.shape[1:]) * np.random.uniform(0, thresh) return x
[ "def", "_rgb_randomize", "(", "x", ",", "channel", ":", "int", "=", "None", ",", "thresh", ":", "float", "=", "0.3", ")", ":", "if", "channel", "is", "None", ":", "channel", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "x", ".", "shape", "[", "0", "]", "-", "1", ")", "x", "[", "channel", "]", "=", "torch", ".", "rand", "(", "x", ".", "shape", "[", "1", ":", "]", ")", "*", "np", ".", "random", ".", "uniform", "(", "0", ",", "thresh", ")", "return", "x" ]
Randomize one of the channels of the input image
[ "Randomize", "one", "of", "the", "channels", "of", "the", "input", "image" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L137-L141
train
fastai/fastai
fastai/vision/transform.py
_crop_default
def _crop_default(x, size, row_pct:uniform=0.5, col_pct:uniform=0.5): "Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop." rows,cols = tis2hw(size) row_pct,col_pct = _minus_epsilon(row_pct,col_pct) row = int((x.size(1)-rows+1) * row_pct) col = int((x.size(2)-cols+1) * col_pct) return x[:, row:row+rows, col:col+cols].contiguous()
python
def _crop_default(x, size, row_pct:uniform=0.5, col_pct:uniform=0.5): "Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop." rows,cols = tis2hw(size) row_pct,col_pct = _minus_epsilon(row_pct,col_pct) row = int((x.size(1)-rows+1) * row_pct) col = int((x.size(2)-cols+1) * col_pct) return x[:, row:row+rows, col:col+cols].contiguous()
[ "def", "_crop_default", "(", "x", ",", "size", ",", "row_pct", ":", "uniform", "=", "0.5", ",", "col_pct", ":", "uniform", "=", "0.5", ")", ":", "rows", ",", "cols", "=", "tis2hw", "(", "size", ")", "row_pct", ",", "col_pct", "=", "_minus_epsilon", "(", "row_pct", ",", "col_pct", ")", "row", "=", "int", "(", "(", "x", ".", "size", "(", "1", ")", "-", "rows", "+", "1", ")", "*", "row_pct", ")", "col", "=", "int", "(", "(", "x", ".", "size", "(", "2", ")", "-", "cols", "+", "1", ")", "*", "col_pct", ")", "return", "x", "[", ":", ",", "row", ":", "row", "+", "rows", ",", "col", ":", "col", "+", "cols", "]", ".", "contiguous", "(", ")" ]
Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop.
[ "Crop", "x", "to", "size", "pixels", ".", "row_pct", "col_pct", "select", "focal", "point", "of", "crop", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L150-L156
train
fastai/fastai
fastai/vision/transform.py
_crop_pad_default
def _crop_pad_default(x, size, padding_mode='reflection', row_pct:uniform = 0.5, col_pct:uniform = 0.5): "Crop and pad tfm - `row_pct`,`col_pct` sets focal point." padding_mode = _pad_mode_convert[padding_mode] size = tis2hw(size) if x.shape[1:] == torch.Size(size): return x rows,cols = size row_pct,col_pct = _minus_epsilon(row_pct,col_pct) if x.size(1)<rows or x.size(2)<cols: row_pad = max((rows-x.size(1)+1)//2, 0) col_pad = max((cols-x.size(2)+1)//2, 0) x = F.pad(x[None], (col_pad,col_pad,row_pad,row_pad), mode=padding_mode)[0] row = int((x.size(1)-rows+1)*row_pct) col = int((x.size(2)-cols+1)*col_pct) x = x[:, row:row+rows, col:col+cols] return x.contiguous()
python
def _crop_pad_default(x, size, padding_mode='reflection', row_pct:uniform = 0.5, col_pct:uniform = 0.5): "Crop and pad tfm - `row_pct`,`col_pct` sets focal point." padding_mode = _pad_mode_convert[padding_mode] size = tis2hw(size) if x.shape[1:] == torch.Size(size): return x rows,cols = size row_pct,col_pct = _minus_epsilon(row_pct,col_pct) if x.size(1)<rows or x.size(2)<cols: row_pad = max((rows-x.size(1)+1)//2, 0) col_pad = max((cols-x.size(2)+1)//2, 0) x = F.pad(x[None], (col_pad,col_pad,row_pad,row_pad), mode=padding_mode)[0] row = int((x.size(1)-rows+1)*row_pct) col = int((x.size(2)-cols+1)*col_pct) x = x[:, row:row+rows, col:col+cols] return x.contiguous()
[ "def", "_crop_pad_default", "(", "x", ",", "size", ",", "padding_mode", "=", "'reflection'", ",", "row_pct", ":", "uniform", "=", "0.5", ",", "col_pct", ":", "uniform", "=", "0.5", ")", ":", "padding_mode", "=", "_pad_mode_convert", "[", "padding_mode", "]", "size", "=", "tis2hw", "(", "size", ")", "if", "x", ".", "shape", "[", "1", ":", "]", "==", "torch", ".", "Size", "(", "size", ")", ":", "return", "x", "rows", ",", "cols", "=", "size", "row_pct", ",", "col_pct", "=", "_minus_epsilon", "(", "row_pct", ",", "col_pct", ")", "if", "x", ".", "size", "(", "1", ")", "<", "rows", "or", "x", ".", "size", "(", "2", ")", "<", "cols", ":", "row_pad", "=", "max", "(", "(", "rows", "-", "x", ".", "size", "(", "1", ")", "+", "1", ")", "//", "2", ",", "0", ")", "col_pad", "=", "max", "(", "(", "cols", "-", "x", ".", "size", "(", "2", ")", "+", "1", ")", "//", "2", ",", "0", ")", "x", "=", "F", ".", "pad", "(", "x", "[", "None", "]", ",", "(", "col_pad", ",", "col_pad", ",", "row_pad", ",", "row_pad", ")", ",", "mode", "=", "padding_mode", ")", "[", "0", "]", "row", "=", "int", "(", "(", "x", ".", "size", "(", "1", ")", "-", "rows", "+", "1", ")", "*", "row_pct", ")", "col", "=", "int", "(", "(", "x", ".", "size", "(", "2", ")", "-", "cols", "+", "1", ")", "*", "col_pct", ")", "x", "=", "x", "[", ":", ",", "row", ":", "row", "+", "rows", ",", "col", ":", "col", "+", "cols", "]", "return", "x", ".", "contiguous", "(", ")" ]
Crop and pad tfm - `row_pct`,`col_pct` sets focal point.
[ "Crop", "and", "pad", "tfm", "-", "row_pct", "col_pct", "sets", "focal", "point", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L175-L189
train
fastai/fastai
fastai/vision/transform.py
rand_pad
def rand_pad(padding:int, size:int, mode:str='reflection'): "Fixed `mode` `padding` and random crop of `size`" return [pad(padding=padding,mode=mode), crop(size=size, **rand_pos)]
python
def rand_pad(padding:int, size:int, mode:str='reflection'): "Fixed `mode` `padding` and random crop of `size`" return [pad(padding=padding,mode=mode), crop(size=size, **rand_pos)]
[ "def", "rand_pad", "(", "padding", ":", "int", ",", "size", ":", "int", ",", "mode", ":", "str", "=", "'reflection'", ")", ":", "return", "[", "pad", "(", "padding", "=", "padding", ",", "mode", "=", "mode", ")", ",", "crop", "(", "size", "=", "size", ",", "*", "*", "rand_pos", ")", "]" ]
Fixed `mode` `padding` and random crop of `size`
[ "Fixed", "mode", "padding", "and", "random", "crop", "of", "size" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L213-L216
train
fastai/fastai
fastai/vision/transform.py
rand_zoom
def rand_zoom(scale:uniform=1.0, p:float=1.): "Randomized version of `zoom`." return zoom(scale=scale, **rand_pos, p=p)
python
def rand_zoom(scale:uniform=1.0, p:float=1.): "Randomized version of `zoom`." return zoom(scale=scale, **rand_pos, p=p)
[ "def", "rand_zoom", "(", "scale", ":", "uniform", "=", "1.0", ",", "p", ":", "float", "=", "1.", ")", ":", "return", "zoom", "(", "scale", "=", "scale", ",", "*", "*", "rand_pos", ",", "p", "=", "p", ")" ]
Randomized version of `zoom`.
[ "Randomized", "version", "of", "zoom", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L218-L220
train
fastai/fastai
fastai/vision/transform.py
rand_crop
def rand_crop(*args, padding_mode='reflection', p:float=1.): "Randomized version of `crop_pad`." return crop_pad(*args, **rand_pos, padding_mode=padding_mode, p=p)
python
def rand_crop(*args, padding_mode='reflection', p:float=1.): "Randomized version of `crop_pad`." return crop_pad(*args, **rand_pos, padding_mode=padding_mode, p=p)
[ "def", "rand_crop", "(", "*", "args", ",", "padding_mode", "=", "'reflection'", ",", "p", ":", "float", "=", "1.", ")", ":", "return", "crop_pad", "(", "*", "args", ",", "*", "*", "rand_pos", ",", "padding_mode", "=", "padding_mode", ",", "p", "=", "p", ")" ]
Randomized version of `crop_pad`.
[ "Randomized", "version", "of", "crop_pad", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L222-L224
train
fastai/fastai
fastai/vision/transform.py
zoom_crop
def zoom_crop(scale:float, do_rand:bool=False, p:float=1.0): "Randomly zoom and/or crop." zoom_fn = rand_zoom if do_rand else zoom crop_fn = rand_crop if do_rand else crop_pad return [zoom_fn(scale=scale, p=p), crop_fn()]
python
def zoom_crop(scale:float, do_rand:bool=False, p:float=1.0): "Randomly zoom and/or crop." zoom_fn = rand_zoom if do_rand else zoom crop_fn = rand_crop if do_rand else crop_pad return [zoom_fn(scale=scale, p=p), crop_fn()]
[ "def", "zoom_crop", "(", "scale", ":", "float", ",", "do_rand", ":", "bool", "=", "False", ",", "p", ":", "float", "=", "1.0", ")", ":", "zoom_fn", "=", "rand_zoom", "if", "do_rand", "else", "zoom", "crop_fn", "=", "rand_crop", "if", "do_rand", "else", "crop_pad", "return", "[", "zoom_fn", "(", "scale", "=", "scale", ",", "p", "=", "p", ")", ",", "crop_fn", "(", ")", "]" ]
Randomly zoom and/or crop.
[ "Randomly", "zoom", "and", "/", "or", "crop", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L226-L230
train
fastai/fastai
fastai/vision/transform.py
_find_coeffs
def _find_coeffs(orig_pts:Points, targ_pts:Points)->Tensor: "Find 8 coeff mentioned [here](https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/)." matrix = [] #The equations we'll need to solve. for p1, p2 in zip(targ_pts, orig_pts): matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]]) matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]]) A = FloatTensor(matrix) B = FloatTensor(orig_pts).view(8, 1) #The 8 scalars we seek are solution of AX = B return _solve_func(B,A)[0][:,0]
python
def _find_coeffs(orig_pts:Points, targ_pts:Points)->Tensor: "Find 8 coeff mentioned [here](https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/)." matrix = [] #The equations we'll need to solve. for p1, p2 in zip(targ_pts, orig_pts): matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]]) matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]]) A = FloatTensor(matrix) B = FloatTensor(orig_pts).view(8, 1) #The 8 scalars we seek are solution of AX = B return _solve_func(B,A)[0][:,0]
[ "def", "_find_coeffs", "(", "orig_pts", ":", "Points", ",", "targ_pts", ":", "Points", ")", "->", "Tensor", ":", "matrix", "=", "[", "]", "#The equations we'll need to solve.", "for", "p1", ",", "p2", "in", "zip", "(", "targ_pts", ",", "orig_pts", ")", ":", "matrix", ".", "append", "(", "[", "p1", "[", "0", "]", ",", "p1", "[", "1", "]", ",", "1", ",", "0", ",", "0", ",", "0", ",", "-", "p2", "[", "0", "]", "*", "p1", "[", "0", "]", ",", "-", "p2", "[", "0", "]", "*", "p1", "[", "1", "]", "]", ")", "matrix", ".", "append", "(", "[", "0", ",", "0", ",", "0", ",", "p1", "[", "0", "]", ",", "p1", "[", "1", "]", ",", "1", ",", "-", "p2", "[", "1", "]", "*", "p1", "[", "0", "]", ",", "-", "p2", "[", "1", "]", "*", "p1", "[", "1", "]", "]", ")", "A", "=", "FloatTensor", "(", "matrix", ")", "B", "=", "FloatTensor", "(", "orig_pts", ")", ".", "view", "(", "8", ",", "1", ")", "#The 8 scalars we seek are solution of AX = B", "return", "_solve_func", "(", "B", ",", "A", ")", "[", "0", "]", "[", ":", ",", "0", "]" ]
Find 8 coeff mentioned [here](https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/).
[ "Find", "8", "coeff", "mentioned", "[", "here", "]", "(", "https", ":", "//", "web", ".", "archive", ".", "org", "/", "web", "/", "20150222120106", "/", "xenia", ".", "media", ".", "mit", ".", "edu", "/", "~cwren", "/", "interpolator", "/", ")", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L235-L246
train
fastai/fastai
fastai/vision/transform.py
_apply_perspective
def _apply_perspective(coords:FlowField, coeffs:Points)->FlowField: "Transform `coords` with `coeffs`." size = coords.flow.size() #compress all the dims expect the last one ang adds ones, coords become N * 3 coords.flow = coords.flow.view(-1,2) #Transform the coeffs in a 3*3 matrix with a 1 at the bottom left coeffs = torch.cat([coeffs, FloatTensor([1])]).view(3,3) coords.flow = torch.addmm(coeffs[:,2], coords.flow, coeffs[:,:2].t()) coords.flow.mul_(1/coords.flow[:,2].unsqueeze(1)) coords.flow = coords.flow[:,:2].view(size) return coords
python
def _apply_perspective(coords:FlowField, coeffs:Points)->FlowField: "Transform `coords` with `coeffs`." size = coords.flow.size() #compress all the dims expect the last one ang adds ones, coords become N * 3 coords.flow = coords.flow.view(-1,2) #Transform the coeffs in a 3*3 matrix with a 1 at the bottom left coeffs = torch.cat([coeffs, FloatTensor([1])]).view(3,3) coords.flow = torch.addmm(coeffs[:,2], coords.flow, coeffs[:,:2].t()) coords.flow.mul_(1/coords.flow[:,2].unsqueeze(1)) coords.flow = coords.flow[:,:2].view(size) return coords
[ "def", "_apply_perspective", "(", "coords", ":", "FlowField", ",", "coeffs", ":", "Points", ")", "->", "FlowField", ":", "size", "=", "coords", ".", "flow", ".", "size", "(", ")", "#compress all the dims expect the last one ang adds ones, coords become N * 3", "coords", ".", "flow", "=", "coords", ".", "flow", ".", "view", "(", "-", "1", ",", "2", ")", "#Transform the coeffs in a 3*3 matrix with a 1 at the bottom left", "coeffs", "=", "torch", ".", "cat", "(", "[", "coeffs", ",", "FloatTensor", "(", "[", "1", "]", ")", "]", ")", ".", "view", "(", "3", ",", "3", ")", "coords", ".", "flow", "=", "torch", ".", "addmm", "(", "coeffs", "[", ":", ",", "2", "]", ",", "coords", ".", "flow", ",", "coeffs", "[", ":", ",", ":", "2", "]", ".", "t", "(", ")", ")", "coords", ".", "flow", ".", "mul_", "(", "1", "/", "coords", ".", "flow", "[", ":", ",", "2", "]", ".", "unsqueeze", "(", "1", ")", ")", "coords", ".", "flow", "=", "coords", ".", "flow", "[", ":", ",", ":", "2", "]", ".", "view", "(", "size", ")", "return", "coords" ]
Transform `coords` with `coeffs`.
[ "Transform", "coords", "with", "coeffs", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L248-L258
train
fastai/fastai
fastai/vision/transform.py
_do_perspective_warp
def _do_perspective_warp(c:FlowField, targ_pts:Points, invert=False): "Apply warp to `targ_pts` from `_orig_pts` to `c` `FlowField`." if invert: return _apply_perspective(c, _find_coeffs(targ_pts, _orig_pts)) return _apply_perspective(c, _find_coeffs(_orig_pts, targ_pts))
python
def _do_perspective_warp(c:FlowField, targ_pts:Points, invert=False): "Apply warp to `targ_pts` from `_orig_pts` to `c` `FlowField`." if invert: return _apply_perspective(c, _find_coeffs(targ_pts, _orig_pts)) return _apply_perspective(c, _find_coeffs(_orig_pts, targ_pts))
[ "def", "_do_perspective_warp", "(", "c", ":", "FlowField", ",", "targ_pts", ":", "Points", ",", "invert", "=", "False", ")", ":", "if", "invert", ":", "return", "_apply_perspective", "(", "c", ",", "_find_coeffs", "(", "targ_pts", ",", "_orig_pts", ")", ")", "return", "_apply_perspective", "(", "c", ",", "_find_coeffs", "(", "_orig_pts", ",", "targ_pts", ")", ")" ]
Apply warp to `targ_pts` from `_orig_pts` to `c` `FlowField`.
[ "Apply", "warp", "to", "targ_pts", "from", "_orig_pts", "to", "c", "FlowField", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L262-L265
train
fastai/fastai
fastai/vision/transform.py
_perspective_warp
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)
python
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", ")", ":", "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`.
[ "Apply", "warp", "of", "magnitude", "to", "c", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L267-L271
train
fastai/fastai
fastai/vision/transform.py
_symmetric_warp
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)
python
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", ")", ":", "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`.
[ "Apply", "symmetric", "warp", "of", "magnitude", "to", "c", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L274-L278
train
fastai/fastai
fastai/vision/transform.py
_tilt
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-magnitude], [-1,1+magnitude], [1,-1], [1,1]] elif direction == 2: targ_pts = [[-1,-1], [-1-magnitude,1], [1,-1], [1+magnitude,1]] elif direction == 3: targ_pts = [[-1-magnitude,-1], [-1,1], [1+magnitude,-1], [1,1]] coeffs = _find_coeffs(targ_pts, _orig_pts) if invert else _find_coeffs(_orig_pts, targ_pts) return _apply_perspective(c, coeffs)
python
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-magnitude], [-1,1+magnitude], [1,-1], [1,1]] elif direction == 2: targ_pts = [[-1,-1], [-1-magnitude,1], [1,-1], [1+magnitude,1]] elif direction == 3: targ_pts = [[-1-magnitude,-1], [-1,1], [1+magnitude,-1], [1,1]] coeffs = _find_coeffs(targ_pts, _orig_pts) if invert else _find_coeffs(_orig_pts, targ_pts) return _apply_perspective(c, coeffs)
[ "def", "_tilt", "(", "c", ",", "direction", ":", "uniform_int", ",", "magnitude", ":", "uniform", "=", "0", ",", "invert", "=", "False", ")", ":", "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", "-", "magnitude", "]", ",", "[", "-", "1", ",", "1", "+", "magnitude", "]", ",", "[", "1", ",", "-", "1", "]", ",", "[", "1", ",", "1", "]", "]", "elif", "direction", "==", "2", ":", "targ_pts", "=", "[", "[", "-", "1", ",", "-", "1", "]", ",", "[", "-", "1", "-", "magnitude", ",", "1", "]", ",", "[", "1", ",", "-", "1", "]", ",", "[", "1", "+", "magnitude", ",", "1", "]", "]", "elif", "direction", "==", "3", ":", "targ_pts", "=", "[", "[", "-", "1", "-", "magnitude", ",", "-", "1", "]", ",", "[", "-", "1", ",", "1", "]", ",", "[", "1", "+", "magnitude", ",", "-", "1", "]", ",", "[", "1", ",", "1", "]", "]", "coeffs", "=", "_find_coeffs", "(", "targ_pts", ",", "_orig_pts", ")", "if", "invert", "else", "_find_coeffs", "(", "_orig_pts", ",", "targ_pts", ")", "return", "_apply_perspective", "(", "c", ",", "coeffs", ")" ]
Tilt `c` field with random `direction` and `magnitude`.
[ "Tilt", "c", "field", "with", "random", "direction", "and", "magnitude", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L281-L289
train
fastai/fastai
fastai/vision/transform.py
get_transforms
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 easily create a list of flip, rotate, `zoom`, warp, lighting transforms." res = [rand_crop()] if do_flip: res.append(dihedral_affine() if flip_vert else flip_lr(p=0.5)) if max_warp: res.append(symmetric_warp(magnitude=(-max_warp,max_warp), p=p_affine)) if max_rotate: res.append(rotate(degrees=(-max_rotate,max_rotate), p=p_affine)) if max_zoom>1: res.append(rand_zoom(scale=(1.,max_zoom), p=p_affine)) if max_lighting: res.append(brightness(change=(0.5*(1-max_lighting), 0.5*(1+max_lighting)), p=p_lighting)) res.append(contrast(scale=(1-max_lighting, 1/(1-max_lighting)), p=p_lighting)) # train , valid return (res + listify(xtra_tfms), [crop_pad()])
python
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 easily create a list of flip, rotate, `zoom`, warp, lighting transforms." res = [rand_crop()] if do_flip: res.append(dihedral_affine() if flip_vert else flip_lr(p=0.5)) if max_warp: res.append(symmetric_warp(magnitude=(-max_warp,max_warp), p=p_affine)) if max_rotate: res.append(rotate(degrees=(-max_rotate,max_rotate), p=p_affine)) if max_zoom>1: res.append(rand_zoom(scale=(1.,max_zoom), p=p_affine)) if max_lighting: res.append(brightness(change=(0.5*(1-max_lighting), 0.5*(1+max_lighting)), p=p_lighting)) res.append(contrast(scale=(1-max_lighting, 1/(1-max_lighting)), p=p_lighting)) # train , valid return (res + listify(xtra_tfms), [crop_pad()])
[ "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", "]", ":", "res", "=", "[", "rand_crop", "(", ")", "]", "if", "do_flip", ":", "res", ".", "append", "(", "dihedral_affine", "(", ")", "if", "flip_vert", "else", "flip_lr", "(", "p", "=", "0.5", ")", ")", "if", "max_warp", ":", "res", ".", "append", "(", "symmetric_warp", "(", "magnitude", "=", "(", "-", "max_warp", ",", "max_warp", ")", ",", "p", "=", "p_affine", ")", ")", "if", "max_rotate", ":", "res", ".", "append", "(", "rotate", "(", "degrees", "=", "(", "-", "max_rotate", ",", "max_rotate", ")", ",", "p", "=", "p_affine", ")", ")", "if", "max_zoom", ">", "1", ":", "res", ".", "append", "(", "rand_zoom", "(", "scale", "=", "(", "1.", ",", "max_zoom", ")", ",", "p", "=", "p_affine", ")", ")", "if", "max_lighting", ":", "res", ".", "append", "(", "brightness", "(", "change", "=", "(", "0.5", "*", "(", "1", "-", "max_lighting", ")", ",", "0.5", "*", "(", "1", "+", "max_lighting", ")", ")", ",", "p", "=", "p_lighting", ")", ")", "res", ".", "append", "(", "contrast", "(", "scale", "=", "(", "1", "-", "max_lighting", ",", "1", "/", "(", "1", "-", "max_lighting", ")", ")", ",", "p", "=", "p_lighting", ")", ")", "# train , valid", "return", "(", "res", "+", "listify", "(", "xtra_tfms", ")", ",", "[", "crop_pad", "(", ")", "]", ")" ]
Utility func to easily create a list of flip, rotate, `zoom`, warp, lighting transforms.
[ "Utility", "func", "to", "easily", "create", "a", "list", "of", "flip", "rotate", "zoom", "warp", "lighting", "transforms", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L307-L320
train
fastai/fastai
fastai/vision/transform.py
_compute_zs_mat
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(r) if s * r <= 1 and s / r <= 1: #Test if we are completely inside the picture w,h = (s/r, s*r) if i else (s*r,s/r) col_c = (1-w) * (2*col_pct - 1) row_c = (1-h) * (2*row_pct - 1) return _get_zoom_mat(w, h, col_c, row_c) #Fallback, hack to emulate a center crop without cropping anything yet. if orig_ratio > 1: return _get_zoom_mat(1/orig_ratio**2, 1, 0, 0.) else: return _get_zoom_mat(1, orig_ratio**2, 0, 0.)
python
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(r) if s * r <= 1 and s / r <= 1: #Test if we are completely inside the picture w,h = (s/r, s*r) if i else (s*r,s/r) col_c = (1-w) * (2*col_pct - 1) row_c = (1-h) * (2*row_pct - 1) return _get_zoom_mat(w, h, col_c, row_c) #Fallback, hack to emulate a center crop without cropping anything yet. if orig_ratio > 1: return _get_zoom_mat(1/orig_ratio**2, 1, 0, 0.) else: return _get_zoom_mat(1, orig_ratio**2, 0, 0.)
[ "def", "_compute_zs_mat", "(", "sz", ":", "TensorImageSize", ",", "scale", ":", "float", ",", "squish", ":", "float", ",", "invert", ":", "bool", ",", "row_pct", ":", "float", ",", "col_pct", ":", "float", ")", "->", "AffineMatrix", ":", "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", "(", "r", ")", "if", "s", "*", "r", "<=", "1", "and", "s", "/", "r", "<=", "1", ":", "#Test if we are completely inside the picture", "w", ",", "h", "=", "(", "s", "/", "r", ",", "s", "*", "r", ")", "if", "i", "else", "(", "s", "*", "r", ",", "s", "/", "r", ")", "col_c", "=", "(", "1", "-", "w", ")", "*", "(", "2", "*", "col_pct", "-", "1", ")", "row_c", "=", "(", "1", "-", "h", ")", "*", "(", "2", "*", "row_pct", "-", "1", ")", "return", "_get_zoom_mat", "(", "w", ",", "h", ",", "col_c", ",", "row_c", ")", "#Fallback, hack to emulate a center crop without cropping anything yet.", "if", "orig_ratio", ">", "1", ":", "return", "_get_zoom_mat", "(", "1", "/", "orig_ratio", "**", "2", ",", "1", ",", "0", ",", "0.", ")", "else", ":", "return", "_get_zoom_mat", "(", "1", ",", "orig_ratio", "**", "2", ",", "0", ",", "0.", ")" ]
Utility routine to compute zoom/squish matrix.
[ "Utility", "routine", "to", "compute", "zoom", "/", "squish", "matrix", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L322-L336
train
fastai/fastai
fastai/vision/transform.py
rand_resize_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(size=size)]
python
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(size=size)]
[ "def", "rand_resize_crop", "(", "size", ":", "int", ",", "max_scale", ":", "float", "=", "2.", ",", "ratios", ":", "Tuple", "[", "float", ",", "float", "]", "=", "(", "0.75", ",", "1.33", ")", ")", ":", "return", "[", "zoom_squish", "(", "scale", "=", "(", "1.", ",", "max_scale", ",", "8", ")", ",", "squish", "=", "(", "*", "ratios", ",", "8", ")", ",", "invert", "=", "(", "0.5", ",", "8", ")", ",", "row_pct", "=", "(", "0.", ",", "1.", ")", ",", "col_pct", "=", "(", "0.", ",", "1.", ")", ")", ",", "crop", "(", "size", "=", "size", ")", "]" ]
Randomly resize and crop the image to a ratio in `ratios` after a zoom of `max_scale`.
[ "Randomly", "resize", "and", "crop", "the", "image", "to", "a", "ratio", "in", "ratios", "after", "a", "zoom", "of", "max_scale", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L346-L349
train
fastai/fastai
old/fastai/models/cifar10/main_dxy.py
adjust_learning_rate
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 >= step): lr = lr * gamma else: break for param_group in optimizer.param_groups: param_group['lr'] = lr return lr
python
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 >= step): lr = lr * gamma else: break for param_group in optimizer.param_groups: param_group['lr'] = lr return lr
[ "def", "adjust_learning_rate", "(", "optimizer", ",", "epoch", ",", "gammas", ",", "schedule", ")", ":", "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", ">=", "step", ")", ":", "lr", "=", "lr", "*", "gamma", "else", ":", "break", "for", "param_group", "in", "optimizer", ".", "param_groups", ":", "param_group", "[", "'lr'", "]", "=", "lr", "return", "lr" ]
Sets the learning rate to the initial LR decayed by 10 every 30 epochs
[ "Sets", "the", "learning", "rate", "to", "the", "initial", "LR", "decayed", "by", "10", "every", "30", "epochs" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/models/cifar10/main_dxy.py#L254-L265
train
fastai/fastai
old/fastai/learner.py
Learner.fit_gen
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_eval_freq=5, **kwargs): """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 'cycle_len', 'cycle_mult', and 'n_cycle' parameters. Args: model (Learner): Any neural architecture for solving a supported problem. Eg. ResNet-34, RNN_Learner etc. data (ModelData): An instance of ModelData. layer_opt (LayerOptimizer): An instance of the LayerOptimizer class n_cycle (int): number of cycles cycle_len (int): number of epochs before lr is reset to the initial value. E.g if cycle_len = 3, then the lr is varied between a maximum and minimum value over 3 epochs. cycle_mult (int): additional parameter for influencing how the lr resets over the cycles. For an intuitive explanation, please see https://github.com/fastai/fastai/blob/master/courses/dl1/lesson1.ipynb cycle_save_name (str): use to save the weights at end of each cycle (requires use_clr, use_clr_beta or cycle_len arg) best_save_name (str): use to save weights of best model during training. metrics (function): some function for evaluating a desired metric. Eg. accuracy. callbacks (list(Callback)): callbacks to apply during the training. use_wd_sched (bool, optional): set to True to enable weight regularization using the technique mentioned in https://arxiv.org/abs/1711.05101. When this is True alone (see below), the regularization is detached from gradient update and applied directly to the weights. norm_wds (bool, optional): when this is set to True along with use_wd_sched, the regularization factor is normalized with each training cycle. wds_sched_mult (function, optional): when this is provided along with use_wd_sched as True, the value computed by this function is multiplied with the regularization strength. This function is passed the WeightDecaySchedule object. And example function that can be passed is: f = lambda x: np.array(x.layer_opt.lrs) / x.init_lrs use_swa (bool, optional): when this is set to True, it will enable the use of Stochastic Weight Averaging (https://arxiv.org/abs/1803.05407). The learner will include an additional model (in the swa_model attribute) for keeping track of the average weights as described in the paper. All testing of this technique so far has been in image classification, so use in other contexts is not guaranteed to work. swa_start (int, optional): if use_swa is set to True, then this determines the epoch to start keeping track of the average weights. It is 1-indexed per the paper's conventions. swa_eval_freq (int, optional): if use_swa is set to True, this determines the frequency at which to evaluate the performance of the swa_model. This evaluation can be costly for models using BatchNorm (requiring a full pass through the data), which is why the default is not to evaluate after each epoch. Returns: None """ if cycle_save_name: assert use_clr or use_clr_beta or cycle_len, "cycle_save_name argument requires either of the following arguments use_clr, use_clr_beta, cycle_len" if callbacks is None: callbacks=[] if metrics is None: metrics=self.metrics if use_wd_sched: # This needs to come before CosAnneal() because we need to read the initial learning rate from # layer_opt.lrs - but CosAnneal() alters the layer_opt.lrs value initially (divides by 100) if np.sum(layer_opt.wds) == 0: print('fit() warning: use_wd_sched is set to True, but weight decay(s) passed are 0. Use wds to ' 'pass weight decay values.') batch_per_epoch = len(data.trn_dl) cl = cycle_len if cycle_len else 1 self.wd_sched = WeightDecaySchedule(layer_opt, batch_per_epoch, cl, cycle_mult, n_cycle, norm_wds, wds_sched_mult) callbacks += [self.wd_sched] if use_clr is not None: clr_div,cut_div = use_clr[:2] moms = use_clr[2:] if len(use_clr) > 2 else None cycle_end = self.get_cycle_end(cycle_save_name) assert cycle_len, "use_clr requires cycle_len arg" self.sched = CircularLR(layer_opt, len(data.trn_dl)*cycle_len, on_cycle_end=cycle_end, div=clr_div, cut_div=cut_div, momentums=moms) elif use_clr_beta is not None: div,pct = use_clr_beta[:2] moms = use_clr_beta[2:] if len(use_clr_beta) > 3 else None cycle_end = self.get_cycle_end(cycle_save_name) assert cycle_len, "use_clr_beta requires cycle_len arg" self.sched = CircularLR_beta(layer_opt, len(data.trn_dl)*cycle_len, on_cycle_end=cycle_end, div=div, pct=pct, momentums=moms) elif cycle_len: cycle_end = self.get_cycle_end(cycle_save_name) cycle_batches = len(data.trn_dl)*cycle_len self.sched = CosAnneal(layer_opt, cycle_batches, on_cycle_end=cycle_end, cycle_mult=cycle_mult) elif not self.sched: self.sched=LossRecorder(layer_opt) callbacks+=[self.sched] if best_save_name is not None: callbacks+=[SaveBestModel(self, layer_opt, metrics, best_save_name)] if use_swa: # make a copy of the model to track average weights self.swa_model = copy.deepcopy(model) callbacks+=[SWA(model, self.swa_model, swa_start)] n_epoch = int(sum_geom(cycle_len if cycle_len else 1, cycle_mult, n_cycle)) return fit(model, data, n_epoch, layer_opt.opt, self.crit, metrics=metrics, callbacks=callbacks, reg_fn=self.reg_fn, clip=self.clip, fp16=self.fp16, swa_model=self.swa_model if use_swa else None, swa_start=swa_start, swa_eval_freq=swa_eval_freq, **kwargs)
python
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_eval_freq=5, **kwargs): """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 'cycle_len', 'cycle_mult', and 'n_cycle' parameters. Args: model (Learner): Any neural architecture for solving a supported problem. Eg. ResNet-34, RNN_Learner etc. data (ModelData): An instance of ModelData. layer_opt (LayerOptimizer): An instance of the LayerOptimizer class n_cycle (int): number of cycles cycle_len (int): number of epochs before lr is reset to the initial value. E.g if cycle_len = 3, then the lr is varied between a maximum and minimum value over 3 epochs. cycle_mult (int): additional parameter for influencing how the lr resets over the cycles. For an intuitive explanation, please see https://github.com/fastai/fastai/blob/master/courses/dl1/lesson1.ipynb cycle_save_name (str): use to save the weights at end of each cycle (requires use_clr, use_clr_beta or cycle_len arg) best_save_name (str): use to save weights of best model during training. metrics (function): some function for evaluating a desired metric. Eg. accuracy. callbacks (list(Callback)): callbacks to apply during the training. use_wd_sched (bool, optional): set to True to enable weight regularization using the technique mentioned in https://arxiv.org/abs/1711.05101. When this is True alone (see below), the regularization is detached from gradient update and applied directly to the weights. norm_wds (bool, optional): when this is set to True along with use_wd_sched, the regularization factor is normalized with each training cycle. wds_sched_mult (function, optional): when this is provided along with use_wd_sched as True, the value computed by this function is multiplied with the regularization strength. This function is passed the WeightDecaySchedule object. And example function that can be passed is: f = lambda x: np.array(x.layer_opt.lrs) / x.init_lrs use_swa (bool, optional): when this is set to True, it will enable the use of Stochastic Weight Averaging (https://arxiv.org/abs/1803.05407). The learner will include an additional model (in the swa_model attribute) for keeping track of the average weights as described in the paper. All testing of this technique so far has been in image classification, so use in other contexts is not guaranteed to work. swa_start (int, optional): if use_swa is set to True, then this determines the epoch to start keeping track of the average weights. It is 1-indexed per the paper's conventions. swa_eval_freq (int, optional): if use_swa is set to True, this determines the frequency at which to evaluate the performance of the swa_model. This evaluation can be costly for models using BatchNorm (requiring a full pass through the data), which is why the default is not to evaluate after each epoch. Returns: None """ if cycle_save_name: assert use_clr or use_clr_beta or cycle_len, "cycle_save_name argument requires either of the following arguments use_clr, use_clr_beta, cycle_len" if callbacks is None: callbacks=[] if metrics is None: metrics=self.metrics if use_wd_sched: # This needs to come before CosAnneal() because we need to read the initial learning rate from # layer_opt.lrs - but CosAnneal() alters the layer_opt.lrs value initially (divides by 100) if np.sum(layer_opt.wds) == 0: print('fit() warning: use_wd_sched is set to True, but weight decay(s) passed are 0. Use wds to ' 'pass weight decay values.') batch_per_epoch = len(data.trn_dl) cl = cycle_len if cycle_len else 1 self.wd_sched = WeightDecaySchedule(layer_opt, batch_per_epoch, cl, cycle_mult, n_cycle, norm_wds, wds_sched_mult) callbacks += [self.wd_sched] if use_clr is not None: clr_div,cut_div = use_clr[:2] moms = use_clr[2:] if len(use_clr) > 2 else None cycle_end = self.get_cycle_end(cycle_save_name) assert cycle_len, "use_clr requires cycle_len arg" self.sched = CircularLR(layer_opt, len(data.trn_dl)*cycle_len, on_cycle_end=cycle_end, div=clr_div, cut_div=cut_div, momentums=moms) elif use_clr_beta is not None: div,pct = use_clr_beta[:2] moms = use_clr_beta[2:] if len(use_clr_beta) > 3 else None cycle_end = self.get_cycle_end(cycle_save_name) assert cycle_len, "use_clr_beta requires cycle_len arg" self.sched = CircularLR_beta(layer_opt, len(data.trn_dl)*cycle_len, on_cycle_end=cycle_end, div=div, pct=pct, momentums=moms) elif cycle_len: cycle_end = self.get_cycle_end(cycle_save_name) cycle_batches = len(data.trn_dl)*cycle_len self.sched = CosAnneal(layer_opt, cycle_batches, on_cycle_end=cycle_end, cycle_mult=cycle_mult) elif not self.sched: self.sched=LossRecorder(layer_opt) callbacks+=[self.sched] if best_save_name is not None: callbacks+=[SaveBestModel(self, layer_opt, metrics, best_save_name)] if use_swa: # make a copy of the model to track average weights self.swa_model = copy.deepcopy(model) callbacks+=[SWA(model, self.swa_model, swa_start)] n_epoch = int(sum_geom(cycle_len if cycle_len else 1, cycle_mult, n_cycle)) return fit(model, data, n_epoch, layer_opt.opt, self.crit, metrics=metrics, callbacks=callbacks, reg_fn=self.reg_fn, clip=self.clip, fp16=self.fp16, swa_model=self.swa_model if use_swa else None, swa_start=swa_start, swa_eval_freq=swa_eval_freq, **kwargs)
[ "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_eval_freq", "=", "5", ",", "*", "*", "kwargs", ")", ":", "if", "cycle_save_name", ":", "assert", "use_clr", "or", "use_clr_beta", "or", "cycle_len", ",", "\"cycle_save_name argument requires either of the following arguments use_clr, use_clr_beta, cycle_len\"", "if", "callbacks", "is", "None", ":", "callbacks", "=", "[", "]", "if", "metrics", "is", "None", ":", "metrics", "=", "self", ".", "metrics", "if", "use_wd_sched", ":", "# This needs to come before CosAnneal() because we need to read the initial learning rate from", "# layer_opt.lrs - but CosAnneal() alters the layer_opt.lrs value initially (divides by 100)", "if", "np", ".", "sum", "(", "layer_opt", ".", "wds", ")", "==", "0", ":", "print", "(", "'fit() warning: use_wd_sched is set to True, but weight decay(s) passed are 0. Use wds to '", "'pass weight decay values.'", ")", "batch_per_epoch", "=", "len", "(", "data", ".", "trn_dl", ")", "cl", "=", "cycle_len", "if", "cycle_len", "else", "1", "self", ".", "wd_sched", "=", "WeightDecaySchedule", "(", "layer_opt", ",", "batch_per_epoch", ",", "cl", ",", "cycle_mult", ",", "n_cycle", ",", "norm_wds", ",", "wds_sched_mult", ")", "callbacks", "+=", "[", "self", ".", "wd_sched", "]", "if", "use_clr", "is", "not", "None", ":", "clr_div", ",", "cut_div", "=", "use_clr", "[", ":", "2", "]", "moms", "=", "use_clr", "[", "2", ":", "]", "if", "len", "(", "use_clr", ")", ">", "2", "else", "None", "cycle_end", "=", "self", ".", "get_cycle_end", "(", "cycle_save_name", ")", "assert", "cycle_len", ",", "\"use_clr requires cycle_len arg\"", "self", ".", "sched", "=", "CircularLR", "(", "layer_opt", ",", "len", "(", "data", ".", "trn_dl", ")", "*", "cycle_len", ",", "on_cycle_end", "=", "cycle_end", ",", "div", "=", "clr_div", ",", "cut_div", "=", "cut_div", ",", "momentums", "=", "moms", ")", "elif", "use_clr_beta", "is", "not", "None", ":", "div", ",", "pct", "=", "use_clr_beta", "[", ":", "2", "]", "moms", "=", "use_clr_beta", "[", "2", ":", "]", "if", "len", "(", "use_clr_beta", ")", ">", "3", "else", "None", "cycle_end", "=", "self", ".", "get_cycle_end", "(", "cycle_save_name", ")", "assert", "cycle_len", ",", "\"use_clr_beta requires cycle_len arg\"", "self", ".", "sched", "=", "CircularLR_beta", "(", "layer_opt", ",", "len", "(", "data", ".", "trn_dl", ")", "*", "cycle_len", ",", "on_cycle_end", "=", "cycle_end", ",", "div", "=", "div", ",", "pct", "=", "pct", ",", "momentums", "=", "moms", ")", "elif", "cycle_len", ":", "cycle_end", "=", "self", ".", "get_cycle_end", "(", "cycle_save_name", ")", "cycle_batches", "=", "len", "(", "data", ".", "trn_dl", ")", "*", "cycle_len", "self", ".", "sched", "=", "CosAnneal", "(", "layer_opt", ",", "cycle_batches", ",", "on_cycle_end", "=", "cycle_end", ",", "cycle_mult", "=", "cycle_mult", ")", "elif", "not", "self", ".", "sched", ":", "self", ".", "sched", "=", "LossRecorder", "(", "layer_opt", ")", "callbacks", "+=", "[", "self", ".", "sched", "]", "if", "best_save_name", "is", "not", "None", ":", "callbacks", "+=", "[", "SaveBestModel", "(", "self", ",", "layer_opt", ",", "metrics", ",", "best_save_name", ")", "]", "if", "use_swa", ":", "# make a copy of the model to track average weights", "self", ".", "swa_model", "=", "copy", ".", "deepcopy", "(", "model", ")", "callbacks", "+=", "[", "SWA", "(", "model", ",", "self", ".", "swa_model", ",", "swa_start", ")", "]", "n_epoch", "=", "int", "(", "sum_geom", "(", "cycle_len", "if", "cycle_len", "else", "1", ",", "cycle_mult", ",", "n_cycle", ")", ")", "return", "fit", "(", "model", ",", "data", ",", "n_epoch", ",", "layer_opt", ".", "opt", ",", "self", ".", "crit", ",", "metrics", "=", "metrics", ",", "callbacks", "=", "callbacks", ",", "reg_fn", "=", "self", ".", "reg_fn", ",", "clip", "=", "self", ".", "clip", ",", "fp16", "=", "self", ".", "fp16", ",", "swa_model", "=", "self", ".", "swa_model", "if", "use_swa", "else", "None", ",", "swa_start", "=", "swa_start", ",", "swa_eval_freq", "=", "swa_eval_freq", ",", "*", "*", "kwargs", ")" ]
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 'cycle_len', 'cycle_mult', and 'n_cycle' parameters. Args: model (Learner): Any neural architecture for solving a supported problem. Eg. ResNet-34, RNN_Learner etc. data (ModelData): An instance of ModelData. layer_opt (LayerOptimizer): An instance of the LayerOptimizer class n_cycle (int): number of cycles cycle_len (int): number of epochs before lr is reset to the initial value. E.g if cycle_len = 3, then the lr is varied between a maximum and minimum value over 3 epochs. cycle_mult (int): additional parameter for influencing how the lr resets over the cycles. For an intuitive explanation, please see https://github.com/fastai/fastai/blob/master/courses/dl1/lesson1.ipynb cycle_save_name (str): use to save the weights at end of each cycle (requires use_clr, use_clr_beta or cycle_len arg) best_save_name (str): use to save weights of best model during training. metrics (function): some function for evaluating a desired metric. Eg. accuracy. callbacks (list(Callback)): callbacks to apply during the training. use_wd_sched (bool, optional): set to True to enable weight regularization using the technique mentioned in https://arxiv.org/abs/1711.05101. When this is True alone (see below), the regularization is detached from gradient update and applied directly to the weights. norm_wds (bool, optional): when this is set to True along with use_wd_sched, the regularization factor is normalized with each training cycle. wds_sched_mult (function, optional): when this is provided along with use_wd_sched as True, the value computed by this function is multiplied with the regularization strength. This function is passed the WeightDecaySchedule object. And example function that can be passed is: f = lambda x: np.array(x.layer_opt.lrs) / x.init_lrs use_swa (bool, optional): when this is set to True, it will enable the use of Stochastic Weight Averaging (https://arxiv.org/abs/1803.05407). The learner will include an additional model (in the swa_model attribute) for keeping track of the average weights as described in the paper. All testing of this technique so far has been in image classification, so use in other contexts is not guaranteed to work. swa_start (int, optional): if use_swa is set to True, then this determines the epoch to start keeping track of the average weights. It is 1-indexed per the paper's conventions. swa_eval_freq (int, optional): if use_swa is set to True, this determines the frequency at which to evaluate the performance of the swa_model. This evaluation can be costly for models using BatchNorm (requiring a full pass through the data), which is why the default is not to evaluate after each epoch. Returns: None
[ "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", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L127-L249
train
fastai/fastai
old/fastai/learner.py
Learner.get_layer_opt
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 differential learning rates and weight decays is seen in ../.../courses/dl1/fastai/conv_learner.py, using the dict 'model_meta'. Currently, this seems supported only for convolutional networks such as VGG-19, ResNet-XX etc. Args: lrs (float or list(float)): learning rate(s) for the model wds (float or list(float)): weight decay parameter(s). Returns: An instance of a LayerOptimizer """ return LayerOptimizer(self.opt_fn, self.get_layer_groups(), lrs, wds)
python
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 differential learning rates and weight decays is seen in ../.../courses/dl1/fastai/conv_learner.py, using the dict 'model_meta'. Currently, this seems supported only for convolutional networks such as VGG-19, ResNet-XX etc. Args: lrs (float or list(float)): learning rate(s) for the model wds (float or list(float)): weight decay parameter(s). Returns: An instance of a LayerOptimizer """ return LayerOptimizer(self.opt_fn, self.get_layer_groups(), lrs, wds)
[ "def", "get_layer_opt", "(", "self", ",", "lrs", ",", "wds", ")", ":", "return", "LayerOptimizer", "(", "self", ".", "opt_fn", ",", "self", ".", "get_layer_groups", "(", ")", ",", "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 differential learning rates and weight decays is seen in ../.../courses/dl1/fastai/conv_learner.py, using the dict 'model_meta'. Currently, this seems supported only for convolutional networks such as VGG-19, ResNet-XX etc. Args: lrs (float or list(float)): learning rate(s) for the model wds (float or list(float)): weight decay parameter(s). Returns: An instance of a LayerOptimizer
[ "Method", "returns", "an", "instance", "of", "the", "LayerOptimizer", "class", "which", "allows", "for", "setting", "differential", "learning", "rates", "for", "different", "parts", "of", "the", "model", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L253-L273
train
fastai/fastai
old/fastai/learner.py
Learner.fit
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 mostly relevant to ImageNet-trained models, where we want to alter the layers closest to the images by much smaller amounts. Likewise, a single or list of weight decay parameters can be specified, which if appropriate for a model, will apply variable weight decay parameters to different segments of the model. Args: lrs (float or list(float)): learning rate for the model n_cycle (int): number of cycles (or iterations) to fit the model for wds (float or list(float)): weight decay parameter(s). kwargs: other arguments Returns: None """ self.sched = None layer_opt = self.get_layer_opt(lrs, wds) return self.fit_gen(self.model, self.data, layer_opt, n_cycle, **kwargs)
python
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 mostly relevant to ImageNet-trained models, where we want to alter the layers closest to the images by much smaller amounts. Likewise, a single or list of weight decay parameters can be specified, which if appropriate for a model, will apply variable weight decay parameters to different segments of the model. Args: lrs (float or list(float)): learning rate for the model n_cycle (int): number of cycles (or iterations) to fit the model for wds (float or list(float)): weight decay parameter(s). kwargs: other arguments Returns: None """ self.sched = None layer_opt = self.get_layer_opt(lrs, wds) return self.fit_gen(self.model, self.data, layer_opt, n_cycle, **kwargs)
[ "def", "fit", "(", "self", ",", "lrs", ",", "n_cycle", ",", "wds", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "sched", "=", "None", "layer_opt", "=", "self", ".", "get_layer_opt", "(", "lrs", ",", "wds", ")", "return", "self", ".", "fit_gen", "(", "self", ".", "model", ",", "self", ".", "data", ",", "layer_opt", ",", "n_cycle", ",", "*", "*", "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 mostly relevant to ImageNet-trained models, where we want to alter the layers closest to the images by much smaller amounts. Likewise, a single or list of weight decay parameters can be specified, which if appropriate for a model, will apply variable weight decay parameters to different segments of the model. Args: lrs (float or list(float)): learning rate for the model n_cycle (int): number of cycles (or iterations) to fit the model for wds (float or list(float)): weight decay parameter(s). kwargs: other arguments Returns: None
[ "Method", "gets", "an", "instance", "of", "LayerOptimizer", "and", "delegates", "to", "self", ".", "fit_gen", "(", "..", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L275-L302
train
fastai/fastai
old/fastai/learner.py
Learner.lr_find
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 learning rate from a very small value, until the loss starts decreasing. Args: start_lr (float/numpy array) : Passing in a numpy array allows you to specify learning rates for a learner's layer_groups end_lr (float) : The maximum learning rate to try. wds (iterable/float) Examples: As training moves us closer to the optimal weights for a model, the optimal learning rate will be smaller. We can take advantage of that knowledge and provide lr_find() with a starting learning rate 1000x smaller than the model's current learning rate as such: >> learn.lr_find(lr/1000) >> lrs = np.array([ 1e-4, 1e-3, 1e-2 ]) >> learn.lr_find(lrs / 1000) Notes: lr_find() may finish before going through each batch of examples if the loss decreases enough. .. _Cyclical Learning Rates for Training Neural Networks: http://arxiv.org/abs/1506.01186 """ self.save('tmp') layer_opt = self.get_layer_opt(start_lr, wds) self.sched = LR_Finder(layer_opt, len(self.data.trn_dl), end_lr, linear=linear) self.fit_gen(self.model, self.data, layer_opt, 1, **kwargs) self.load('tmp')
python
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 learning rate from a very small value, until the loss starts decreasing. Args: start_lr (float/numpy array) : Passing in a numpy array allows you to specify learning rates for a learner's layer_groups end_lr (float) : The maximum learning rate to try. wds (iterable/float) Examples: As training moves us closer to the optimal weights for a model, the optimal learning rate will be smaller. We can take advantage of that knowledge and provide lr_find() with a starting learning rate 1000x smaller than the model's current learning rate as such: >> learn.lr_find(lr/1000) >> lrs = np.array([ 1e-4, 1e-3, 1e-2 ]) >> learn.lr_find(lrs / 1000) Notes: lr_find() may finish before going through each batch of examples if the loss decreases enough. .. _Cyclical Learning Rates for Training Neural Networks: http://arxiv.org/abs/1506.01186 """ self.save('tmp') layer_opt = self.get_layer_opt(start_lr, wds) self.sched = LR_Finder(layer_opt, len(self.data.trn_dl), end_lr, linear=linear) self.fit_gen(self.model, self.data, layer_opt, 1, **kwargs) self.load('tmp')
[ "def", "lr_find", "(", "self", ",", "start_lr", "=", "1e-5", ",", "end_lr", "=", "10", ",", "wds", "=", "None", ",", "linear", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "save", "(", "'tmp'", ")", "layer_opt", "=", "self", ".", "get_layer_opt", "(", "start_lr", ",", "wds", ")", "self", ".", "sched", "=", "LR_Finder", "(", "layer_opt", ",", "len", "(", "self", ".", "data", ".", "trn_dl", ")", ",", "end_lr", ",", "linear", "=", "linear", ")", "self", ".", "fit_gen", "(", "self", ".", "model", ",", "self", ".", "data", ",", "layer_opt", ",", "1", ",", "*", "*", "kwargs", ")", "self", ".", "load", "(", "'tmp'", ")" ]
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: start_lr (float/numpy array) : Passing in a numpy array allows you to specify learning rates for a learner's layer_groups end_lr (float) : The maximum learning rate to try. wds (iterable/float) Examples: As training moves us closer to the optimal weights for a model, the optimal learning rate will be smaller. We can take advantage of that knowledge and provide lr_find() with a starting learning rate 1000x smaller than the model's current learning rate as such: >> learn.lr_find(lr/1000) >> lrs = np.array([ 1e-4, 1e-3, 1e-2 ]) >> learn.lr_find(lrs / 1000) Notes: lr_find() may finish before going through each batch of examples if the loss decreases enough. .. _Cyclical Learning Rates for Training Neural Networks: http://arxiv.org/abs/1506.01186
[ "Helps", "you", "find", "an", "optimal", "learning", "rate", "for", "a", "model", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L309-L346
train
fastai/fastai
old/fastai/learner.py
Learner.lr_find2
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). At each step, it computes the validation loss and the metrics on the next batch of the validation data, so it's slower than lr_find(). Args: start_lr (float/numpy array) : Passing in a numpy array allows you to specify learning rates for a learner's layer_groups end_lr (float) : The maximum learning rate to try. num_it : the number of iterations you want it to run wds (iterable/float) stop_dv : stops (or not) when the losses starts to explode. """ self.save('tmp') layer_opt = self.get_layer_opt(start_lr, wds) self.sched = LR_Finder2(layer_opt, num_it, end_lr, linear=linear, metrics=self.metrics, stop_dv=stop_dv) self.fit_gen(self.model, self.data, layer_opt, num_it//len(self.data.trn_dl) + 1, all_val=True, **kwargs) self.load('tmp')
python
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). At each step, it computes the validation loss and the metrics on the next batch of the validation data, so it's slower than lr_find(). Args: start_lr (float/numpy array) : Passing in a numpy array allows you to specify learning rates for a learner's layer_groups end_lr (float) : The maximum learning rate to try. num_it : the number of iterations you want it to run wds (iterable/float) stop_dv : stops (or not) when the losses starts to explode. """ self.save('tmp') layer_opt = self.get_layer_opt(start_lr, wds) self.sched = LR_Finder2(layer_opt, num_it, end_lr, linear=linear, metrics=self.metrics, stop_dv=stop_dv) self.fit_gen(self.model, self.data, layer_opt, num_it//len(self.data.trn_dl) + 1, all_val=True, **kwargs) self.load('tmp')
[ "def", "lr_find2", "(", "self", ",", "start_lr", "=", "1e-5", ",", "end_lr", "=", "10", ",", "num_it", "=", "100", ",", "wds", "=", "None", ",", "linear", "=", "False", ",", "stop_dv", "=", "True", ",", "*", "*", "kwargs", ")", ":", "self", ".", "save", "(", "'tmp'", ")", "layer_opt", "=", "self", ".", "get_layer_opt", "(", "start_lr", ",", "wds", ")", "self", ".", "sched", "=", "LR_Finder2", "(", "layer_opt", ",", "num_it", ",", "end_lr", ",", "linear", "=", "linear", ",", "metrics", "=", "self", ".", "metrics", ",", "stop_dv", "=", "stop_dv", ")", "self", ".", "fit_gen", "(", "self", ".", "model", ",", "self", ".", "data", ",", "layer_opt", ",", "num_it", "//", "len", "(", "self", ".", "data", ".", "trn_dl", ")", "+", "1", ",", "all_val", "=", "True", ",", "*", "*", "kwargs", ")", "self", ".", "load", "(", "'tmp'", ")" ]
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 it's slower than lr_find(). Args: start_lr (float/numpy array) : Passing in a numpy array allows you to specify learning rates for a learner's layer_groups end_lr (float) : The maximum learning rate to try. num_it : the number of iterations you want it to run wds (iterable/float) stop_dv : stops (or not) when the losses starts to explode.
[ "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", "it", "s", "slower", "than", "lr_find", "()", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L348-L367
train
fastai/fastai
old/fastai/learner.py
Learner.predict_array
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 array') self.model.eval() return to_np(self.model(to_gpu(V(T(arr)))))
python
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 array') self.model.eval() return to_np(self.model(to_gpu(V(T(arr)))))
[ "def", "predict_array", "(", "self", ",", "arr", ")", ":", "if", "not", "isinstance", "(", "arr", ",", "np", ".", "ndarray", ")", ":", "raise", "OSError", "(", "f'Not valid numpy array'", ")", "self", ".", "model", ".", "eval", "(", ")", "return", "to_np", "(", "self", ".", "model", "(", "to_gpu", "(", "V", "(", "T", "(", "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
[ "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" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L381-L390
train
fastai/fastai
old/fastai/learner.py
Learner.TTA
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 predictions by examining the images using multiple perspectives. n_aug: a number of augmentation images to use per original image is_test: indicate to use test images; otherwise use validation images Returns: (tuple): a tuple containing: log predictions (numpy.ndarray): log predictions (i.e. `np.exp(log_preds)` will return probabilities) targs (numpy.ndarray): target values when `is_test==False`; zeros otherwise. """ dl1 = self.data.test_dl if is_test else self.data.val_dl dl2 = self.data.test_aug_dl if is_test else self.data.aug_dl preds1,targs = predict_with_targs(self.model, dl1) preds1 = [preds1]*math.ceil(n_aug/4) preds2 = [predict_with_targs(self.model, dl2)[0] for i in tqdm(range(n_aug), leave=False)] return np.stack(preds1+preds2), targs
python
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 predictions by examining the images using multiple perspectives. n_aug: a number of augmentation images to use per original image is_test: indicate to use test images; otherwise use validation images Returns: (tuple): a tuple containing: log predictions (numpy.ndarray): log predictions (i.e. `np.exp(log_preds)` will return probabilities) targs (numpy.ndarray): target values when `is_test==False`; zeros otherwise. """ dl1 = self.data.test_dl if is_test else self.data.val_dl dl2 = self.data.test_aug_dl if is_test else self.data.aug_dl preds1,targs = predict_with_targs(self.model, dl1) preds1 = [preds1]*math.ceil(n_aug/4) preds2 = [predict_with_targs(self.model, dl2)[0] for i in tqdm(range(n_aug), leave=False)] return np.stack(preds1+preds2), targs
[ "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_aug_dl", "if", "is_test", "else", "self", ".", "data", ".", "aug_dl", "preds1", ",", "targs", "=", "predict_with_targs", "(", "self", ".", "model", ",", "dl1", ")", "preds1", "=", "[", "preds1", "]", "*", "math", ".", "ceil", "(", "n_aug", "/", "4", ")", "preds2", "=", "[", "predict_with_targs", "(", "self", ".", "model", ",", "dl2", ")", "[", "0", "]", "for", "i", "in", "tqdm", "(", "range", "(", "n_aug", ")", ",", "leave", "=", "False", ")", "]", "return", "np", ".", "stack", "(", "preds1", "+", "preds2", ")", ",", "targs" ]
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 perspectives. n_aug: a number of augmentation images to use per original image is_test: indicate to use test images; otherwise use validation images Returns: (tuple): a tuple containing: log predictions (numpy.ndarray): log predictions (i.e. `np.exp(log_preds)` will return probabilities) targs (numpy.ndarray): target values when `is_test==False`; zeros otherwise.
[ "Predict", "with", "Test", "Time", "Augmentation", "(", "TTA", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L392-L415
train
fastai/fastai
old/fastai/learner.py
Learner.fit_opt_sched
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 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 (to change the size for instance) for each of these groups. Args: phases: a list of TrainingPhase objects stop_div: when True, stops the training if the loss goes too high data_list: a list of different Data objects. kwargs: other arguments use_swa (bool, optional): when this is set to True, it will enable the use of Stochastic Weight Averaging (https://arxiv.org/abs/1803.05407). The learner will include an additional model (in the swa_model attribute) for keeping track of the average weights as described in the paper. All testing of this technique so far has been in image classification, so use in other contexts is not guaranteed to work. swa_start (int, optional): if use_swa is set to True, then this determines the epoch to start keeping track of the average weights. It is 1-indexed per the paper's conventions. swa_eval_freq (int, optional): if use_swa is set to True, this determines the frequency at which to evaluate the performance of the swa_model. This evaluation can be costly for models using BatchNorm (requiring a full pass through the data), which is why the default is not to evaluate after each epoch. Returns: None """ if data_list is None: data_list=[] if callbacks is None: callbacks=[] layer_opt = LayerOptimizer(phases[0].opt_fn, self.get_layer_groups(), 1e-2, phases[0].wds) if len(data_list) == 0: nb_batches = [len(self.data.trn_dl)] * len(phases) else: nb_batches = [len(data.trn_dl) for data in data_list] self.sched = OptimScheduler(layer_opt, phases, nb_batches, stop_div) callbacks.append(self.sched) metrics = self.metrics if best_save_name is not None: callbacks+=[SaveBestModel(self, layer_opt, metrics, best_save_name)] if use_swa: # make a copy of the model to track average weights self.swa_model = copy.deepcopy(self.model) callbacks+=[SWA(self.model, self.swa_model, swa_start)] n_epochs = [phase.epochs for phase in phases] if cut is None else cut if len(data_list)==0: data_list = [self.data] return fit(self.model, data_list, n_epochs,layer_opt, self.crit, metrics=metrics, callbacks=callbacks, reg_fn=self.reg_fn, clip=self.clip, fp16=self.fp16, swa_model=self.swa_model if use_swa else None, swa_start=swa_start, swa_eval_freq=swa_eval_freq, **kwargs)
python
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 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 (to change the size for instance) for each of these groups. Args: phases: a list of TrainingPhase objects stop_div: when True, stops the training if the loss goes too high data_list: a list of different Data objects. kwargs: other arguments use_swa (bool, optional): when this is set to True, it will enable the use of Stochastic Weight Averaging (https://arxiv.org/abs/1803.05407). The learner will include an additional model (in the swa_model attribute) for keeping track of the average weights as described in the paper. All testing of this technique so far has been in image classification, so use in other contexts is not guaranteed to work. swa_start (int, optional): if use_swa is set to True, then this determines the epoch to start keeping track of the average weights. It is 1-indexed per the paper's conventions. swa_eval_freq (int, optional): if use_swa is set to True, this determines the frequency at which to evaluate the performance of the swa_model. This evaluation can be costly for models using BatchNorm (requiring a full pass through the data), which is why the default is not to evaluate after each epoch. Returns: None """ if data_list is None: data_list=[] if callbacks is None: callbacks=[] layer_opt = LayerOptimizer(phases[0].opt_fn, self.get_layer_groups(), 1e-2, phases[0].wds) if len(data_list) == 0: nb_batches = [len(self.data.trn_dl)] * len(phases) else: nb_batches = [len(data.trn_dl) for data in data_list] self.sched = OptimScheduler(layer_opt, phases, nb_batches, stop_div) callbacks.append(self.sched) metrics = self.metrics if best_save_name is not None: callbacks+=[SaveBestModel(self, layer_opt, metrics, best_save_name)] if use_swa: # make a copy of the model to track average weights self.swa_model = copy.deepcopy(self.model) callbacks+=[SWA(self.model, self.swa_model, swa_start)] n_epochs = [phase.epochs for phase in phases] if cut is None else cut if len(data_list)==0: data_list = [self.data] return fit(self.model, data_list, n_epochs,layer_opt, self.crit, metrics=metrics, callbacks=callbacks, reg_fn=self.reg_fn, clip=self.clip, fp16=self.fp16, swa_model=self.swa_model if use_swa else None, swa_start=swa_start, swa_eval_freq=swa_eval_freq, **kwargs)
[ "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", ")", ":", "if", "data_list", "is", "None", ":", "data_list", "=", "[", "]", "if", "callbacks", "is", "None", ":", "callbacks", "=", "[", "]", "layer_opt", "=", "LayerOptimizer", "(", "phases", "[", "0", "]", ".", "opt_fn", ",", "self", ".", "get_layer_groups", "(", ")", ",", "1e-2", ",", "phases", "[", "0", "]", ".", "wds", ")", "if", "len", "(", "data_list", ")", "==", "0", ":", "nb_batches", "=", "[", "len", "(", "self", ".", "data", ".", "trn_dl", ")", "]", "*", "len", "(", "phases", ")", "else", ":", "nb_batches", "=", "[", "len", "(", "data", ".", "trn_dl", ")", "for", "data", "in", "data_list", "]", "self", ".", "sched", "=", "OptimScheduler", "(", "layer_opt", ",", "phases", ",", "nb_batches", ",", "stop_div", ")", "callbacks", ".", "append", "(", "self", ".", "sched", ")", "metrics", "=", "self", ".", "metrics", "if", "best_save_name", "is", "not", "None", ":", "callbacks", "+=", "[", "SaveBestModel", "(", "self", ",", "layer_opt", ",", "metrics", ",", "best_save_name", ")", "]", "if", "use_swa", ":", "# make a copy of the model to track average weights", "self", ".", "swa_model", "=", "copy", ".", "deepcopy", "(", "self", ".", "model", ")", "callbacks", "+=", "[", "SWA", "(", "self", ".", "model", ",", "self", ".", "swa_model", ",", "swa_start", ")", "]", "n_epochs", "=", "[", "phase", ".", "epochs", "for", "phase", "in", "phases", "]", "if", "cut", "is", "None", "else", "cut", "if", "len", "(", "data_list", ")", "==", "0", ":", "data_list", "=", "[", "self", ".", "data", "]", "return", "fit", "(", "self", ".", "model", ",", "data_list", ",", "n_epochs", ",", "layer_opt", ",", "self", ".", "crit", ",", "metrics", "=", "metrics", ",", "callbacks", "=", "callbacks", ",", "reg_fn", "=", "self", ".", "reg_fn", ",", "clip", "=", "self", ".", "clip", ",", "fp16", "=", "self", ".", "fp16", ",", "swa_model", "=", "self", ".", "swa_model", "if", "use_swa", "else", "None", ",", "swa_start", "=", "swa_start", ",", "swa_eval_freq", "=", "swa_eval_freq", ",", "*", "*", "kwargs", ")" ]
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 (to change the size for instance) for each of these groups. Args: phases: a list of TrainingPhase objects stop_div: when True, stops the training if the loss goes too high data_list: a list of different Data objects. kwargs: other arguments use_swa (bool, optional): when this is set to True, it will enable the use of Stochastic Weight Averaging (https://arxiv.org/abs/1803.05407). The learner will include an additional model (in the swa_model attribute) for keeping track of the average weights as described in the paper. All testing of this technique so far has been in image classification, so use in other contexts is not guaranteed to work. swa_start (int, optional): if use_swa is set to True, then this determines the epoch to start keeping track of the average weights. It is 1-indexed per the paper's conventions. swa_eval_freq (int, optional): if use_swa is set to True, this determines the frequency at which to evaluate the performance of the swa_model. This evaluation can be costly for models using BatchNorm (requiring a full pass through the data), which is why the default is not to evaluate after each epoch. Returns: None
[ "Wraps", "us", "the", "content", "of", "phases", "to", "send", "them", "to", "model", ".", "fit", "(", "..", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L417-L466
train
fastai/fastai
fastai/callbacks/rnn.py
RNNTrainer.on_loss_begin
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]}
python
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", ")", ":", "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.
[ "Save", "the", "extra", "outputs", "for", "later", "and", "only", "returns", "the", "true", "output", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/rnn.py#L19-L22
train
fastai/fastai
fastai/callbacks/rnn.py
RNNTrainer.on_backward_begin
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: last_loss += self.beta * (h[:,1:] - h[:,:-1]).float().pow(2).mean() return {'last_loss': last_loss}
python
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: last_loss += self.beta * (h[:,1:] - h[:,:-1]).float().pow(2).mean() return {'last_loss': last_loss}
[ "def", "on_backward_begin", "(", "self", ",", "last_loss", ":", "Rank0Tensor", ",", "last_input", ":", "Tensor", ",", "*", "*", "kwargs", ")", ":", "#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", ":", "last_loss", "+=", "self", ".", "beta", "*", "(", "h", "[", ":", ",", "1", ":", "]", "-", "h", "[", ":", ",", ":", "-", "1", "]", ")", ".", "float", "(", ")", ".", "pow", "(", "2", ")", ".", "mean", "(", ")", "return", "{", "'last_loss'", ":", "last_loss", "}" ]
Apply AR and TAR to `last_loss`.
[ "Apply", "AR", "and", "TAR", "to", "last_loss", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/rnn.py#L24-L31
train
fastai/fastai
fastai/text/learner.py
convert_weights
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.mean(0) new_w = enc_wgts.new_zeros((len(itos_new),enc_wgts.size(1))).zero_() if dec_bias is not None: new_b = dec_bias.new_zeros((len(itos_new),)).zero_() for i,w in enumerate(itos_new): r = stoi_wgts[w] if w in stoi_wgts else -1 new_w[i] = enc_wgts[r] if r>=0 else wgts_m if dec_bias is not None: new_b[i] = dec_bias[r] if r>=0 else bias_m wgts['0.encoder.weight'] = new_w if '0.encoder_dp.emb.weight' in wgts: wgts['0.encoder_dp.emb.weight'] = new_w.clone() wgts['1.decoder.weight'] = new_w.clone() if dec_bias is not None: wgts['1.decoder.bias'] = new_b return wgts
python
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.mean(0) new_w = enc_wgts.new_zeros((len(itos_new),enc_wgts.size(1))).zero_() if dec_bias is not None: new_b = dec_bias.new_zeros((len(itos_new),)).zero_() for i,w in enumerate(itos_new): r = stoi_wgts[w] if w in stoi_wgts else -1 new_w[i] = enc_wgts[r] if r>=0 else wgts_m if dec_bias is not None: new_b[i] = dec_bias[r] if r>=0 else bias_m wgts['0.encoder.weight'] = new_w if '0.encoder_dp.emb.weight' in wgts: wgts['0.encoder_dp.emb.weight'] = new_w.clone() wgts['1.decoder.weight'] = new_w.clone() if dec_bias is not None: wgts['1.decoder.bias'] = new_b return wgts
[ "def", "convert_weights", "(", "wgts", ":", "Weights", ",", "stoi_wgts", ":", "Dict", "[", "str", ",", "int", "]", ",", "itos_new", ":", "Collection", "[", "str", "]", ")", "->", "Weights", ":", "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", ".", "mean", "(", "0", ")", "new_w", "=", "enc_wgts", ".", "new_zeros", "(", "(", "len", "(", "itos_new", ")", ",", "enc_wgts", ".", "size", "(", "1", ")", ")", ")", ".", "zero_", "(", ")", "if", "dec_bias", "is", "not", "None", ":", "new_b", "=", "dec_bias", ".", "new_zeros", "(", "(", "len", "(", "itos_new", ")", ",", ")", ")", ".", "zero_", "(", ")", "for", "i", ",", "w", "in", "enumerate", "(", "itos_new", ")", ":", "r", "=", "stoi_wgts", "[", "w", "]", "if", "w", "in", "stoi_wgts", "else", "-", "1", "new_w", "[", "i", "]", "=", "enc_wgts", "[", "r", "]", "if", "r", ">=", "0", "else", "wgts_m", "if", "dec_bias", "is", "not", "None", ":", "new_b", "[", "i", "]", "=", "dec_bias", "[", "r", "]", "if", "r", ">=", "0", "else", "bias_m", "wgts", "[", "'0.encoder.weight'", "]", "=", "new_w", "if", "'0.encoder_dp.emb.weight'", "in", "wgts", ":", "wgts", "[", "'0.encoder_dp.emb.weight'", "]", "=", "new_w", ".", "clone", "(", ")", "wgts", "[", "'1.decoder.weight'", "]", "=", "new_w", ".", "clone", "(", ")", "if", "dec_bias", "is", "not", "None", ":", "wgts", "[", "'1.decoder.bias'", "]", "=", "new_b", "return", "wgts" ]
Convert the model `wgts` to go with a new vocabulary.
[ "Convert", "the", "model", "wgts", "to", "go", "with", "a", "new", "vocabulary", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L28-L43
train
fastai/fastai
fastai/text/learner.py
get_language_model
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] *= drop_mult tie_weights,output_p,out_bias = map(config.pop, ['tie_weights', 'output_p', 'out_bias']) init = config.pop('init') if 'init' in config else None encoder = arch(vocab_sz, **config) enc = encoder.encoder if tie_weights else None decoder = LinearDecoder(vocab_sz, config[meta['hid_name']], output_p, tie_encoder=enc, bias=out_bias) model = SequentialRNN(encoder, decoder) return model if init is None else model.apply(init)
python
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] *= drop_mult tie_weights,output_p,out_bias = map(config.pop, ['tie_weights', 'output_p', 'out_bias']) init = config.pop('init') if 'init' in config else None encoder = arch(vocab_sz, **config) enc = encoder.encoder if tie_weights else None decoder = LinearDecoder(vocab_sz, config[meta['hid_name']], output_p, tie_encoder=enc, bias=out_bias) model = SequentialRNN(encoder, decoder) return model if init is None else model.apply(init)
[ "def", "get_language_model", "(", "arch", ":", "Callable", ",", "vocab_sz", ":", "int", ",", "config", ":", "dict", "=", "None", ",", "drop_mult", ":", "float", "=", "1.", ")", ":", "meta", "=", "_model_meta", "[", "arch", "]", "config", "=", "ifnone", "(", "config", ",", "meta", "[", "'config_lm'", "]", ".", "copy", "(", ")", ")", "for", "k", "in", "config", ".", "keys", "(", ")", ":", "if", "k", ".", "endswith", "(", "'_p'", ")", ":", "config", "[", "k", "]", "*=", "drop_mult", "tie_weights", ",", "output_p", ",", "out_bias", "=", "map", "(", "config", ".", "pop", ",", "[", "'tie_weights'", ",", "'output_p'", ",", "'out_bias'", "]", ")", "init", "=", "config", ".", "pop", "(", "'init'", ")", "if", "'init'", "in", "config", "else", "None", "encoder", "=", "arch", "(", "vocab_sz", ",", "*", "*", "config", ")", "enc", "=", "encoder", ".", "encoder", "if", "tie_weights", "else", "None", "decoder", "=", "LinearDecoder", "(", "vocab_sz", ",", "config", "[", "meta", "[", "'hid_name'", "]", "]", ",", "output_p", ",", "tie_encoder", "=", "enc", ",", "bias", "=", "out_bias", ")", "model", "=", "SequentialRNN", "(", "encoder", ",", "decoder", ")", "return", "model", "if", "init", "is", "None", "else", "model", ".", "apply", "(", "init", ")" ]
Create a language model from `arch` and its `config`, maybe `pretrained`.
[ "Create", "a", "language", "model", "from", "arch", "and", "its", "config", "maybe", "pretrained", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L187-L199
train
fastai/fastai
fastai/text/learner.py
language_model_learner
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, len(data.vocab.itos), config=config, drop_mult=drop_mult) meta = _model_meta[arch] learn = LanguageLearner(data, model, split_func=meta['split_lm'], **learn_kwargs) if pretrained: if 'url' not in meta: warn("There are no pretrained weights for that architecture yet!") return learn model_path = untar_data(meta['url'], data=False) fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']] learn.load_pretrained(*fnames) learn.freeze() if pretrained_fnames is not None: fnames = [learn.path/learn.model_dir/f'{fn}.{ext}' for fn,ext in zip(pretrained_fnames, ['pth', 'pkl'])] learn.load_pretrained(*fnames) learn.freeze() return learn
python
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, len(data.vocab.itos), config=config, drop_mult=drop_mult) meta = _model_meta[arch] learn = LanguageLearner(data, model, split_func=meta['split_lm'], **learn_kwargs) if pretrained: if 'url' not in meta: warn("There are no pretrained weights for that architecture yet!") return learn model_path = untar_data(meta['url'], data=False) fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']] learn.load_pretrained(*fnames) learn.freeze() if pretrained_fnames is not None: fnames = [learn.path/learn.model_dir/f'{fn}.{ext}' for fn,ext in zip(pretrained_fnames, ['pth', 'pkl'])] learn.load_pretrained(*fnames) learn.freeze() return learn
[ "def", "language_model_learner", "(", "data", ":", "DataBunch", ",", "arch", ",", "config", ":", "dict", "=", "None", ",", "drop_mult", ":", "float", "=", "1.", ",", "pretrained", ":", "bool", "=", "True", ",", "pretrained_fnames", ":", "OptStrTuple", "=", "None", ",", "*", "*", "learn_kwargs", ")", "->", "'LanguageLearner'", ":", "model", "=", "get_language_model", "(", "arch", ",", "len", "(", "data", ".", "vocab", ".", "itos", ")", ",", "config", "=", "config", ",", "drop_mult", "=", "drop_mult", ")", "meta", "=", "_model_meta", "[", "arch", "]", "learn", "=", "LanguageLearner", "(", "data", ",", "model", ",", "split_func", "=", "meta", "[", "'split_lm'", "]", ",", "*", "*", "learn_kwargs", ")", "if", "pretrained", ":", "if", "'url'", "not", "in", "meta", ":", "warn", "(", "\"There are no pretrained weights for that architecture yet!\"", ")", "return", "learn", "model_path", "=", "untar_data", "(", "meta", "[", "'url'", "]", ",", "data", "=", "False", ")", "fnames", "=", "[", "list", "(", "model_path", ".", "glob", "(", "f'*.{ext}'", ")", ")", "[", "0", "]", "for", "ext", "in", "[", "'pth'", ",", "'pkl'", "]", "]", "learn", ".", "load_pretrained", "(", "*", "fnames", ")", "learn", ".", "freeze", "(", ")", "if", "pretrained_fnames", "is", "not", "None", ":", "fnames", "=", "[", "learn", ".", "path", "/", "learn", ".", "model_dir", "/", "f'{fn}.{ext}'", "for", "fn", ",", "ext", "in", "zip", "(", "pretrained_fnames", ",", "[", "'pth'", ",", "'pkl'", "]", ")", "]", "learn", ".", "load_pretrained", "(", "*", "fnames", ")", "learn", ".", "freeze", "(", ")", "return", "learn" ]
Create a `Learner` with a language model from `data` and `arch`.
[ "Create", "a", "Learner", "with", "a", "language", "model", "from", "data", "and", "arch", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L201-L219
train
fastai/fastai
fastai/text/learner.py
get_text_classifier
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 its `config`, maybe `pretrained`." meta = _model_meta[arch] config = ifnone(config, meta['config_clas'].copy()) for k in config.keys(): if k.endswith('_p'): config[k] *= drop_mult if lin_ftrs is None: lin_ftrs = [50] if ps is None: ps = [0.1]*len(lin_ftrs) layers = [config[meta['hid_name']] * 3] + lin_ftrs + [n_class] ps = [config.pop('output_p')] + ps init = config.pop('init') if 'init' in config else None encoder = MultiBatchEncoder(bptt, max_len, arch(vocab_sz, **config), pad_idx=pad_idx) model = SequentialRNN(encoder, PoolingLinearClassifier(layers, ps)) return model if init is None else model.apply(init)
python
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 its `config`, maybe `pretrained`." meta = _model_meta[arch] config = ifnone(config, meta['config_clas'].copy()) for k in config.keys(): if k.endswith('_p'): config[k] *= drop_mult if lin_ftrs is None: lin_ftrs = [50] if ps is None: ps = [0.1]*len(lin_ftrs) layers = [config[meta['hid_name']] * 3] + lin_ftrs + [n_class] ps = [config.pop('output_p')] + ps init = config.pop('init') if 'init' in config else None encoder = MultiBatchEncoder(bptt, max_len, arch(vocab_sz, **config), pad_idx=pad_idx) model = SequentialRNN(encoder, PoolingLinearClassifier(layers, ps)) return model if init is None else model.apply(init)
[ "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", ":", "meta", "=", "_model_meta", "[", "arch", "]", "config", "=", "ifnone", "(", "config", ",", "meta", "[", "'config_clas'", "]", ".", "copy", "(", ")", ")", "for", "k", "in", "config", ".", "keys", "(", ")", ":", "if", "k", ".", "endswith", "(", "'_p'", ")", ":", "config", "[", "k", "]", "*=", "drop_mult", "if", "lin_ftrs", "is", "None", ":", "lin_ftrs", "=", "[", "50", "]", "if", "ps", "is", "None", ":", "ps", "=", "[", "0.1", "]", "*", "len", "(", "lin_ftrs", ")", "layers", "=", "[", "config", "[", "meta", "[", "'hid_name'", "]", "]", "*", "3", "]", "+", "lin_ftrs", "+", "[", "n_class", "]", "ps", "=", "[", "config", ".", "pop", "(", "'output_p'", ")", "]", "+", "ps", "init", "=", "config", ".", "pop", "(", "'init'", ")", "if", "'init'", "in", "config", "else", "None", "encoder", "=", "MultiBatchEncoder", "(", "bptt", ",", "max_len", ",", "arch", "(", "vocab_sz", ",", "*", "*", "config", ")", ",", "pad_idx", "=", "pad_idx", ")", "model", "=", "SequentialRNN", "(", "encoder", ",", "PoolingLinearClassifier", "(", "layers", ",", "ps", ")", ")", "return", "model", "if", "init", "is", "None", "else", "model", ".", "apply", "(", "init", ")" ]
Create a text classifier from `arch` and its `config`, maybe `pretrained`.
[ "Create", "a", "text", "classifier", "from", "arch", "and", "its", "config", "maybe", "pretrained", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L269-L284
train
fastai/fastai
fastai/text/learner.py
text_classifier_learner
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': "Create a `Learner` with a text classifier from `data` and `arch`." model = get_text_classifier(arch, len(data.vocab.itos), data.c, bptt=bptt, max_len=max_len, config=config, drop_mult=drop_mult, lin_ftrs=lin_ftrs, ps=ps) meta = _model_meta[arch] learn = RNNLearner(data, model, split_func=meta['split_clas'], **learn_kwargs) if pretrained: if 'url' not in meta: warn("There are no pretrained weights for that architecture yet!") return learn model_path = untar_data(meta['url'], data=False) fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']] learn.load_pretrained(*fnames, strict=False) learn.freeze() return learn
python
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': "Create a `Learner` with a text classifier from `data` and `arch`." model = get_text_classifier(arch, len(data.vocab.itos), data.c, bptt=bptt, max_len=max_len, config=config, drop_mult=drop_mult, lin_ftrs=lin_ftrs, ps=ps) meta = _model_meta[arch] learn = RNNLearner(data, model, split_func=meta['split_clas'], **learn_kwargs) if pretrained: if 'url' not in meta: warn("There are no pretrained weights for that architecture yet!") return learn model_path = untar_data(meta['url'], data=False) fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']] learn.load_pretrained(*fnames, strict=False) learn.freeze() return learn
[ "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'", ":", "model", "=", "get_text_classifier", "(", "arch", ",", "len", "(", "data", ".", "vocab", ".", "itos", ")", ",", "data", ".", "c", ",", "bptt", "=", "bptt", ",", "max_len", "=", "max_len", ",", "config", "=", "config", ",", "drop_mult", "=", "drop_mult", ",", "lin_ftrs", "=", "lin_ftrs", ",", "ps", "=", "ps", ")", "meta", "=", "_model_meta", "[", "arch", "]", "learn", "=", "RNNLearner", "(", "data", ",", "model", ",", "split_func", "=", "meta", "[", "'split_clas'", "]", ",", "*", "*", "learn_kwargs", ")", "if", "pretrained", ":", "if", "'url'", "not", "in", "meta", ":", "warn", "(", "\"There are no pretrained weights for that architecture yet!\"", ")", "return", "learn", "model_path", "=", "untar_data", "(", "meta", "[", "'url'", "]", ",", "data", "=", "False", ")", "fnames", "=", "[", "list", "(", "model_path", ".", "glob", "(", "f'*.{ext}'", ")", ")", "[", "0", "]", "for", "ext", "in", "[", "'pth'", ",", "'pkl'", "]", "]", "learn", ".", "load_pretrained", "(", "*", "fnames", ",", "strict", "=", "False", ")", "learn", ".", "freeze", "(", ")", "return", "learn" ]
Create a `Learner` with a text classifier from `data` and `arch`.
[ "Create", "a", "Learner", "with", "a", "text", "classifier", "from", "data", "and", "arch", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L286-L302
train
fastai/fastai
fastai/text/learner.py
RNNLearner.save_encoder
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')
python
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", ")", ":", "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.
[ "Save", "the", "encoder", "to", "name", "inside", "the", "model", "directory", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L57-L61
train
fastai/fastai
fastai/text/learner.py
RNNLearner.load_encoder
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.load(self.path/self.model_dir/f'{name}.pth')) encoder.load_state_dict(torch.load(self.path/self.model_dir/f'{name}.pth', map_location=device)) self.freeze()
python
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.load(self.path/self.model_dir/f'{name}.pth')) encoder.load_state_dict(torch.load(self.path/self.model_dir/f'{name}.pth', map_location=device)) self.freeze()
[ "def", "load_encoder", "(", "self", ",", "name", ":", "str", ",", "device", ":", "torch", ".", "device", "=", "None", ")", ":", "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", ".", "load", "(", "self", ".", "path", "/", "self", ".", "model_dir", "/", "f'{name}.pth'", ")", ")", "encoder", ".", "load_state_dict", "(", "torch", ".", "load", "(", "self", ".", "path", "/", "self", ".", "model_dir", "/", "f'{name}.pth'", ",", "map_location", "=", "device", ")", ")", "self", ".", "freeze", "(", ")" ]
Load the encoder `name` from the model directory.
[ "Load", "the", "encoder", "name", "from", "the", "model", "directory", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L63-L70
train
fastai/fastai
fastai/text/learner.py
RNNLearner.load_pretrained
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 storage, loc: storage) if 'model' in wgts: wgts = wgts['model'] wgts = convert_weights(wgts, old_stoi, self.data.train_ds.vocab.itos) self.model.load_state_dict(wgts, strict=strict)
python
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 storage, loc: storage) if 'model' in wgts: wgts = wgts['model'] wgts = convert_weights(wgts, old_stoi, self.data.train_ds.vocab.itos) self.model.load_state_dict(wgts, strict=strict)
[ "def", "load_pretrained", "(", "self", ",", "wgts_fname", ":", "str", ",", "itos_fname", ":", "str", ",", "strict", ":", "bool", "=", "True", ")", ":", "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", "storage", ",", "loc", ":", "storage", ")", "if", "'model'", "in", "wgts", ":", "wgts", "=", "wgts", "[", "'model'", "]", "wgts", "=", "convert_weights", "(", "wgts", ",", "old_stoi", ",", "self", ".", "data", ".", "train_ds", ".", "vocab", ".", "itos", ")", "self", ".", "model", ".", "load_state_dict", "(", "wgts", ",", "strict", "=", "strict", ")" ]
Load a pretrained model and adapts it to the data vocabulary.
[ "Load", "a", "pretrained", "model", "and", "adapts", "it", "to", "the", "data", "vocabulary", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L72-L79
train
fastai/fastai
fastai/text/learner.py
RNNLearner.get_preds
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() if ordered: np.random.seed(42) preds = super().get_preds(ds_type=ds_type, with_loss=with_loss, n_batch=n_batch, pbar=pbar) if ordered and hasattr(self.dl(ds_type), 'sampler'): np.random.seed(42) sampler = [i for i in self.dl(ds_type).sampler] reverse_sampler = np.argsort(sampler) preds = [p[reverse_sampler] for p in preds] return(preds)
python
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() if ordered: np.random.seed(42) preds = super().get_preds(ds_type=ds_type, with_loss=with_loss, n_batch=n_batch, pbar=pbar) if ordered and hasattr(self.dl(ds_type), 'sampler'): np.random.seed(42) sampler = [i for i in self.dl(ds_type).sampler] reverse_sampler = np.argsort(sampler) preds = [p[reverse_sampler] for p in preds] return(preds)
[ "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", "]", ":", "self", ".", "model", ".", "reset", "(", ")", "if", "ordered", ":", "np", ".", "random", ".", "seed", "(", "42", ")", "preds", "=", "super", "(", ")", ".", "get_preds", "(", "ds_type", "=", "ds_type", ",", "with_loss", "=", "with_loss", ",", "n_batch", "=", "n_batch", ",", "pbar", "=", "pbar", ")", "if", "ordered", "and", "hasattr", "(", "self", ".", "dl", "(", "ds_type", ")", ",", "'sampler'", ")", ":", "np", ".", "random", ".", "seed", "(", "42", ")", "sampler", "=", "[", "i", "for", "i", "in", "self", ".", "dl", "(", "ds_type", ")", ".", "sampler", "]", "reverse_sampler", "=", "np", ".", "argsort", "(", "sampler", ")", "preds", "=", "[", "p", "[", "reverse_sampler", "]", "for", "p", "in", "preds", "]", "return", "(", "preds", ")" ]
Return predictions and targets on the valid, train, or test set, depending on `ds_type`.
[ "Return", "predictions", "and", "targets", "on", "the", "valid", "train", "or", "test", "set", "depending", "on", "ds_type", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L81-L92
train
fastai/fastai
fastai/text/learner.py
LanguageLearner.predict
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(text) new_idx = [] for _ in range(n_words): #progress_bar(range(n_words), leave=False): res = self.pred_batch(batch=(xb,yb))[0][-1] #if len(new_idx) == 0: self.model[0].select_hidden([0]) if no_unk: res[self.data.vocab.stoi[UNK]] = 0. if min_p is not None: if (res >= min_p).float().sum() == 0: warn(f"There is no item with probability >= {min_p}, try a lower value.") else: res[res < min_p] = 0. if temperature != 1.: res.pow_(1 / temperature) idx = torch.multinomial(res, 1).item() new_idx.append(idx) xb = xb.new_tensor([idx])[None] return text + sep + sep.join(decoder(self.data.vocab.textify(new_idx, sep=None)))
python
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(text) new_idx = [] for _ in range(n_words): #progress_bar(range(n_words), leave=False): res = self.pred_batch(batch=(xb,yb))[0][-1] #if len(new_idx) == 0: self.model[0].select_hidden([0]) if no_unk: res[self.data.vocab.stoi[UNK]] = 0. if min_p is not None: if (res >= min_p).float().sum() == 0: warn(f"There is no item with probability >= {min_p}, try a lower value.") else: res[res < min_p] = 0. if temperature != 1.: res.pow_(1 / temperature) idx = torch.multinomial(res, 1).item() new_idx.append(idx) xb = xb.new_tensor([idx])[None] return text + sep + sep.join(decoder(self.data.vocab.textify(new_idx, sep=None)))
[ "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", ")", ":", "ds", "=", "self", ".", "data", ".", "single_dl", ".", "dataset", "self", ".", "model", ".", "reset", "(", ")", "xb", ",", "yb", "=", "self", ".", "data", ".", "one_item", "(", "text", ")", "new_idx", "=", "[", "]", "for", "_", "in", "range", "(", "n_words", ")", ":", "#progress_bar(range(n_words), leave=False):", "res", "=", "self", ".", "pred_batch", "(", "batch", "=", "(", "xb", ",", "yb", ")", ")", "[", "0", "]", "[", "-", "1", "]", "#if len(new_idx) == 0: self.model[0].select_hidden([0])", "if", "no_unk", ":", "res", "[", "self", ".", "data", ".", "vocab", ".", "stoi", "[", "UNK", "]", "]", "=", "0.", "if", "min_p", "is", "not", "None", ":", "if", "(", "res", ">=", "min_p", ")", ".", "float", "(", ")", ".", "sum", "(", ")", "==", "0", ":", "warn", "(", "f\"There is no item with probability >= {min_p}, try a lower value.\"", ")", "else", ":", "res", "[", "res", "<", "min_p", "]", "=", "0.", "if", "temperature", "!=", "1.", ":", "res", ".", "pow_", "(", "1", "/", "temperature", ")", "idx", "=", "torch", ".", "multinomial", "(", "res", ",", "1", ")", ".", "item", "(", ")", "new_idx", ".", "append", "(", "idx", ")", "xb", "=", "xb", ".", "new_tensor", "(", "[", "idx", "]", ")", "[", "None", "]", "return", "text", "+", "sep", "+", "sep", ".", "join", "(", "decoder", "(", "self", ".", "data", ".", "vocab", ".", "textify", "(", "new_idx", ",", "sep", "=", "None", ")", ")", ")" ]
Return the `n_words` that come after `text`.
[ "Return", "the", "n_words", "that", "come", "after", "text", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L116-L135
train
fastai/fastai
fastai/text/learner.py
LanguageLearner.beam_search
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() xb, yb = self.data.one_item(text) nodes = None xb = xb.repeat(top_k, 1) nodes = xb.clone() scores = xb.new_zeros(1).float() with torch.no_grad(): for k in progress_bar(range(n_words), leave=False): out = F.log_softmax(self.model(xb)[0][:,-1], dim=-1) if no_unk: out[:,self.data.vocab.stoi[UNK]] = -float('Inf') values, indices = out.topk(top_k, dim=-1) scores = (-values + scores[:,None]).view(-1) indices_idx = torch.arange(0,nodes.size(0))[:,None].expand(nodes.size(0), top_k).contiguous().view(-1) sort_idx = scores.argsort()[:beam_sz] scores = scores[sort_idx] nodes = torch.cat([nodes[:,None].expand(nodes.size(0),top_k,nodes.size(1)), indices[:,:,None].expand(nodes.size(0),top_k,1),], dim=2) nodes = nodes.view(-1, nodes.size(2))[sort_idx] self.model[0].select_hidden(indices_idx[sort_idx]) xb = nodes[:,-1][:,None] if temperature != 1.: scores.div_(temperature) node_idx = torch.multinomial(torch.exp(-scores), 1).item() return text + sep + sep.join(decoder(self.data.vocab.textify([i.item() for i in nodes[node_idx][1:] ], sep=None)))
python
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() xb, yb = self.data.one_item(text) nodes = None xb = xb.repeat(top_k, 1) nodes = xb.clone() scores = xb.new_zeros(1).float() with torch.no_grad(): for k in progress_bar(range(n_words), leave=False): out = F.log_softmax(self.model(xb)[0][:,-1], dim=-1) if no_unk: out[:,self.data.vocab.stoi[UNK]] = -float('Inf') values, indices = out.topk(top_k, dim=-1) scores = (-values + scores[:,None]).view(-1) indices_idx = torch.arange(0,nodes.size(0))[:,None].expand(nodes.size(0), top_k).contiguous().view(-1) sort_idx = scores.argsort()[:beam_sz] scores = scores[sort_idx] nodes = torch.cat([nodes[:,None].expand(nodes.size(0),top_k,nodes.size(1)), indices[:,:,None].expand(nodes.size(0),top_k,1),], dim=2) nodes = nodes.view(-1, nodes.size(2))[sort_idx] self.model[0].select_hidden(indices_idx[sort_idx]) xb = nodes[:,-1][:,None] if temperature != 1.: scores.div_(temperature) node_idx = torch.multinomial(torch.exp(-scores), 1).item() return text + sep + sep.join(decoder(self.data.vocab.textify([i.item() for i in nodes[node_idx][1:] ], sep=None)))
[ "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", ")", ":", "ds", "=", "self", ".", "data", ".", "single_dl", ".", "dataset", "self", ".", "model", ".", "reset", "(", ")", "xb", ",", "yb", "=", "self", ".", "data", ".", "one_item", "(", "text", ")", "nodes", "=", "None", "xb", "=", "xb", ".", "repeat", "(", "top_k", ",", "1", ")", "nodes", "=", "xb", ".", "clone", "(", ")", "scores", "=", "xb", ".", "new_zeros", "(", "1", ")", ".", "float", "(", ")", "with", "torch", ".", "no_grad", "(", ")", ":", "for", "k", "in", "progress_bar", "(", "range", "(", "n_words", ")", ",", "leave", "=", "False", ")", ":", "out", "=", "F", ".", "log_softmax", "(", "self", ".", "model", "(", "xb", ")", "[", "0", "]", "[", ":", ",", "-", "1", "]", ",", "dim", "=", "-", "1", ")", "if", "no_unk", ":", "out", "[", ":", ",", "self", ".", "data", ".", "vocab", ".", "stoi", "[", "UNK", "]", "]", "=", "-", "float", "(", "'Inf'", ")", "values", ",", "indices", "=", "out", ".", "topk", "(", "top_k", ",", "dim", "=", "-", "1", ")", "scores", "=", "(", "-", "values", "+", "scores", "[", ":", ",", "None", "]", ")", ".", "view", "(", "-", "1", ")", "indices_idx", "=", "torch", ".", "arange", "(", "0", ",", "nodes", ".", "size", "(", "0", ")", ")", "[", ":", ",", "None", "]", ".", "expand", "(", "nodes", ".", "size", "(", "0", ")", ",", "top_k", ")", ".", "contiguous", "(", ")", ".", "view", "(", "-", "1", ")", "sort_idx", "=", "scores", ".", "argsort", "(", ")", "[", ":", "beam_sz", "]", "scores", "=", "scores", "[", "sort_idx", "]", "nodes", "=", "torch", ".", "cat", "(", "[", "nodes", "[", ":", ",", "None", "]", ".", "expand", "(", "nodes", ".", "size", "(", "0", ")", ",", "top_k", ",", "nodes", ".", "size", "(", "1", ")", ")", ",", "indices", "[", ":", ",", ":", ",", "None", "]", ".", "expand", "(", "nodes", ".", "size", "(", "0", ")", ",", "top_k", ",", "1", ")", ",", "]", ",", "dim", "=", "2", ")", "nodes", "=", "nodes", ".", "view", "(", "-", "1", ",", "nodes", ".", "size", "(", "2", ")", ")", "[", "sort_idx", "]", "self", ".", "model", "[", "0", "]", ".", "select_hidden", "(", "indices_idx", "[", "sort_idx", "]", ")", "xb", "=", "nodes", "[", ":", ",", "-", "1", "]", "[", ":", ",", "None", "]", "if", "temperature", "!=", "1.", ":", "scores", ".", "div_", "(", "temperature", ")", "node_idx", "=", "torch", ".", "multinomial", "(", "torch", ".", "exp", "(", "-", "scores", ")", ",", "1", ")", ".", "item", "(", ")", "return", "text", "+", "sep", "+", "sep", ".", "join", "(", "decoder", "(", "self", ".", "data", ".", "vocab", ".", "textify", "(", "[", "i", ".", "item", "(", ")", "for", "i", "in", "nodes", "[", "node_idx", "]", "[", "1", ":", "]", "]", ",", "sep", "=", "None", ")", ")", ")" ]
Return the `n_words` that come after `text` using beam search.
[ "Return", "the", "n_words", "that", "come", "after", "text", "using", "beam", "search", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L137-L163
train
fastai/fastai
fastai/text/learner.py
LanguageLearner.show_results
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 = self.pred_batch(batch=(x,y)) y = y.view(*x.size()) z = preds.view(*x.size(),-1).argmax(dim=2) xs = [ds.x.reconstruct(grab_idx(x, i)) for i in range(rows)] ys = [ds.x.reconstruct(grab_idx(y, i)) for i in range(rows)] zs = [ds.x.reconstruct(grab_idx(z, i)) for i in range(rows)] items,names = [],['text', 'target', 'pred'] for i, (x,y,z) in enumerate(zip(xs,ys,zs)): txt_x = ' '.join(x.text.split(' ')[:max_len]) txt_y = ' '.join(y.text.split(' ')[max_len-1:2*max_len-1]) txt_z = ' '.join(z.text.split(' ')[max_len-1:2*max_len-1]) items.append([txt_x, txt_y, txt_z]) items = np.array(items) df = pd.DataFrame({n:items[:,i] for i,n in enumerate(names)}, columns=names) with pd.option_context('display.max_colwidth', -1): display(HTML(df.to_html(index=False)))
python
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 = self.pred_batch(batch=(x,y)) y = y.view(*x.size()) z = preds.view(*x.size(),-1).argmax(dim=2) xs = [ds.x.reconstruct(grab_idx(x, i)) for i in range(rows)] ys = [ds.x.reconstruct(grab_idx(y, i)) for i in range(rows)] zs = [ds.x.reconstruct(grab_idx(z, i)) for i in range(rows)] items,names = [],['text', 'target', 'pred'] for i, (x,y,z) in enumerate(zip(xs,ys,zs)): txt_x = ' '.join(x.text.split(' ')[:max_len]) txt_y = ' '.join(y.text.split(' ')[max_len-1:2*max_len-1]) txt_z = ' '.join(z.text.split(' ')[max_len-1:2*max_len-1]) items.append([txt_x, txt_y, txt_z]) items = np.array(items) df = pd.DataFrame({n:items[:,i] for i,n in enumerate(names)}, columns=names) with pd.option_context('display.max_colwidth', -1): display(HTML(df.to_html(index=False)))
[ "def", "show_results", "(", "self", ",", "ds_type", "=", "DatasetType", ".", "Valid", ",", "rows", ":", "int", "=", "5", ",", "max_len", ":", "int", "=", "20", ")", ":", "from", "IPython", ".", "display", "import", "display", ",", "HTML", "ds", "=", "self", ".", "dl", "(", "ds_type", ")", ".", "dataset", "x", ",", "y", "=", "self", ".", "data", ".", "one_batch", "(", "ds_type", ",", "detach", "=", "False", ",", "denorm", "=", "False", ")", "preds", "=", "self", ".", "pred_batch", "(", "batch", "=", "(", "x", ",", "y", ")", ")", "y", "=", "y", ".", "view", "(", "*", "x", ".", "size", "(", ")", ")", "z", "=", "preds", ".", "view", "(", "*", "x", ".", "size", "(", ")", ",", "-", "1", ")", ".", "argmax", "(", "dim", "=", "2", ")", "xs", "=", "[", "ds", ".", "x", ".", "reconstruct", "(", "grab_idx", "(", "x", ",", "i", ")", ")", "for", "i", "in", "range", "(", "rows", ")", "]", "ys", "=", "[", "ds", ".", "x", ".", "reconstruct", "(", "grab_idx", "(", "y", ",", "i", ")", ")", "for", "i", "in", "range", "(", "rows", ")", "]", "zs", "=", "[", "ds", ".", "x", ".", "reconstruct", "(", "grab_idx", "(", "z", ",", "i", ")", ")", "for", "i", "in", "range", "(", "rows", ")", "]", "items", ",", "names", "=", "[", "]", ",", "[", "'text'", ",", "'target'", ",", "'pred'", "]", "for", "i", ",", "(", "x", ",", "y", ",", "z", ")", "in", "enumerate", "(", "zip", "(", "xs", ",", "ys", ",", "zs", ")", ")", ":", "txt_x", "=", "' '", ".", "join", "(", "x", ".", "text", ".", "split", "(", "' '", ")", "[", ":", "max_len", "]", ")", "txt_y", "=", "' '", ".", "join", "(", "y", ".", "text", ".", "split", "(", "' '", ")", "[", "max_len", "-", "1", ":", "2", "*", "max_len", "-", "1", "]", ")", "txt_z", "=", "' '", ".", "join", "(", "z", ".", "text", ".", "split", "(", "' '", ")", "[", "max_len", "-", "1", ":", "2", "*", "max_len", "-", "1", "]", ")", "items", ".", "append", "(", "[", "txt_x", ",", "txt_y", ",", "txt_z", "]", ")", "items", "=", "np", ".", "array", "(", "items", ")", "df", "=", "pd", ".", "DataFrame", "(", "{", "n", ":", "items", "[", ":", ",", "i", "]", "for", "i", ",", "n", "in", "enumerate", "(", "names", ")", "}", ",", "columns", "=", "names", ")", "with", "pd", ".", "option_context", "(", "'display.max_colwidth'", ",", "-", "1", ")", ":", "display", "(", "HTML", "(", "df", ".", "to_html", "(", "index", "=", "False", ")", ")", ")" ]
Show `rows` result of predictions on `ds_type` dataset.
[ "Show", "rows", "result", "of", "predictions", "on", "ds_type", "dataset", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L165-L185
train
fastai/fastai
fastai/text/learner.py
MultiBatchEncoder.concat
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])]
python
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", ":", "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.
[ "Concatenate", "the", "arrs", "along", "the", "batch", "dimension", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L250-L252
train
fastai/fastai
fastai/layers.py
batchnorm_2d
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
python
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", ")", ":", "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`.
[ "A", "batchnorm2d", "layer", "with", "nf", "features", "initialized", "depending", "on", "norm_type", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L52-L58
train
fastai/fastai
fastai/layers.py
bn_drop_lin
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(nn.Linear(n_in, n_out)) if actn is not None: layers.append(actn) return layers
python
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(nn.Linear(n_in, n_out)) if actn is not None: layers.append(actn) return layers
[ "def", "bn_drop_lin", "(", "n_in", ":", "int", ",", "n_out", ":", "int", ",", "bn", ":", "bool", "=", "True", ",", "p", ":", "float", "=", "0.", ",", "actn", ":", "Optional", "[", "nn", ".", "Module", "]", "=", "None", ")", ":", "layers", "=", "[", "nn", ".", "BatchNorm1d", "(", "n_in", ")", "]", "if", "bn", "else", "[", "]", "if", "p", "!=", "0", ":", "layers", ".", "append", "(", "nn", ".", "Dropout", "(", "p", ")", ")", "layers", ".", "append", "(", "nn", ".", "Linear", "(", "n_in", ",", "n_out", ")", ")", "if", "actn", "is", "not", "None", ":", "layers", ".", "append", "(", "actn", ")", "return", "layers" ]
Sequence of batchnorm (if `bn`), dropout (with `p`) and linear (`n_in`,`n_out`) layers followed by `actn`.
[ "Sequence", "of", "batchnorm", "(", "if", "bn", ")", "dropout", "(", "with", "p", ")", "and", "linear", "(", "n_in", "n_out", ")", "layers", "followed", "by", "actn", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L60-L66
train
fastai/fastai
fastai/layers.py
conv1d
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_() return spectral_norm(conv)
python
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_() return spectral_norm(conv)
[ "def", "conv1d", "(", "ni", ":", "int", ",", "no", ":", "int", ",", "ks", ":", "int", "=", "1", ",", "stride", ":", "int", "=", "1", ",", "padding", ":", "int", "=", "0", ",", "bias", ":", "bool", "=", "False", ")", ":", "conv", "=", "nn", ".", "Conv1d", "(", "ni", ",", "no", ",", "ks", ",", "stride", "=", "stride", ",", "padding", "=", "padding", ",", "bias", "=", "bias", ")", "nn", ".", "init", ".", "kaiming_normal_", "(", "conv", ".", "weight", ")", "if", "bias", ":", "conv", ".", "bias", ".", "data", ".", "zero_", "(", ")", "return", "spectral_norm", "(", "conv", ")" ]
Create and initialize a `nn.Conv1d` layer with spectral normalization.
[ "Create", "and", "initialize", "a", "nn", ".", "Conv1d", "layer", "with", "spectral", "normalization", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L68-L73
train
fastai/fastai
fastai/layers.py
conv2d
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=stride, padding=padding, bias=bias), init)
python
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=stride, padding=padding, bias=bias), init)
[ "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", ":", "if", "padding", "is", "None", ":", "padding", "=", "ks", "//", "2", "return", "init_default", "(", "nn", ".", "Conv2d", "(", "ni", ",", "nf", ",", "kernel_size", "=", "ks", ",", "stride", "=", "stride", ",", "padding", "=", "padding", ",", "bias", "=", "bias", ")", ",", "init", ")" ]
Create and initialize `nn.Conv2d` layer. `padding` defaults to `ks//2`.
[ "Create", "and", "initialize", "nn", ".", "Conv2d", "layer", ".", "padding", "defaults", "to", "ks", "//", "2", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L115-L118
train
fastai/fastai
fastai/layers.py
conv2d_trans
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)
python
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", ":", "return", "nn", ".", "ConvTranspose2d", "(", "ni", ",", "nf", ",", "kernel_size", "=", "ks", ",", "stride", "=", "stride", ",", "padding", "=", "padding", ",", "bias", "=", "bias", ")" ]
Create `nn.ConvTranspose2d` layer.
[ "Create", "nn", ".", "ConvTranspose2d", "layer", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L120-L122
train
fastai/fastai
fastai/layers.py
relu
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)
python
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", "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`.
[ "Return", "a", "relu", "activation", "maybe", "leaky", "and", "inplace", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L124-L126
train
fastai/fastai
fastai/layers.py
conv_layer
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): "Create a sequence of convolutional (`ni` to `nf`), ReLU (if `use_activ`) and batchnorm (if `bn`) layers." if padding is None: padding = (ks-1)//2 if not transpose else 0 bn = norm_type in (NormType.Batch, NormType.BatchZero) if bias is None: bias = not bn conv_func = nn.ConvTranspose2d if transpose else nn.Conv1d if is_1d else nn.Conv2d conv = init_default(conv_func(ni, nf, kernel_size=ks, bias=bias, stride=stride, padding=padding), init) if norm_type==NormType.Weight: conv = weight_norm(conv) elif norm_type==NormType.Spectral: conv = spectral_norm(conv) layers = [conv] if use_activ: layers.append(relu(True, leaky=leaky)) if bn: layers.append((nn.BatchNorm1d if is_1d else nn.BatchNorm2d)(nf)) if self_attention: layers.append(SelfAttention(nf)) return nn.Sequential(*layers)
python
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): "Create a sequence of convolutional (`ni` to `nf`), ReLU (if `use_activ`) and batchnorm (if `bn`) layers." if padding is None: padding = (ks-1)//2 if not transpose else 0 bn = norm_type in (NormType.Batch, NormType.BatchZero) if bias is None: bias = not bn conv_func = nn.ConvTranspose2d if transpose else nn.Conv1d if is_1d else nn.Conv2d conv = init_default(conv_func(ni, nf, kernel_size=ks, bias=bias, stride=stride, padding=padding), init) if norm_type==NormType.Weight: conv = weight_norm(conv) elif norm_type==NormType.Spectral: conv = spectral_norm(conv) layers = [conv] if use_activ: layers.append(relu(True, leaky=leaky)) if bn: layers.append((nn.BatchNorm1d if is_1d else nn.BatchNorm2d)(nf)) if self_attention: layers.append(SelfAttention(nf)) return nn.Sequential(*layers)
[ "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", ")", ":", "if", "padding", "is", "None", ":", "padding", "=", "(", "ks", "-", "1", ")", "//", "2", "if", "not", "transpose", "else", "0", "bn", "=", "norm_type", "in", "(", "NormType", ".", "Batch", ",", "NormType", ".", "BatchZero", ")", "if", "bias", "is", "None", ":", "bias", "=", "not", "bn", "conv_func", "=", "nn", ".", "ConvTranspose2d", "if", "transpose", "else", "nn", ".", "Conv1d", "if", "is_1d", "else", "nn", ".", "Conv2d", "conv", "=", "init_default", "(", "conv_func", "(", "ni", ",", "nf", ",", "kernel_size", "=", "ks", ",", "bias", "=", "bias", ",", "stride", "=", "stride", ",", "padding", "=", "padding", ")", ",", "init", ")", "if", "norm_type", "==", "NormType", ".", "Weight", ":", "conv", "=", "weight_norm", "(", "conv", ")", "elif", "norm_type", "==", "NormType", ".", "Spectral", ":", "conv", "=", "spectral_norm", "(", "conv", ")", "layers", "=", "[", "conv", "]", "if", "use_activ", ":", "layers", ".", "append", "(", "relu", "(", "True", ",", "leaky", "=", "leaky", ")", ")", "if", "bn", ":", "layers", ".", "append", "(", "(", "nn", ".", "BatchNorm1d", "if", "is_1d", "else", "nn", ".", "BatchNorm2d", ")", "(", "nf", ")", ")", "if", "self_attention", ":", "layers", ".", "append", "(", "SelfAttention", "(", "nf", ")", ")", "return", "nn", ".", "Sequential", "(", "*", "layers", ")" ]
Create a sequence of convolutional (`ni` to `nf`), ReLU (if `use_activ`) and batchnorm (if `bn`) layers.
[ "Create", "a", "sequence", "of", "convolutional", "(", "ni", "to", "nf", ")", "ReLU", "(", "if", "use_activ", ")", "and", "batchnorm", "(", "if", "bn", ")", "layers", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L128-L143
train
fastai/fastai
fastai/layers.py
res_block
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 bottle else nf return SequentialEx(conv_layer(nf, nf_inner, norm_type=norm_type, **conv_kwargs), conv_layer(nf_inner, nf, norm_type=norm2, **conv_kwargs), MergeLayer(dense))
python
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 bottle else nf return SequentialEx(conv_layer(nf, nf_inner, norm_type=norm_type, **conv_kwargs), conv_layer(nf_inner, nf, norm_type=norm2, **conv_kwargs), MergeLayer(dense))
[ "def", "res_block", "(", "nf", ",", "dense", ":", "bool", "=", "False", ",", "norm_type", ":", "Optional", "[", "NormType", "]", "=", "NormType", ".", "Batch", ",", "bottle", ":", "bool", "=", "False", ",", "*", "*", "conv_kwargs", ")", ":", "norm2", "=", "norm_type", "if", "not", "dense", "and", "(", "norm_type", "==", "NormType", ".", "Batch", ")", ":", "norm2", "=", "NormType", ".", "BatchZero", "nf_inner", "=", "nf", "//", "2", "if", "bottle", "else", "nf", "return", "SequentialEx", "(", "conv_layer", "(", "nf", ",", "nf_inner", ",", "norm_type", "=", "norm_type", ",", "*", "*", "conv_kwargs", ")", ",", "conv_layer", "(", "nf_inner", ",", "nf", ",", "norm_type", "=", "norm2", ",", "*", "*", "conv_kwargs", ")", ",", "MergeLayer", "(", "dense", ")", ")" ]
Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`.
[ "Resnet", "block", "of", "nf", "features", ".", "conv_kwargs", "are", "passed", "to", "conv_layer", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L174-L181
train
fastai/fastai
fastai/layers.py
sigmoid_range
def sigmoid_range(x, low, high): "Sigmoid function with range `(low, high)`" return torch.sigmoid(x) * (high - low) + low
python
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", ")", ":", "return", "torch", ".", "sigmoid", "(", "x", ")", "*", "(", "high", "-", "low", ")", "+", "low" ]
Sigmoid function with range `(low, high)`
[ "Sigmoid", "function", "with", "range", "(", "low", "high", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L183-L185
train
fastai/fastai
fastai/layers.py
icnr
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([nf,ni,h,w]).transpose(0, 1) x.data.copy_(k)
python
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([nf,ni,h,w]).transpose(0, 1) x.data.copy_(k)
[ "def", "icnr", "(", "x", ",", "scale", "=", "2", ",", "init", "=", "nn", ".", "init", ".", "kaiming_normal_", ")", ":", "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", "(", "[", "nf", ",", "ni", ",", "h", ",", "w", "]", ")", ".", "transpose", "(", "0", ",", "1", ")", "x", ".", "data", ".", "copy_", "(", "k", ")" ]
ICNR init of `x`, with `scale` and `init` function.
[ "ICNR", "init", "of", "x", "with", "scale", "and", "init", "function", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L221-L229
train
fastai/fastai
fastai/layers.py
CrossEntropyFlat
def CrossEntropyFlat(*args, axis:int=-1, **kwargs): "Same as `nn.CrossEntropyLoss`, but flattens input and target." return FlattenedLoss(nn.CrossEntropyLoss, *args, axis=axis, **kwargs)
python
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", ")", ":", "return", "FlattenedLoss", "(", "nn", ".", "CrossEntropyLoss", ",", "*", "args", ",", "axis", "=", "axis", ",", "*", "*", "kwargs", ")" ]
Same as `nn.CrossEntropyLoss`, but flattens input and target.
[ "Same", "as", "nn", ".", "CrossEntropyLoss", "but", "flattens", "input", "and", "target", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L269-L271
train
fastai/fastai
fastai/layers.py
BCEWithLogitsFlat
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)
python
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", ")", ":", "return", "FlattenedLoss", "(", "nn", ".", "BCEWithLogitsLoss", ",", "*", "args", ",", "axis", "=", "axis", ",", "floatify", "=", "floatify", ",", "is_2d", "=", "False", ",", "*", "*", "kwargs", ")" ]
Same as `nn.BCEWithLogitsLoss`, but flattens input and target.
[ "Same", "as", "nn", ".", "BCEWithLogitsLoss", "but", "flattens", "input", "and", "target", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L273-L275
train
fastai/fastai
fastai/layers.py
BCEFlat
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)
python
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", ")", ":", "return", "FlattenedLoss", "(", "nn", ".", "BCELoss", ",", "*", "args", ",", "axis", "=", "axis", ",", "floatify", "=", "floatify", ",", "is_2d", "=", "False", ",", "*", "*", "kwargs", ")" ]
Same as `nn.BCELoss`, but flattens input and target.
[ "Same", "as", "nn", ".", "BCELoss", "but", "flattens", "input", "and", "target", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L277-L279
train
fastai/fastai
fastai/layers.py
MSELossFlat
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)
python
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", ")", ":", "return", "FlattenedLoss", "(", "nn", ".", "MSELoss", ",", "*", "args", ",", "axis", "=", "axis", ",", "floatify", "=", "floatify", ",", "is_2d", "=", "False", ",", "*", "*", "kwargs", ")" ]
Same as `nn.MSELoss`, but flattens input and target.
[ "Same", "as", "nn", ".", "MSELoss", "but", "flattens", "input", "and", "target", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L281-L283
train
fastai/fastai
fastai/layers.py
simple_cnn
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) strides = ifnone(strides , [2]*nl) layers = [conv_layer(actns[i], actns[i+1], kernel_szs[i], stride=strides[i], norm_type=(NormType.Batch if bn and i<(len(strides)-1) else None)) for i in range_of(strides)] layers.append(PoolFlatten()) return nn.Sequential(*layers)
python
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) strides = ifnone(strides , [2]*nl) layers = [conv_layer(actns[i], actns[i+1], kernel_szs[i], stride=strides[i], norm_type=(NormType.Batch if bn and i<(len(strides)-1) else None)) for i in range_of(strides)] layers.append(PoolFlatten()) return nn.Sequential(*layers)
[ "def", "simple_cnn", "(", "actns", ":", "Collection", "[", "int", "]", ",", "kernel_szs", ":", "Collection", "[", "int", "]", "=", "None", ",", "strides", ":", "Collection", "[", "int", "]", "=", "None", ",", "bn", "=", "False", ")", "->", "nn", ".", "Sequential", ":", "nl", "=", "len", "(", "actns", ")", "-", "1", "kernel_szs", "=", "ifnone", "(", "kernel_szs", ",", "[", "3", "]", "*", "nl", ")", "strides", "=", "ifnone", "(", "strides", ",", "[", "2", "]", "*", "nl", ")", "layers", "=", "[", "conv_layer", "(", "actns", "[", "i", "]", ",", "actns", "[", "i", "+", "1", "]", ",", "kernel_szs", "[", "i", "]", ",", "stride", "=", "strides", "[", "i", "]", ",", "norm_type", "=", "(", "NormType", ".", "Batch", "if", "bn", "and", "i", "<", "(", "len", "(", "strides", ")", "-", "1", ")", "else", "None", ")", ")", "for", "i", "in", "range_of", "(", "strides", ")", "]", "layers", ".", "append", "(", "PoolFlatten", "(", ")", ")", "return", "nn", ".", "Sequential", "(", "*", "layers", ")" ]
CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`.
[ "CNN", "with", "conv_layer", "defined", "by", "actns", "kernel_szs", "and", "strides", "plus", "batchnorm", "if", "bn", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L293-L302
train
fastai/fastai
fastai/layers.py
trunc_normal_
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)
python
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", ":", "# From https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/12", "return", "x", ".", "normal_", "(", ")", ".", "fmod_", "(", "2", ")", ".", "mul_", "(", "std", ")", ".", "add_", "(", "mean", ")" ]
Truncated normal initialization.
[ "Truncated", "normal", "initialization", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L304-L307
train
fastai/fastai
fastai/layers.py
embedding
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
python
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", ":", "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.
[ "Create", "an", "embedding", "layer", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L309-L314
train
fastai/fastai
fastai/callbacks/mlflow.py
MLFlowTracker.on_train_begin
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.experiment_id run = self.client.create_run(experiment_id=self.exp_id) self.run = run.info.run_uuid for k,v in self.params.items(): self.client.log_param(run_id=self.run, key=k, value=v)
python
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.experiment_id run = self.client.create_run(experiment_id=self.exp_id) self.run = run.info.run_uuid for k,v in self.params.items(): self.client.log_param(run_id=self.run, key=k, value=v)
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "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", ".", "experiment_id", "run", "=", "self", ".", "client", ".", "create_run", "(", "experiment_id", "=", "self", ".", "exp_id", ")", "self", ".", "run", "=", "run", ".", "info", ".", "run_uuid", "for", "k", ",", "v", "in", "self", ".", "params", ".", "items", "(", ")", ":", "self", ".", "client", ".", "log_param", "(", "run_id", "=", "self", ".", "run", ",", "key", "=", "k", ",", "value", "=", "v", ")" ]
Prepare MLflow experiment and log params
[ "Prepare", "MLflow", "experiment", "and", "log", "params" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L16-L24
train
fastai/fastai
fastai/callbacks/mlflow.py
MLFlowTracker.on_epoch_end
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, metrics): self.client.log_metric(self.run, name, np.float(val))
python
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, metrics): self.client.log_metric(self.run, name, np.float(val))
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "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", ",", "metrics", ")", ":", "self", ".", "client", ".", "log_metric", "(", "self", ".", "run", ",", "name", ",", "np", ".", "float", "(", "val", ")", ")" ]
Send loss and metrics values to MLFlow after each epoch
[ "Send", "loss", "and", "metrics", "values", "to", "MLFlow", "after", "each", "epoch" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L26-L31
train
fastai/fastai
fastai/callbacks/mlflow.py
MLFlowTracker.on_train_end
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)
python
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", ":", "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
[ "Store", "the", "notebook", "and", "stop", "run" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L33-L36
train
fastai/fastai
fastai/vision/image.py
pil2tensor
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(dtype, copy=False) )
python
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(dtype, copy=False) )
[ "def", "pil2tensor", "(", "image", ":", "Union", "[", "NPImage", ",", "NPArray", "]", ",", "dtype", ":", "np", ".", "dtype", ")", "->", "TensorImage", ":", "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", "(", "dtype", ",", "copy", "=", "False", ")", ")" ]
Convert PIL style `image` array to torch style image tensor.
[ "Convert", "PIL", "style", "image", "array", "to", "torch", "style", "image", "tensor", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L14-L20
train
fastai/fastai
fastai/vision/image.py
image2np
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
python
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", ":", "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.
[ "Convert", "from", "torch", "style", "image", "to", "numpy", "/", "matplotlib", "style", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L22-L25
train
fastai/fastai
fastai/vision/image.py
bb2hw
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]])
python
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", ":", "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).
[ "Convert", "bounding", "box", "points", "from", "(", "width", "height", "center", ")", "to", "(", "height", "width", "top", "left", ")", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L27-L29
train
fastai/fastai
fastai/vision/image.py
tis2hw
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)
python
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", "]", ":", "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.
[ "Convert", "int", "or", "TensorImageSize", "to", "(", "height", "width", ")", "of", "an", "image", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L31-L34
train
fastai/fastai
fastai/vision/image.py
_draw_outline
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()])
python
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", ")", ":", "o", ".", "set_path_effects", "(", "[", "patheffects", ".", "Stroke", "(", "linewidth", "=", "lw", ",", "foreground", "=", "'black'", ")", ",", "patheffects", ".", "Normal", "(", ")", "]", ")" ]
Outline bounding box onto image `Patch`.
[ "Outline", "bounding", "box", "onto", "image", "Patch", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L36-L39
train
fastai/fastai
fastai/vision/image.py
_draw_rect
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, verticalalignment='top', color=color, fontsize=text_size, weight='bold') _draw_outline(patch,1)
python
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, verticalalignment='top', color=color, fontsize=text_size, weight='bold') _draw_outline(patch,1)
[ "def", "_draw_rect", "(", "ax", ":", "plt", ".", "Axes", ",", "b", ":", "Collection", "[", "int", "]", ",", "color", ":", "str", "=", "'white'", ",", "text", "=", "None", ",", "text_size", "=", "14", ")", ":", "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", ",", "verticalalignment", "=", "'top'", ",", "color", "=", "color", ",", "fontsize", "=", "text_size", ",", "weight", "=", "'bold'", ")", "_draw_outline", "(", "patch", ",", "1", ")" ]
Draw bounding box on `ax`.
[ "Draw", "bounding", "box", "on", "ax", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L41-L47
train
fastai/fastai
fastai/vision/image.py
open_image
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 = PIL.Image.open(fn).convert(convert_mode) if after_open: x = after_open(x) x = pil2tensor(x,np.float32) if div: x.div_(255) return cls(x)
python
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 = PIL.Image.open(fn).convert(convert_mode) if after_open: x = after_open(x) x = pil2tensor(x,np.float32) if div: x.div_(255) return cls(x)
[ "def", "open_image", "(", "fn", ":", "PathOrStr", ",", "div", ":", "bool", "=", "True", ",", "convert_mode", ":", "str", "=", "'RGB'", ",", "cls", ":", "type", "=", "Image", ",", "after_open", ":", "Callable", "=", "None", ")", "->", "Image", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ",", "UserWarning", ")", "# EXIF warning from TiffPlugin", "x", "=", "PIL", ".", "Image", ".", "open", "(", "fn", ")", ".", "convert", "(", "convert_mode", ")", "if", "after_open", ":", "x", "=", "after_open", "(", "x", ")", "x", "=", "pil2tensor", "(", "x", ",", "np", ".", "float32", ")", "if", "div", ":", "x", ".", "div_", "(", "255", ")", "return", "cls", "(", "x", ")" ]
Return `Image` object created from image in file `fn`.
[ "Return", "Image", "object", "created", "from", "image", "in", "file", "fn", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L388-L397
train
fastai/fastai
fastai/vision/image.py
open_mask
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)
python
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", "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.
[ "Return", "ImageSegment", "object", "create", "from", "mask", "in", "file", "fn", ".", "If", "div", "divides", "pixel", "values", "by", "255", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L399-L401
train
fastai/fastai
fastai/vision/image.py
open_mask_rle
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.permute(2,0,1))
python
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.permute(2,0,1))
[ "def", "open_mask_rle", "(", "mask_rle", ":", "str", ",", "shape", ":", "Tuple", "[", "int", ",", "int", "]", ")", "->", "ImageSegment", ":", "x", "=", "FloatTensor", "(", "rle_decode", "(", "str", "(", "mask_rle", ")", ",", "shape", ")", ".", "astype", "(", "np", ".", "uint8", ")", ")", "x", "=", "x", ".", "view", "(", "shape", "[", "1", "]", ",", "shape", "[", "0", "]", ",", "-", "1", ")", "return", "ImageSegment", "(", "x", ".", "permute", "(", "2", ",", "0", ",", "1", ")", ")" ]
Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`.
[ "Return", "ImageSegment", "object", "create", "from", "run", "-", "length", "encoded", "string", "in", "mask_lre", "with", "size", "in", "shape", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L403-L407
train
fastai/fastai
fastai/vision/image.py
rle_encode
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)
python
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", ":", "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`.
[ "Return", "run", "-", "length", "encoding", "string", "from", "img", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L409-L414
train
fastai/fastai
fastai/vision/image.py
rle_decode
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(shape[0]*shape[1], dtype=np.uint) for low, up in zip(starts, ends): img[low:up] = 1 return img.reshape(shape)
python
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(shape[0]*shape[1], dtype=np.uint) for low, up in zip(starts, ends): img[low:up] = 1 return img.reshape(shape)
[ "def", "rle_decode", "(", "mask_rle", ":", "str", ",", "shape", ":", "Tuple", "[", "int", ",", "int", "]", ")", "->", "NPArrayMask", ":", "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", "(", "shape", "[", "0", "]", "*", "shape", "[", "1", "]", ",", "dtype", "=", "np", ".", "uint", ")", "for", "low", ",", "up", "in", "zip", "(", "starts", ",", "ends", ")", ":", "img", "[", "low", ":", "up", "]", "=", "1", "return", "img", ".", "reshape", "(", "shape", ")" ]
Return an image array from run-length encoded string `mask_rle` with `shape`.
[ "Return", "an", "image", "array", "from", "run", "-", "length", "encoded", "string", "mask_rle", "with", "shape", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L416-L424
train
fastai/fastai
fastai/vision/image.py
show_image
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) if hide_axis: ax.axis('off') return ax
python
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) if hide_axis: ax.axis('off') return ax
[ "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", ":", "if", "ax", "is", "None", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "figsize", ")", "ax", ".", "imshow", "(", "image2np", "(", "img", ".", "data", ")", ",", "cmap", "=", "cmap", ",", "alpha", "=", "alpha", ",", "*", "*", "kwargs", ")", "if", "hide_axis", ":", "ax", ".", "axis", "(", "'off'", ")", "return", "ax" ]
Display `Image` in notebook.
[ "Display", "Image", "in", "notebook", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L426-L432
train
fastai/fastai
fastai/vision/image.py
scale_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
python
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", ")", ":", "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`.
[ "Scale", "the", "coords", "in", "flow", "to", "-", "1", "/", "1", "or", "the", "image", "size", "depending", "on", "to_unit", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L434-L439
train
fastai/fastai
fastai/vision/image.py
_grid_sample
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, 3, 1) # optimize layout for grid_sample if mode=='bilinear': # hack to get smoother downwards resampling mn,mx = coords.min(),coords.max() # max amount we're affine zooming by (>1 means zooming in) z = 1/(mx-mn).item()*2 # amount we're resizing by, with 100% extra margin d = min(x.shape[1]/coords.shape[1], x.shape[2]/coords.shape[2])/2 # If we're resizing up by >200%, and we're zooming less than that, interpolate first if d>1 and d>z: x = F.interpolate(x[None], scale_factor=1/d, mode='area')[0] return F.grid_sample(x[None], coords, mode=mode, padding_mode=padding_mode)[0]
python
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, 3, 1) # optimize layout for grid_sample if mode=='bilinear': # hack to get smoother downwards resampling mn,mx = coords.min(),coords.max() # max amount we're affine zooming by (>1 means zooming in) z = 1/(mx-mn).item()*2 # amount we're resizing by, with 100% extra margin d = min(x.shape[1]/coords.shape[1], x.shape[2]/coords.shape[2])/2 # If we're resizing up by >200%, and we're zooming less than that, interpolate first if d>1 and d>z: x = F.interpolate(x[None], scale_factor=1/d, mode='area')[0] return F.grid_sample(x[None], coords, mode=mode, padding_mode=padding_mode)[0]
[ "def", "_grid_sample", "(", "x", ":", "TensorImage", ",", "coords", ":", "FlowField", ",", "mode", ":", "str", "=", "'bilinear'", ",", "padding_mode", ":", "str", "=", "'reflection'", ",", "remove_out", ":", "bool", "=", "True", ")", "->", "TensorImage", ":", "coords", "=", "coords", ".", "flow", ".", "permute", "(", "0", ",", "3", ",", "1", ",", "2", ")", ".", "contiguous", "(", ")", ".", "permute", "(", "0", ",", "2", ",", "3", ",", "1", ")", "# optimize layout for grid_sample", "if", "mode", "==", "'bilinear'", ":", "# hack to get smoother downwards resampling", "mn", ",", "mx", "=", "coords", ".", "min", "(", ")", ",", "coords", ".", "max", "(", ")", "# max amount we're affine zooming by (>1 means zooming in)", "z", "=", "1", "/", "(", "mx", "-", "mn", ")", ".", "item", "(", ")", "*", "2", "# amount we're resizing by, with 100% extra margin", "d", "=", "min", "(", "x", ".", "shape", "[", "1", "]", "/", "coords", ".", "shape", "[", "1", "]", ",", "x", ".", "shape", "[", "2", "]", "/", "coords", ".", "shape", "[", "2", "]", ")", "/", "2", "# If we're resizing up by >200%, and we're zooming less than that, interpolate first", "if", "d", ">", "1", "and", "d", ">", "z", ":", "x", "=", "F", ".", "interpolate", "(", "x", "[", "None", "]", ",", "scale_factor", "=", "1", "/", "d", ",", "mode", "=", "'area'", ")", "[", "0", "]", "return", "F", ".", "grid_sample", "(", "x", "[", "None", "]", ",", "coords", ",", "mode", "=", "mode", ",", "padding_mode", "=", "padding_mode", ")", "[", "0", "]" ]
Resample pixels in `coords` from `x` by `mode`, with `padding_mode` in ('reflection','border','zeros').
[ "Resample", "pixels", "in", "coords", "from", "x", "by", "mode", "with", "padding_mode", "in", "(", "reflection", "border", "zeros", ")", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L524-L535
train
fastai/fastai
fastai/vision/image.py
_affine_mult
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()).view(size) return c
python
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()).view(size) return c
[ "def", "_affine_mult", "(", "c", ":", "FlowField", ",", "m", ":", "AffineMatrix", ")", "->", "FlowField", ":", "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", "(", ")", ")", ".", "view", "(", "size", ")", "return", "c" ]
Multiply `c` by `m` - can adjust for rectangular shaped `c`.
[ "Multiply", "c", "by", "m", "-", "can", "adjust", "for", "rectangular", "shaped", "c", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L547-L556
train
fastai/fastai
fastai/vision/image.py
_affine_inv_mult
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
python
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", ")", ":", "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`.
[ "Applies", "the", "inverse", "affine", "transform", "described", "in", "m", "to", "c", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L558-L567
train
fastai/fastai
fastai/vision/image.py
_round_multiple
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
python
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", ":", "return", "(", "int", "(", "x", "/", "mult", "+", "0.5", ")", "*", "mult", ")", "if", "mult", "is", "not", "None", "else", "x" ]
Calc `x` to nearest multiple of `mult`.
[ "Calc", "x", "to", "nearest", "multiple", "of", "mult", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L585-L587
train
fastai/fastai
fastai/vision/image.py
_get_crop_target
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)
python
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", "]", ":", "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`.
[ "Calc", "crop", "shape", "of", "target_px", "to", "nearest", "multiple", "of", "mult", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L589-L592
train
fastai/fastai
fastai/vision/image.py
_get_resize_target
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) return ch,int(round(r/ratio)),int(round(c/ratio))
python
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) return ch,int(round(r/ratio)),int(round(c/ratio))
[ "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", ",", "target_c", "=", "crop_target", "ratio", "=", "(", "min", "if", "do_crop", "else", "max", ")", "(", "r", "/", "target_r", ",", "c", "/", "target_c", ")", "return", "ch", ",", "int", "(", "round", "(", "r", "/", "ratio", ")", ")", ",", "int", "(", "round", "(", "c", "/", "ratio", ")", ")" ]
Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`.
[ "Calc", "size", "of", "img", "to", "fit", "in", "crop_target", "-", "adjust", "based", "on", "do_crop", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L594-L600
train
fastai/fastai
fastai/vision/image.py
plot_flat
def plot_flat(r, c, figsize): "Shortcut for `enumerate(subplots.flatten())`" return enumerate(plt.subplots(r, c, figsize=figsize)[1].flatten())
python
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", ")", ":", "return", "enumerate", "(", "plt", ".", "subplots", "(", "r", ",", "c", ",", "figsize", "=", "figsize", ")", "[", "1", "]", ".", "flatten", "(", ")", ")" ]
Shortcut for `enumerate(subplots.flatten())`
[ "Shortcut", "for", "enumerate", "(", "subplots", ".", "flatten", "()", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L602-L604
train
fastai/fastai
fastai/vision/image.py
plot_multi
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])
python
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", ")", ")", ":", "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
[ "Call", "func", "for", "every", "combination", "of", "r", "c", "on", "a", "subplot" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L606-L610
train
fastai/fastai
fastai/vision/image.py
show_multi
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)
python
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", ")", ")", ":", "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`
[ "Call", "func", "(", "i", "j", ")", ".", "show", "(", "ax", ")", "for", "every", "combination", "of", "r", "c" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L612-L614
train
fastai/fastai
fastai/vision/image.py
show_all
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)
python
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", ")", ")", ":", "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
[ "Show", "all", "imgs", "using", "r", "rows" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L616-L620
train
fastai/fastai
fastai/vision/image.py
Image.apply_tfms
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." if not (tfms or xtra or size): return self tfms = listify(tfms) xtra = ifnone(xtra, {}) default_rsz = ResizeMethod.SQUISH if (size is not None and is_listy(size)) else ResizeMethod.CROP resize_method = ifnone(resize_method, default_rsz) if resize_method <= 2 and size is not None: tfms = self._maybe_add_crop_pad(tfms) tfms = sorted(tfms, key=lambda o: o.tfm.order) if do_resolve: _resolve_tfms(tfms) x = self.clone() x.set_sample(padding_mode=padding_mode, mode=mode, remove_out=remove_out) if size is not None: crop_target = _get_crop_target(size, mult=mult) if resize_method in (ResizeMethod.CROP,ResizeMethod.PAD): target = _get_resize_target(x, crop_target, do_crop=(resize_method==ResizeMethod.CROP)) x.resize(target) elif resize_method==ResizeMethod.SQUISH: x.resize((x.shape[0],) + crop_target) else: size = x.size size_tfms = [o for o in tfms if isinstance(o.tfm,TfmCrop)] for tfm in tfms: if tfm.tfm in xtra: x = tfm(x, **xtra[tfm.tfm]) elif tfm in size_tfms: if resize_method in (ResizeMethod.CROP,ResizeMethod.PAD): x = tfm(x, size=_get_crop_target(size,mult=mult), padding_mode=padding_mode) else: x = tfm(x) return x.refresh()
python
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." if not (tfms or xtra or size): return self tfms = listify(tfms) xtra = ifnone(xtra, {}) default_rsz = ResizeMethod.SQUISH if (size is not None and is_listy(size)) else ResizeMethod.CROP resize_method = ifnone(resize_method, default_rsz) if resize_method <= 2 and size is not None: tfms = self._maybe_add_crop_pad(tfms) tfms = sorted(tfms, key=lambda o: o.tfm.order) if do_resolve: _resolve_tfms(tfms) x = self.clone() x.set_sample(padding_mode=padding_mode, mode=mode, remove_out=remove_out) if size is not None: crop_target = _get_crop_target(size, mult=mult) if resize_method in (ResizeMethod.CROP,ResizeMethod.PAD): target = _get_resize_target(x, crop_target, do_crop=(resize_method==ResizeMethod.CROP)) x.resize(target) elif resize_method==ResizeMethod.SQUISH: x.resize((x.shape[0],) + crop_target) else: size = x.size size_tfms = [o for o in tfms if isinstance(o.tfm,TfmCrop)] for tfm in tfms: if tfm.tfm in xtra: x = tfm(x, **xtra[tfm.tfm]) elif tfm in size_tfms: if resize_method in (ResizeMethod.CROP,ResizeMethod.PAD): x = tfm(x, size=_get_crop_target(size,mult=mult), padding_mode=padding_mode) else: x = tfm(x) return x.refresh()
[ "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", ":", "if", "not", "(", "tfms", "or", "xtra", "or", "size", ")", ":", "return", "self", "tfms", "=", "listify", "(", "tfms", ")", "xtra", "=", "ifnone", "(", "xtra", ",", "{", "}", ")", "default_rsz", "=", "ResizeMethod", ".", "SQUISH", "if", "(", "size", "is", "not", "None", "and", "is_listy", "(", "size", ")", ")", "else", "ResizeMethod", ".", "CROP", "resize_method", "=", "ifnone", "(", "resize_method", ",", "default_rsz", ")", "if", "resize_method", "<=", "2", "and", "size", "is", "not", "None", ":", "tfms", "=", "self", ".", "_maybe_add_crop_pad", "(", "tfms", ")", "tfms", "=", "sorted", "(", "tfms", ",", "key", "=", "lambda", "o", ":", "o", ".", "tfm", ".", "order", ")", "if", "do_resolve", ":", "_resolve_tfms", "(", "tfms", ")", "x", "=", "self", ".", "clone", "(", ")", "x", ".", "set_sample", "(", "padding_mode", "=", "padding_mode", ",", "mode", "=", "mode", ",", "remove_out", "=", "remove_out", ")", "if", "size", "is", "not", "None", ":", "crop_target", "=", "_get_crop_target", "(", "size", ",", "mult", "=", "mult", ")", "if", "resize_method", "in", "(", "ResizeMethod", ".", "CROP", ",", "ResizeMethod", ".", "PAD", ")", ":", "target", "=", "_get_resize_target", "(", "x", ",", "crop_target", ",", "do_crop", "=", "(", "resize_method", "==", "ResizeMethod", ".", "CROP", ")", ")", "x", ".", "resize", "(", "target", ")", "elif", "resize_method", "==", "ResizeMethod", ".", "SQUISH", ":", "x", ".", "resize", "(", "(", "x", ".", "shape", "[", "0", "]", ",", ")", "+", "crop_target", ")", "else", ":", "size", "=", "x", ".", "size", "size_tfms", "=", "[", "o", "for", "o", "in", "tfms", "if", "isinstance", "(", "o", ".", "tfm", ",", "TfmCrop", ")", "]", "for", "tfm", "in", "tfms", ":", "if", "tfm", ".", "tfm", "in", "xtra", ":", "x", "=", "tfm", "(", "x", ",", "*", "*", "xtra", "[", "tfm", ".", "tfm", "]", ")", "elif", "tfm", "in", "size_tfms", ":", "if", "resize_method", "in", "(", "ResizeMethod", ".", "CROP", ",", "ResizeMethod", ".", "PAD", ")", ":", "x", "=", "tfm", "(", "x", ",", "size", "=", "_get_crop_target", "(", "size", ",", "mult", "=", "mult", ")", ",", "padding_mode", "=", "padding_mode", ")", "else", ":", "x", "=", "tfm", "(", "x", ")", "return", "x", ".", "refresh", "(", ")" ]
Apply all `tfms` to the `Image`, if `do_resolve` picks value for random args.
[ "Apply", "all", "tfms", "to", "the", "Image", "if", "do_resolve", "picks", "value", "for", "random", "args", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L96-L124
train
fastai/fastai
fastai/vision/image.py
Image.refresh
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._px = _grid_sample(self._px, self.flow, **self.sample_kwargs) self.sample_kwargs = {} self._flow = None return self
python
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._px = _grid_sample(self._px, self.flow, **self.sample_kwargs) self.sample_kwargs = {} self._flow = None return self
[ "def", "refresh", "(", "self", ")", "->", "None", ":", "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", ".", "_px", "=", "_grid_sample", "(", "self", ".", "_px", ",", "self", ".", "flow", ",", "*", "*", "self", ".", "sample_kwargs", ")", "self", ".", "sample_kwargs", "=", "{", "}", "self", ".", "_flow", "=", "None", "return", "self" ]
Apply any logit, flow, or affine transfers that have been sent to the `Image`.
[ "Apply", "any", "logit", "flow", "or", "affine", "transfers", "that", "have", "been", "sent", "to", "the", "Image", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L126-L135
train
fastai/fastai
fastai/vision/image.py
Image.save
def save(self, fn:PathOrStr): "Save the image to `fn`." x = image2np(self.data*255).astype(np.uint8) PIL.Image.fromarray(x).save(fn)
python
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", ")", ":", "x", "=", "image2np", "(", "self", ".", "data", "*", "255", ")", ".", "astype", "(", "np", ".", "uint8", ")", "PIL", ".", "Image", ".", "fromarray", "(", "x", ")", ".", "save", "(", "fn", ")" ]
Save the image to `fn`.
[ "Save", "the", "image", "to", "fn", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L137-L140
train