partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | read_dir | Returns a list of relative file paths to `path` for all files within `folder` | old/fastai/dataset.py | def read_dir(path, folder):
""" Returns a list of relative file paths to `path` for all files within `folder` """
full_path = os.path.join(path, folder)
fnames = glob(f"{full_path}/*.*")
directories = glob(f"{full_path}/*/")
if any(fnames):
return [os.path.relpath(f,path) for f in fnames]
... | def read_dir(path, folder):
""" Returns a list of relative file paths to `path` for all files within `folder` """
full_path = os.path.join(path, folder)
fnames = glob(f"{full_path}/*.*")
directories = glob(f"{full_path}/*/")
if any(fnames):
return [os.path.relpath(f,path) for f in fnames]
... | [
"Returns",
"a",
"list",
"of",
"relative",
"file",
"paths",
"to",
"path",
"for",
"all",
"files",
"within",
"folder"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L89-L99 | [
"def",
"read_dir",
"(",
"path",
",",
"folder",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"folder",
")",
"fnames",
"=",
"glob",
"(",
"f\"{full_path}/*.*\"",
")",
"directories",
"=",
"glob",
"(",
"f\"{full_path}/*/\"",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | read_dirs | Fetches name of all files in path in long form, and labels associated by extrapolation of directory names. | old/fastai/dataset.py | def read_dirs(path, folder):
'''
Fetches name of all files in path in long form, and labels associated by extrapolation of directory names.
'''
lbls, fnames, all_lbls = [], [], []
full_path = os.path.join(path, folder)
for lbl in sorted(os.listdir(full_path)):
if lbl not in ('.ipynb_che... | def read_dirs(path, folder):
'''
Fetches name of all files in path in long form, and labels associated by extrapolation of directory names.
'''
lbls, fnames, all_lbls = [], [], []
full_path = os.path.join(path, folder)
for lbl in sorted(os.listdir(full_path)):
if lbl not in ('.ipynb_che... | [
"Fetches",
"name",
"of",
"all",
"files",
"in",
"path",
"in",
"long",
"form",
"and",
"labels",
"associated",
"by",
"extrapolation",
"of",
"directory",
"names",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L101-L114 | [
"def",
"read_dirs",
"(",
"path",
",",
"folder",
")",
":",
"lbls",
",",
"fnames",
",",
"all_lbls",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"folder",
")",
"for",
"lbl",
"in"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | n_hot | one hot encoding by index. Returns array of length c, where all entries are 0, except for the indecies in ids | old/fastai/dataset.py | def n_hot(ids, c):
'''
one hot encoding by index. Returns array of length c, where all entries are 0, except for the indecies in ids
'''
res = np.zeros((c,), dtype=np.float32)
res[ids] = 1
return res | def n_hot(ids, c):
'''
one hot encoding by index. Returns array of length c, where all entries are 0, except for the indecies in ids
'''
res = np.zeros((c,), dtype=np.float32)
res[ids] = 1
return res | [
"one",
"hot",
"encoding",
"by",
"index",
".",
"Returns",
"array",
"of",
"length",
"c",
"where",
"all",
"entries",
"are",
"0",
"except",
"for",
"the",
"indecies",
"in",
"ids"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L116-L122 | [
"def",
"n_hot",
"(",
"ids",
",",
"c",
")",
":",
"res",
"=",
"np",
".",
"zeros",
"(",
"(",
"c",
",",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"res",
"[",
"ids",
"]",
"=",
"1",
"return",
"res"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | folder_source | Returns the filenames and labels for a folder within a path
Returns:
-------
fnames: a list of the filenames within `folder`
all_lbls: a list of all of the labels in `folder`, where the # of labels is determined by the # of directories within `folder`
lbl_arr: a numpy array of the label indices... | old/fastai/dataset.py | def folder_source(path, folder):
"""
Returns the filenames and labels for a folder within a path
Returns:
-------
fnames: a list of the filenames within `folder`
all_lbls: a list of all of the labels in `folder`, where the # of labels is determined by the # of directories within `folder`
... | def folder_source(path, folder):
"""
Returns the filenames and labels for a folder within a path
Returns:
-------
fnames: a list of the filenames within `folder`
all_lbls: a list of all of the labels in `folder`, where the # of labels is determined by the # of directories within `folder`
... | [
"Returns",
"the",
"filenames",
"and",
"labels",
"for",
"a",
"folder",
"within",
"a",
"path",
"Returns",
":",
"-------",
"fnames",
":",
"a",
"list",
"of",
"the",
"filenames",
"within",
"folder",
"all_lbls",
":",
"a",
"list",
"of",
"all",
"of",
"the",
"lab... | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L124-L138 | [
"def",
"folder_source",
"(",
"path",
",",
"folder",
")",
":",
"fnames",
",",
"lbls",
",",
"all_lbls",
"=",
"read_dirs",
"(",
"path",
",",
"folder",
")",
"lbl2idx",
"=",
"{",
"lbl",
":",
"idx",
"for",
"idx",
",",
"lbl",
"in",
"enumerate",
"(",
"all_lb... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | parse_csv_labels | Parse filenames and label sets from a CSV file.
This method expects that the csv file at path :fn: has two columns. If it
has a header, :skip_header: should be set to True. The labels in the
label set are expected to be space separated.
Arguments:
fn: Path to a CSV file.
skip_header: A... | old/fastai/dataset.py | def parse_csv_labels(fn, skip_header=True, cat_separator = ' '):
"""Parse filenames and label sets from a CSV file.
This method expects that the csv file at path :fn: has two columns. If it
has a header, :skip_header: should be set to True. The labels in the
label set are expected to be space separated... | def parse_csv_labels(fn, skip_header=True, cat_separator = ' '):
"""Parse filenames and label sets from a CSV file.
This method expects that the csv file at path :fn: has two columns. If it
has a header, :skip_header: should be set to True. The labels in the
label set are expected to be space separated... | [
"Parse",
"filenames",
"and",
"label",
"sets",
"from",
"a",
"CSV",
"file",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L140-L162 | [
"def",
"parse_csv_labels",
"(",
"fn",
",",
"skip_header",
"=",
"True",
",",
"cat_separator",
"=",
"' '",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"fn",
",",
"index_col",
"=",
"0",
",",
"header",
"=",
"0",
"if",
"skip_header",
"else",
"None",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | isdicom | True if the fn points to a DICOM image | old/fastai/dataset.py | def isdicom(fn):
'''True if the fn points to a DICOM image'''
fn = str(fn)
if fn.endswith('.dcm'):
return True
# Dicom signature from the dicom spec.
with open(fn,'rb') as fh:
fh.seek(0x80)
return fh.read(4)==b'DICM' | def isdicom(fn):
'''True if the fn points to a DICOM image'''
fn = str(fn)
if fn.endswith('.dcm'):
return True
# Dicom signature from the dicom spec.
with open(fn,'rb') as fh:
fh.seek(0x80)
return fh.read(4)==b'DICM' | [
"True",
"if",
"the",
"fn",
"points",
"to",
"a",
"DICOM",
"image"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L245-L253 | [
"def",
"isdicom",
"(",
"fn",
")",
":",
"fn",
"=",
"str",
"(",
"fn",
")",
"if",
"fn",
".",
"endswith",
"(",
"'.dcm'",
")",
":",
"return",
"True",
"# Dicom signature from the dicom spec.",
"with",
"open",
"(",
"fn",
",",
"'rb'",
")",
"as",
"fh",
":",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | open_image | Opens an image using OpenCV given the file path.
Arguments:
fn: the file path of the image
Returns:
The image in RGB format as numpy array of floats normalized to range between 0.0 - 1.0 | old/fastai/dataset.py | def open_image(fn):
""" Opens an image using OpenCV given the file path.
Arguments:
fn: the file path of the image
Returns:
The image in RGB format as numpy array of floats normalized to range between 0.0 - 1.0
"""
flags = cv2.IMREAD_UNCHANGED+cv2.IMREAD_ANYDEPTH+cv2.IMREAD_ANYCOLO... | def open_image(fn):
""" Opens an image using OpenCV given the file path.
Arguments:
fn: the file path of the image
Returns:
The image in RGB format as numpy array of floats normalized to range between 0.0 - 1.0
"""
flags = cv2.IMREAD_UNCHANGED+cv2.IMREAD_ANYDEPTH+cv2.IMREAD_ANYCOLO... | [
"Opens",
"an",
"image",
"using",
"OpenCV",
"given",
"the",
"file",
"path",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L255-L293 | [
"def",
"open_image",
"(",
"fn",
")",
":",
"flags",
"=",
"cv2",
".",
"IMREAD_UNCHANGED",
"+",
"cv2",
".",
"IMREAD_ANYDEPTH",
"+",
"cv2",
".",
"IMREAD_ANYCOLOR",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
"and",
"not",
"str",
"(",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | split_by_idx | Split each array passed as *a, to a pair of arrays like this (elements selected by idxs, the remaining elements)
This can be used to split multiple arrays containing training data to validation and training set.
:param idxs [int]: list of indexes selected
:param a list: list of np.array, each array should... | old/fastai/dataset.py | def split_by_idx(idxs, *a):
"""
Split each array passed as *a, to a pair of arrays like this (elements selected by idxs, the remaining elements)
This can be used to split multiple arrays containing training data to validation and training set.
:param idxs [int]: list of indexes selected
:param a l... | def split_by_idx(idxs, *a):
"""
Split each array passed as *a, to a pair of arrays like this (elements selected by idxs, the remaining elements)
This can be used to split multiple arrays containing training data to validation and training set.
:param idxs [int]: list of indexes selected
:param a l... | [
"Split",
"each",
"array",
"passed",
"as",
"*",
"a",
"to",
"a",
"pair",
"of",
"arrays",
"like",
"this",
"(",
"elements",
"selected",
"by",
"idxs",
"the",
"remaining",
"elements",
")",
"This",
"can",
"be",
"used",
"to",
"split",
"multiple",
"arrays",
"cont... | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L594-L607 | [
"def",
"split_by_idx",
"(",
"idxs",
",",
"*",
"a",
")",
":",
"mask",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"a",
"[",
"0",
"]",
")",
",",
"dtype",
"=",
"bool",
")",
"mask",
"[",
"np",
".",
"array",
"(",
"idxs",
")",
"]",
"=",
"True",
"re... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | FilesDataset.resize_imgs | resize all images in the dataset and save them to `new_path`
Arguments:
targ (int): the target size
new_path (string): the new folder to save the images
resume (bool): if true (default), allow resuming a partial resize operation by checking for the existence
of individua... | old/fastai/dataset.py | def resize_imgs(self, targ, new_path, resume=True, fn=None):
"""
resize all images in the dataset and save them to `new_path`
Arguments:
targ (int): the target size
new_path (string): the new folder to save the images
resume (bool): if true (default), allow resum... | def resize_imgs(self, targ, new_path, resume=True, fn=None):
"""
resize all images in the dataset and save them to `new_path`
Arguments:
targ (int): the target size
new_path (string): the new folder to save the images
resume (bool): if true (default), allow resum... | [
"resize",
"all",
"images",
"in",
"the",
"dataset",
"and",
"save",
"them",
"to",
"new_path",
"Arguments",
":",
"targ",
"(",
"int",
")",
":",
"the",
"target",
"size",
"new_path",
"(",
"string",
")",
":",
"the",
"new",
"folder",
"to",
"save",
"the",
"imag... | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L303-L315 | [
"def",
"resize_imgs",
"(",
"self",
",",
"targ",
",",
"new_path",
",",
"resume",
"=",
"True",
",",
"fn",
"=",
"None",
")",
":",
"dest",
"=",
"resize_imgs",
"(",
"self",
".",
"fnames",
",",
"targ",
",",
"self",
".",
"path",
",",
"new_path",
",",
"res... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | FilesDataset.denorm | Reverse the normalization done to a batch of images.
Arguments:
arr: of shape/size (N,3,sz,sz) | old/fastai/dataset.py | def denorm(self,arr):
"""Reverse the normalization done to a batch of images.
Arguments:
arr: of shape/size (N,3,sz,sz)
"""
if type(arr) is not np.ndarray: arr = to_np(arr)
if len(arr.shape)==3: arr = arr[None]
return self.transform.denorm(np.rollaxis(arr,1,4... | def denorm(self,arr):
"""Reverse the normalization done to a batch of images.
Arguments:
arr: of shape/size (N,3,sz,sz)
"""
if type(arr) is not np.ndarray: arr = to_np(arr)
if len(arr.shape)==3: arr = arr[None]
return self.transform.denorm(np.rollaxis(arr,1,4... | [
"Reverse",
"the",
"normalization",
"done",
"to",
"a",
"batch",
"of",
"images",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L317-L325 | [
"def",
"denorm",
"(",
"self",
",",
"arr",
")",
":",
"if",
"type",
"(",
"arr",
")",
"is",
"not",
"np",
".",
"ndarray",
":",
"arr",
"=",
"to_np",
"(",
"arr",
")",
"if",
"len",
"(",
"arr",
".",
"shape",
")",
"==",
"3",
":",
"arr",
"=",
"arr",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ImageData.resized | Return a copy of this dataset resized | old/fastai/dataset.py | def resized(self, dl, targ, new_path, resume = True, fn=None):
"""
Return a copy of this dataset resized
"""
return dl.dataset.resize_imgs(targ, new_path, resume=resume, fn=fn) if dl else None | def resized(self, dl, targ, new_path, resume = True, fn=None):
"""
Return a copy of this dataset resized
"""
return dl.dataset.resize_imgs(targ, new_path, resume=resume, fn=fn) if dl else None | [
"Return",
"a",
"copy",
"of",
"this",
"dataset",
"resized"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L423-L427 | [
"def",
"resized",
"(",
"self",
",",
"dl",
",",
"targ",
",",
"new_path",
",",
"resume",
"=",
"True",
",",
"fn",
"=",
"None",
")",
":",
"return",
"dl",
".",
"dataset",
".",
"resize_imgs",
"(",
"targ",
",",
"new_path",
",",
"resume",
"=",
"resume",
",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ImageData.resize | Resizes all the images in the train, valid, test folders to a given size.
Arguments:
targ_sz (int): the target size
new_path (str): the path to save the resized images (default tmp)
resume (bool): if True, check for images in the DataSet that haven't been resized yet (useful if a previo... | old/fastai/dataset.py | def resize(self, targ_sz, new_path='tmp', resume=True, fn=None):
"""
Resizes all the images in the train, valid, test folders to a given size.
Arguments:
targ_sz (int): the target size
new_path (str): the path to save the resized images (default tmp)
resume (bool): if Tr... | def resize(self, targ_sz, new_path='tmp', resume=True, fn=None):
"""
Resizes all the images in the train, valid, test folders to a given size.
Arguments:
targ_sz (int): the target size
new_path (str): the path to save the resized images (default tmp)
resume (bool): if Tr... | [
"Resizes",
"all",
"the",
"images",
"in",
"the",
"train",
"valid",
"test",
"folders",
"to",
"a",
"given",
"size",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L429-L447 | [
"def",
"resize",
"(",
"self",
",",
"targ_sz",
",",
"new_path",
"=",
"'tmp'",
",",
"resume",
"=",
"True",
",",
"fn",
"=",
"None",
")",
":",
"new_ds",
"=",
"[",
"]",
"dls",
"=",
"[",
"self",
".",
"trn_dl",
",",
"self",
".",
"val_dl",
",",
"self",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ImageClassifierData.from_arrays | Read in images and their labels given as numpy arrays
Arguments:
path: a root path of the data (used for storing trained models, precomputed values, etc)
trn: a tuple of training data matrix and target label/classification array (e.g. `trn=(x,y)` where `x` has the
shape ... | old/fastai/dataset.py | def from_arrays(cls, path, trn, val, bs=64, tfms=(None,None), classes=None, num_workers=4, test=None, continuous=False):
""" Read in images and their labels given as numpy arrays
Arguments:
path: a root path of the data (used for storing trained models, precomputed values, etc)
... | def from_arrays(cls, path, trn, val, bs=64, tfms=(None,None), classes=None, num_workers=4, test=None, continuous=False):
""" Read in images and their labels given as numpy arrays
Arguments:
path: a root path of the data (used for storing trained models, precomputed values, etc)
... | [
"Read",
"in",
"images",
"and",
"their",
"labels",
"given",
"as",
"numpy",
"arrays"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L476-L495 | [
"def",
"from_arrays",
"(",
"cls",
",",
"path",
",",
"trn",
",",
"val",
",",
"bs",
"=",
"64",
",",
"tfms",
"=",
"(",
"None",
",",
"None",
")",
",",
"classes",
"=",
"None",
",",
"num_workers",
"=",
"4",
",",
"test",
"=",
"None",
",",
"continuous",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ImageClassifierData.from_paths | Read in images and their labels given as sub-folder names
Arguments:
path: a root path of the data (used for storing trained models, precomputed values, etc)
bs: batch size
tfms: transformations (for data augmentations). e.g. output of `tfms_from_model`
trn_name:... | old/fastai/dataset.py | def from_paths(cls, path, bs=64, tfms=(None,None), trn_name='train', val_name='valid', test_name=None, test_with_labels=False, num_workers=8):
""" Read in images and their labels given as sub-folder names
Arguments:
path: a root path of the data (used for storing trained models, precomputed... | def from_paths(cls, path, bs=64, tfms=(None,None), trn_name='train', val_name='valid', test_name=None, test_with_labels=False, num_workers=8):
""" Read in images and their labels given as sub-folder names
Arguments:
path: a root path of the data (used for storing trained models, precomputed... | [
"Read",
"in",
"images",
"and",
"their",
"labels",
"given",
"as",
"sub",
"-",
"folder",
"names"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L498-L519 | [
"def",
"from_paths",
"(",
"cls",
",",
"path",
",",
"bs",
"=",
"64",
",",
"tfms",
"=",
"(",
"None",
",",
"None",
")",
",",
"trn_name",
"=",
"'train'",
",",
"val_name",
"=",
"'valid'",
",",
"test_name",
"=",
"None",
",",
"test_with_labels",
"=",
"False... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ImageClassifierData.from_csv | Read in images and their labels given as a CSV file.
This method should be used when training image labels are given in an CSV file as opposed to
sub-directories with label names.
Arguments:
path: a root path of the data (used for storing trained models, precomputed values, etc)
... | old/fastai/dataset.py | def from_csv(cls, path, folder, csv_fname, bs=64, tfms=(None,None),
val_idxs=None, suffix='', test_name=None, continuous=False, skip_header=True, num_workers=8, cat_separator=' '):
""" Read in images and their labels given as a CSV file.
This method should be used when training image lab... | def from_csv(cls, path, folder, csv_fname, bs=64, tfms=(None,None),
val_idxs=None, suffix='', test_name=None, continuous=False, skip_header=True, num_workers=8, cat_separator=' '):
""" Read in images and their labels given as a CSV file.
This method should be used when training image lab... | [
"Read",
"in",
"images",
"and",
"their",
"labels",
"given",
"as",
"a",
"CSV",
"file",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L522-L553 | [
"def",
"from_csv",
"(",
"cls",
",",
"path",
",",
"folder",
",",
"csv_fname",
",",
"bs",
"=",
"64",
",",
"tfms",
"=",
"(",
"None",
",",
"None",
")",
",",
"val_idxs",
"=",
"None",
",",
"suffix",
"=",
"''",
",",
"test_name",
"=",
"None",
",",
"conti... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | ImageClassifierData.from_path_and_array | Read in images given a sub-folder and their labels given a numpy array
Arguments:
path: a root path of the data (used for storing trained models, precomputed values, etc)
folder: a name of the folder in which training images are contained.
y: numpy array which contains targe... | old/fastai/dataset.py | def from_path_and_array(cls, path, folder, y, classes=None, val_idxs=None, test_name=None,
num_workers=8, tfms=(None,None), bs=64):
""" Read in images given a sub-folder and their labels given a numpy array
Arguments:
path: a root path of the data (used for storing trained model... | def from_path_and_array(cls, path, folder, y, classes=None, val_idxs=None, test_name=None,
num_workers=8, tfms=(None,None), bs=64):
""" Read in images given a sub-folder and their labels given a numpy array
Arguments:
path: a root path of the data (used for storing trained model... | [
"Read",
"in",
"images",
"given",
"a",
"sub",
"-",
"folder",
"and",
"their",
"labels",
"given",
"a",
"numpy",
"array"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L556-L578 | [
"def",
"from_path_and_array",
"(",
"cls",
",",
"path",
",",
"folder",
",",
"y",
",",
"classes",
"=",
"None",
",",
"val_idxs",
"=",
"None",
",",
"test_name",
"=",
"None",
",",
"num_workers",
"=",
"8",
",",
"tfms",
"=",
"(",
"None",
",",
"None",
")",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | is_in_ipython | Is the code running in the ipython environment (jupyter including) | fastai/utils/ipython.py | def is_in_ipython():
"Is the code running in the ipython environment (jupyter including)"
program_name = os.path.basename(os.getenv('_', ''))
if ('jupyter-notebook' in program_name or # jupyter-notebook
'ipython' in program_name or # ipython
'JPY_PARENT_PID' in os.environ): #... | def is_in_ipython():
"Is the code running in the ipython environment (jupyter including)"
program_name = os.path.basename(os.getenv('_', ''))
if ('jupyter-notebook' in program_name or # jupyter-notebook
'ipython' in program_name or # ipython
'JPY_PARENT_PID' in os.environ): #... | [
"Is",
"the",
"code",
"running",
"in",
"the",
"ipython",
"environment",
"(",
"jupyter",
"including",
")"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/utils/ipython.py#L5-L15 | [
"def",
"is_in_ipython",
"(",
")",
":",
"program_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"getenv",
"(",
"'_'",
",",
"''",
")",
")",
"if",
"(",
"'jupyter-notebook'",
"in",
"program_name",
"or",
"# jupyter-notebook",
"'ipython'",
"in",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | get_ref_free_exc_info | Free traceback from references to locals() in each frame to avoid circular reference leading to gc.collect() unable to reclaim memory | fastai/utils/ipython.py | def get_ref_free_exc_info():
"Free traceback from references to locals() in each frame to avoid circular reference leading to gc.collect() unable to reclaim memory"
type, val, tb = sys.exc_info()
traceback.clear_frames(tb)
return (type, val, tb) | def get_ref_free_exc_info():
"Free traceback from references to locals() in each frame to avoid circular reference leading to gc.collect() unable to reclaim memory"
type, val, tb = sys.exc_info()
traceback.clear_frames(tb)
return (type, val, tb) | [
"Free",
"traceback",
"from",
"references",
"to",
"locals",
"()",
"in",
"each",
"frame",
"to",
"avoid",
"circular",
"reference",
"leading",
"to",
"gc",
".",
"collect",
"()",
"unable",
"to",
"reclaim",
"memory"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/utils/ipython.py#L29-L33 | [
"def",
"get_ref_free_exc_info",
"(",
")",
":",
"type",
",",
"val",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"traceback",
".",
"clear_frames",
"(",
"tb",
")",
"return",
"(",
"type",
",",
"val",
",",
"tb",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | gpu_mem_restore | Reclaim GPU RAM if CUDA out of memory happened, or execution was interrupted | fastai/utils/ipython.py | def gpu_mem_restore(func):
"Reclaim GPU RAM if CUDA out of memory happened, or execution was interrupted"
@functools.wraps(func)
def wrapper(*args, **kwargs):
tb_clear_frames = os.environ.get('FASTAI_TB_CLEAR_FRAMES', None)
if not IS_IN_IPYTHON or tb_clear_frames=="0":
return fun... | def gpu_mem_restore(func):
"Reclaim GPU RAM if CUDA out of memory happened, or execution was interrupted"
@functools.wraps(func)
def wrapper(*args, **kwargs):
tb_clear_frames = os.environ.get('FASTAI_TB_CLEAR_FRAMES', None)
if not IS_IN_IPYTHON or tb_clear_frames=="0":
return fun... | [
"Reclaim",
"GPU",
"RAM",
"if",
"CUDA",
"out",
"of",
"memory",
"happened",
"or",
"execution",
"was",
"interrupted"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/utils/ipython.py#L35-L55 | [
"def",
"gpu_mem_restore",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tb_clear_frames",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'FASTAI_TB_CLEAR_F... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | fit | Fits a model
Arguments:
model (model): any pytorch module
net = to_gpu(net)
data (ModelData): see ModelData class and subclasses (can be a list)
opts: an optimizer. Example: optim.Adam.
If n_epochs is a list, it needs to be the layer_optimizer to get the optimizer as it chan... | old/fastai/model.py | def fit(model, data, n_epochs, opt, crit, metrics=None, callbacks=None, stepper=Stepper,
swa_model=None, swa_start=None, swa_eval_freq=None, visualize=False, **kwargs):
""" Fits a model
Arguments:
model (model): any pytorch module
net = to_gpu(net)
data (ModelData): see ModelDa... | def fit(model, data, n_epochs, opt, crit, metrics=None, callbacks=None, stepper=Stepper,
swa_model=None, swa_start=None, swa_eval_freq=None, visualize=False, **kwargs):
""" Fits a model
Arguments:
model (model): any pytorch module
net = to_gpu(net)
data (ModelData): see ModelDa... | [
"Fits",
"a",
"model"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/model.py#L88-L181 | [
"def",
"fit",
"(",
"model",
",",
"data",
",",
"n_epochs",
",",
"opt",
",",
"crit",
",",
"metrics",
"=",
"None",
",",
"callbacks",
"=",
"None",
",",
"stepper",
"=",
"Stepper",
",",
"swa_model",
"=",
"None",
",",
"swa_start",
"=",
"None",
",",
"swa_eva... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | validate_next | Computes the loss on the next minibatch of the validation set. | old/fastai/model.py | def validate_next(stepper, metrics, val_iter):
"""Computes the loss on the next minibatch of the validation set."""
stepper.reset(False)
with no_grad_context():
(*x,y) = val_iter.next()
preds,l = stepper.evaluate(VV(x), VV(y))
res = [delistify(to_np(l))]
res += [f(datafy(pred... | def validate_next(stepper, metrics, val_iter):
"""Computes the loss on the next minibatch of the validation set."""
stepper.reset(False)
with no_grad_context():
(*x,y) = val_iter.next()
preds,l = stepper.evaluate(VV(x), VV(y))
res = [delistify(to_np(l))]
res += [f(datafy(pred... | [
"Computes",
"the",
"loss",
"on",
"the",
"next",
"minibatch",
"of",
"the",
"validation",
"set",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/model.py#L215-L224 | [
"def",
"validate_next",
"(",
"stepper",
",",
"metrics",
",",
"val_iter",
")",
":",
"stepper",
".",
"reset",
"(",
"False",
")",
"with",
"no_grad_context",
"(",
")",
":",
"(",
"*",
"x",
",",
"y",
")",
"=",
"val_iter",
".",
"next",
"(",
")",
"preds",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | link_type | Create link to documentation. | fastai/gen_doc/nbdoc.py | def link_type(arg_type, arg_name=None, include_bt:bool=True):
"Create link to documentation."
arg_name = arg_name or fn_name(arg_type)
if include_bt: arg_name = code_esc(arg_name)
if belongs_to_module(arg_type, 'torch') and ('Tensor' not in arg_name): return f'[{arg_name}]({get_pytorch_link(arg_type)})'... | def link_type(arg_type, arg_name=None, include_bt:bool=True):
"Create link to documentation."
arg_name = arg_name or fn_name(arg_type)
if include_bt: arg_name = code_esc(arg_name)
if belongs_to_module(arg_type, 'torch') and ('Tensor' not in arg_name): return f'[{arg_name}]({get_pytorch_link(arg_type)})'... | [
"Create",
"link",
"to",
"documentation",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L31-L37 | [
"def",
"link_type",
"(",
"arg_type",
",",
"arg_name",
"=",
"None",
",",
"include_bt",
":",
"bool",
"=",
"True",
")",
":",
"arg_name",
"=",
"arg_name",
"or",
"fn_name",
"(",
"arg_type",
")",
"if",
"include_bt",
":",
"arg_name",
"=",
"code_esc",
"(",
"arg_... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | belongs_to_module | Check if `t` belongs to `module_name`. | fastai/gen_doc/nbdoc.py | def belongs_to_module(t, module_name):
"Check if `t` belongs to `module_name`."
if hasattr(t, '__func__'): return belongs_to_module(t.__func__, module_name)
if not inspect.getmodule(t): return False
return inspect.getmodule(t).__name__.startswith(module_name) | def belongs_to_module(t, module_name):
"Check if `t` belongs to `module_name`."
if hasattr(t, '__func__'): return belongs_to_module(t.__func__, module_name)
if not inspect.getmodule(t): return False
return inspect.getmodule(t).__name__.startswith(module_name) | [
"Check",
"if",
"t",
"belongs",
"to",
"module_name",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L41-L45 | [
"def",
"belongs_to_module",
"(",
"t",
",",
"module_name",
")",
":",
"if",
"hasattr",
"(",
"t",
",",
"'__func__'",
")",
":",
"return",
"belongs_to_module",
"(",
"t",
".",
"__func__",
",",
"module_name",
")",
"if",
"not",
"inspect",
".",
"getmodule",
"(",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | format_param | Formats function param to `param1:Type=val`. Font weights: param1=bold, val=bold+italic | fastai/gen_doc/nbdoc.py | def format_param(p):
"Formats function param to `param1:Type=val`. Font weights: param1=bold, val=bold+italic"
arg_prefix = arg_prefixes.get(p.kind, '') # asterisk prefix for *args and **kwargs
res = f"**{arg_prefix}{code_esc(p.name)}**"
if hasattr(p, 'annotation') and p.annotation != p.empty: res += f'... | def format_param(p):
"Formats function param to `param1:Type=val`. Font weights: param1=bold, val=bold+italic"
arg_prefix = arg_prefixes.get(p.kind, '') # asterisk prefix for *args and **kwargs
res = f"**{arg_prefix}{code_esc(p.name)}**"
if hasattr(p, 'annotation') and p.annotation != p.empty: res += f'... | [
"Formats",
"function",
"param",
"to",
"param1",
":",
"Type",
"=",
"val",
".",
"Font",
"weights",
":",
"param1",
"=",
"bold",
"val",
"=",
"bold",
"+",
"italic"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L68-L77 | [
"def",
"format_param",
"(",
"p",
")",
":",
"arg_prefix",
"=",
"arg_prefixes",
".",
"get",
"(",
"p",
".",
"kind",
",",
"''",
")",
"# asterisk prefix for *args and **kwargs",
"res",
"=",
"f\"**{arg_prefix}{code_esc(p.name)}**\"",
"if",
"hasattr",
"(",
"p",
",",
"'... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | format_ft_def | Format and link `func` definition to show in documentation | fastai/gen_doc/nbdoc.py | def format_ft_def(func, full_name:str=None)->str:
"Format and link `func` definition to show in documentation"
sig = inspect.signature(func)
name = f'<code>{full_name or func.__name__}</code>'
fmt_params = [format_param(param) for name,param
in sig.parameters.items() if name not in ('s... | def format_ft_def(func, full_name:str=None)->str:
"Format and link `func` definition to show in documentation"
sig = inspect.signature(func)
name = f'<code>{full_name or func.__name__}</code>'
fmt_params = [format_param(param) for name,param
in sig.parameters.items() if name not in ('s... | [
"Format",
"and",
"link",
"func",
"definition",
"to",
"show",
"in",
"documentation"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L79-L89 | [
"def",
"format_ft_def",
"(",
"func",
",",
"full_name",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"name",
"=",
"f'<code>{full_name or func.__name__}</code>'",
"fmt_params",
"=",
"[",
"format_param... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | get_enum_doc | Formatted enum documentation. | fastai/gen_doc/nbdoc.py | def get_enum_doc(elt, full_name:str)->str:
"Formatted enum documentation."
vals = ', '.join(elt.__members__.keys())
return f'{code_esc(full_name)}',f'<code>Enum</code> = [{vals}]' | def get_enum_doc(elt, full_name:str)->str:
"Formatted enum documentation."
vals = ', '.join(elt.__members__.keys())
return f'{code_esc(full_name)}',f'<code>Enum</code> = [{vals}]' | [
"Formatted",
"enum",
"documentation",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L91-L94 | [
"def",
"get_enum_doc",
"(",
"elt",
",",
"full_name",
":",
"str",
")",
"->",
"str",
":",
"vals",
"=",
"', '",
".",
"join",
"(",
"elt",
".",
"__members__",
".",
"keys",
"(",
")",
")",
"return",
"f'{code_esc(full_name)}'",
",",
"f'<code>Enum</code> = [{vals}]'"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | get_cls_doc | Class definition. | fastai/gen_doc/nbdoc.py | def get_cls_doc(elt, full_name:str)->str:
"Class definition."
parent_class = inspect.getclasstree([elt])[-1][0][1][0]
name,args = format_ft_def(elt, full_name)
if parent_class != object: args += f' :: {link_type(parent_class, include_bt=True)}'
return name,args | def get_cls_doc(elt, full_name:str)->str:
"Class definition."
parent_class = inspect.getclasstree([elt])[-1][0][1][0]
name,args = format_ft_def(elt, full_name)
if parent_class != object: args += f' :: {link_type(parent_class, include_bt=True)}'
return name,args | [
"Class",
"definition",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L96-L101 | [
"def",
"get_cls_doc",
"(",
"elt",
",",
"full_name",
":",
"str",
")",
"->",
"str",
":",
"parent_class",
"=",
"inspect",
".",
"getclasstree",
"(",
"[",
"elt",
"]",
")",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
"name",
",",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | show_doc | Show documentation for element `elt`. Supported types: class, Callable, and enum. | fastai/gen_doc/nbdoc.py | def show_doc(elt, doc_string:bool=True, full_name:str=None, arg_comments:dict=None, title_level=None, alt_doc_string:str='',
ignore_warn:bool=False, markdown=True, show_tests=True):
"Show documentation for element `elt`. Supported types: class, Callable, and enum."
arg_comments = ifnone(arg_comment... | def show_doc(elt, doc_string:bool=True, full_name:str=None, arg_comments:dict=None, title_level=None, alt_doc_string:str='',
ignore_warn:bool=False, markdown=True, show_tests=True):
"Show documentation for element `elt`. Supported types: class, Callable, and enum."
arg_comments = ifnone(arg_comment... | [
"Show",
"documentation",
"for",
"element",
"elt",
".",
"Supported",
"types",
":",
"class",
"Callable",
"and",
"enum",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L103-L124 | [
"def",
"show_doc",
"(",
"elt",
",",
"doc_string",
":",
"bool",
"=",
"True",
",",
"full_name",
":",
"str",
"=",
"None",
",",
"arg_comments",
":",
"dict",
"=",
"None",
",",
"title_level",
"=",
"None",
",",
"alt_doc_string",
":",
"str",
"=",
"''",
",",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | doc | Show `show_doc` info in preview window along with link to full docs. | fastai/gen_doc/nbdoc.py | def doc(elt):
"Show `show_doc` info in preview window along with link to full docs."
global use_relative_links
use_relative_links = False
elt = getattr(elt, '__func__', elt)
md = show_doc(elt, markdown=False)
if is_fastai_class(elt):
md += f'\n\n<a href="{get_fn_link(elt)}" target="_blan... | def doc(elt):
"Show `show_doc` info in preview window along with link to full docs."
global use_relative_links
use_relative_links = False
elt = getattr(elt, '__func__', elt)
md = show_doc(elt, markdown=False)
if is_fastai_class(elt):
md += f'\n\n<a href="{get_fn_link(elt)}" target="_blan... | [
"Show",
"show_doc",
"info",
"in",
"preview",
"window",
"along",
"with",
"link",
"to",
"full",
"docs",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L126-L139 | [
"def",
"doc",
"(",
"elt",
")",
":",
"global",
"use_relative_links",
"use_relative_links",
"=",
"False",
"elt",
"=",
"getattr",
"(",
"elt",
",",
"'__func__'",
",",
"elt",
")",
"md",
"=",
"show_doc",
"(",
"elt",
",",
"markdown",
"=",
"False",
")",
"if",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | format_docstring | Merge and format the docstring definition with `arg_comments` and `alt_doc_string`. | fastai/gen_doc/nbdoc.py | def format_docstring(elt, arg_comments:dict={}, alt_doc_string:str='', ignore_warn:bool=False)->str:
"Merge and format the docstring definition with `arg_comments` and `alt_doc_string`."
parsed = ""
doc = parse_docstring(inspect.getdoc(elt))
description = alt_doc_string or f"{doc['short_description']} {... | def format_docstring(elt, arg_comments:dict={}, alt_doc_string:str='', ignore_warn:bool=False)->str:
"Merge and format the docstring definition with `arg_comments` and `alt_doc_string`."
parsed = ""
doc = parse_docstring(inspect.getdoc(elt))
description = alt_doc_string or f"{doc['short_description']} {... | [
"Merge",
"and",
"format",
"the",
"docstring",
"definition",
"with",
"arg_comments",
"and",
"alt_doc_string",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L141-L157 | [
"def",
"format_docstring",
"(",
"elt",
",",
"arg_comments",
":",
"dict",
"=",
"{",
"}",
",",
"alt_doc_string",
":",
"str",
"=",
"''",
",",
"ignore_warn",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"parsed",
"=",
"\"\"",
"doc",
"=",
"parse_docstr... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | link_docstring | Search `docstring` for backticks and attempt to link those functions to respective documentation. | fastai/gen_doc/nbdoc.py | def link_docstring(modules, docstring:str, overwrite:bool=False)->str:
"Search `docstring` for backticks and attempt to link those functions to respective documentation."
mods = listify(modules)
for mod in mods: _modvars.update(mod.__dict__) # concat all module definitions
return re.sub(BT_REGEX, replac... | def link_docstring(modules, docstring:str, overwrite:bool=False)->str:
"Search `docstring` for backticks and attempt to link those functions to respective documentation."
mods = listify(modules)
for mod in mods: _modvars.update(mod.__dict__) # concat all module definitions
return re.sub(BT_REGEX, replac... | [
"Search",
"docstring",
"for",
"backticks",
"and",
"attempt",
"to",
"link",
"those",
"functions",
"to",
"respective",
"documentation",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L169-L173 | [
"def",
"link_docstring",
"(",
"modules",
",",
"docstring",
":",
"str",
",",
"overwrite",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"mods",
"=",
"listify",
"(",
"modules",
")",
"for",
"mod",
"in",
"mods",
":",
"_modvars",
".",
"update",
"(",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | find_elt | Attempt to resolve keywords such as Learner.lr_find. `match_last` starts matching from last component. | fastai/gen_doc/nbdoc.py | def find_elt(modvars, keyword, match_last=False):
"Attempt to resolve keywords such as Learner.lr_find. `match_last` starts matching from last component."
keyword = strip_fastai(keyword)
if keyword in modvars: return modvars[keyword]
comps = keyword.split('.')
comp_elt = modvars.get(comps[0])
if... | def find_elt(modvars, keyword, match_last=False):
"Attempt to resolve keywords such as Learner.lr_find. `match_last` starts matching from last component."
keyword = strip_fastai(keyword)
if keyword in modvars: return modvars[keyword]
comps = keyword.split('.')
comp_elt = modvars.get(comps[0])
if... | [
"Attempt",
"to",
"resolve",
"keywords",
"such",
"as",
"Learner",
".",
"lr_find",
".",
"match_last",
"starts",
"matching",
"from",
"last",
"component",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L175-L181 | [
"def",
"find_elt",
"(",
"modvars",
",",
"keyword",
",",
"match_last",
"=",
"False",
")",
":",
"keyword",
"=",
"strip_fastai",
"(",
"keyword",
")",
"if",
"keyword",
"in",
"modvars",
":",
"return",
"modvars",
"[",
"keyword",
"]",
"comps",
"=",
"keyword",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | import_mod | Return module from `mod_name`. | fastai/gen_doc/nbdoc.py | def import_mod(mod_name:str, ignore_errors=False):
"Return module from `mod_name`."
splits = str.split(mod_name, '.')
try:
if len(splits) > 1 : mod = importlib.import_module('.' + '.'.join(splits[1:]), splits[0])
else: mod = importlib.import_module(mod_name)
return mod
except:
... | def import_mod(mod_name:str, ignore_errors=False):
"Return module from `mod_name`."
splits = str.split(mod_name, '.')
try:
if len(splits) > 1 : mod = importlib.import_module('.' + '.'.join(splits[1:]), splits[0])
else: mod = importlib.import_module(mod_name)
return mod
except:
... | [
"Return",
"module",
"from",
"mod_name",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L183-L191 | [
"def",
"import_mod",
"(",
"mod_name",
":",
"str",
",",
"ignore_errors",
"=",
"False",
")",
":",
"splits",
"=",
"str",
".",
"split",
"(",
"mod_name",
",",
"'.'",
")",
"try",
":",
"if",
"len",
"(",
"splits",
")",
">",
"1",
":",
"mod",
"=",
"importlib... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | show_doc_from_name | Show documentation for `ft_name`, see `show_doc`. | fastai/gen_doc/nbdoc.py | def show_doc_from_name(mod_name, ft_name:str, doc_string:bool=True, arg_comments:dict={}, alt_doc_string:str=''):
"Show documentation for `ft_name`, see `show_doc`."
mod = import_mod(mod_name)
splits = str.split(ft_name, '.')
assert hasattr(mod, splits[0]), print(f"Module {mod_name} doesn't have a funct... | def show_doc_from_name(mod_name, ft_name:str, doc_string:bool=True, arg_comments:dict={}, alt_doc_string:str=''):
"Show documentation for `ft_name`, see `show_doc`."
mod = import_mod(mod_name)
splits = str.split(ft_name, '.')
assert hasattr(mod, splits[0]), print(f"Module {mod_name} doesn't have a funct... | [
"Show",
"documentation",
"for",
"ft_name",
"see",
"show_doc",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L193-L202 | [
"def",
"show_doc_from_name",
"(",
"mod_name",
",",
"ft_name",
":",
"str",
",",
"doc_string",
":",
"bool",
"=",
"True",
",",
"arg_comments",
":",
"dict",
"=",
"{",
"}",
",",
"alt_doc_string",
":",
"str",
"=",
"''",
")",
":",
"mod",
"=",
"import_mod",
"(... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | get_ft_names | Return all the functions of module `mod`. | fastai/gen_doc/nbdoc.py | def get_ft_names(mod, include_inner=False)->List[str]:
"Return all the functions of module `mod`."
# If the module has an attribute __all__, it picks those.
# Otherwise, it returns all the functions defined inside a module.
fn_names = []
for elt_name in get_exports(mod):
elt = getattr(mod,el... | def get_ft_names(mod, include_inner=False)->List[str]:
"Return all the functions of module `mod`."
# If the module has an attribute __all__, it picks those.
# Otherwise, it returns all the functions defined inside a module.
fn_names = []
for elt_name in get_exports(mod):
elt = getattr(mod,el... | [
"Return",
"all",
"the",
"functions",
"of",
"module",
"mod",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L209-L228 | [
"def",
"get_ft_names",
"(",
"mod",
",",
"include_inner",
"=",
"False",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# If the module has an attribute __all__, it picks those.",
"# Otherwise, it returns all the functions defined inside a module.",
"fn_names",
"=",
"[",
"]",
"for... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | get_inner_fts | List the inner functions of a class. | fastai/gen_doc/nbdoc.py | def get_inner_fts(elt)->List[str]:
"List the inner functions of a class."
fts = []
for ft_name in elt.__dict__.keys():
if ft_name.startswith('_'): continue
ft = getattr(elt, ft_name)
if inspect.isfunction(ft): fts.append(f'{elt.__name__}.{ft_name}')
if inspect.ismethod(ft): f... | def get_inner_fts(elt)->List[str]:
"List the inner functions of a class."
fts = []
for ft_name in elt.__dict__.keys():
if ft_name.startswith('_'): continue
ft = getattr(elt, ft_name)
if inspect.isfunction(ft): fts.append(f'{elt.__name__}.{ft_name}')
if inspect.ismethod(ft): f... | [
"List",
"the",
"inner",
"functions",
"of",
"a",
"class",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L230-L239 | [
"def",
"get_inner_fts",
"(",
"elt",
")",
"->",
"List",
"[",
"str",
"]",
":",
"fts",
"=",
"[",
"]",
"for",
"ft_name",
"in",
"elt",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"if",
"ft_name",
".",
"startswith",
"(",
"'_'",
")",
":",
"continue",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | get_module_toc | Display table of contents for given `mod_name`. | fastai/gen_doc/nbdoc.py | def get_module_toc(mod_name):
"Display table of contents for given `mod_name`."
mod = import_mod(mod_name)
ft_names = mod.__all__ if hasattr(mod,'__all__') else get_ft_names(mod)
ft_names.sort(key = str.lower)
tabmat = ''
for ft_name in ft_names:
tabmat += f'- [{ft_name}](#{ft_name})\n'
... | def get_module_toc(mod_name):
"Display table of contents for given `mod_name`."
mod = import_mod(mod_name)
ft_names = mod.__all__ if hasattr(mod,'__all__') else get_ft_names(mod)
ft_names.sort(key = str.lower)
tabmat = ''
for ft_name in ft_names:
tabmat += f'- [{ft_name}](#{ft_name})\n'
... | [
"Display",
"table",
"of",
"contents",
"for",
"given",
"mod_name",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L241-L254 | [
"def",
"get_module_toc",
"(",
"mod_name",
")",
":",
"mod",
"=",
"import_mod",
"(",
"mod_name",
")",
"ft_names",
"=",
"mod",
".",
"__all__",
"if",
"hasattr",
"(",
"mod",
",",
"'__all__'",
")",
"else",
"get_ft_names",
"(",
"mod",
")",
"ft_names",
".",
"sor... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | get_fn_link | Return function link to notebook documentation of `ft`. Private functions link to source code | fastai/gen_doc/nbdoc.py | def get_fn_link(ft)->str:
"Return function link to notebook documentation of `ft`. Private functions link to source code"
ft = getattr(ft, '__func__', ft)
anchor = strip_fastai(get_anchor(ft))
module_name = strip_fastai(get_module_name(ft))
base = '' if use_relative_links else FASTAI_DOCS
return... | def get_fn_link(ft)->str:
"Return function link to notebook documentation of `ft`. Private functions link to source code"
ft = getattr(ft, '__func__', ft)
anchor = strip_fastai(get_anchor(ft))
module_name = strip_fastai(get_module_name(ft))
base = '' if use_relative_links else FASTAI_DOCS
return... | [
"Return",
"function",
"link",
"to",
"notebook",
"documentation",
"of",
"ft",
".",
"Private",
"functions",
"link",
"to",
"source",
"code"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L278-L284 | [
"def",
"get_fn_link",
"(",
"ft",
")",
"->",
"str",
":",
"ft",
"=",
"getattr",
"(",
"ft",
",",
"'__func__'",
",",
"ft",
")",
"anchor",
"=",
"strip_fastai",
"(",
"get_anchor",
"(",
"ft",
")",
")",
"module_name",
"=",
"strip_fastai",
"(",
"get_module_name",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | get_pytorch_link | Returns link to pytorch docs of `ft`. | fastai/gen_doc/nbdoc.py | def get_pytorch_link(ft)->str:
"Returns link to pytorch docs of `ft`."
name = ft.__name__
ext = '.html'
if name == 'device': return f'{PYTORCH_DOCS}tensor_attributes{ext}#torch-device'
if name == 'Tensor': return f'{PYTORCH_DOCS}tensors{ext}#torch-tensor'
if name.startswith('torchvision'):
... | def get_pytorch_link(ft)->str:
"Returns link to pytorch docs of `ft`."
name = ft.__name__
ext = '.html'
if name == 'device': return f'{PYTORCH_DOCS}tensor_attributes{ext}#torch-device'
if name == 'Tensor': return f'{PYTORCH_DOCS}tensors{ext}#torch-tensor'
if name.startswith('torchvision'):
... | [
"Returns",
"link",
"to",
"pytorch",
"docs",
"of",
"ft",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L288-L308 | [
"def",
"get_pytorch_link",
"(",
"ft",
")",
"->",
"str",
":",
"name",
"=",
"ft",
".",
"__name__",
"ext",
"=",
"'.html'",
"if",
"name",
"==",
"'device'",
":",
"return",
"f'{PYTORCH_DOCS}tensor_attributes{ext}#torch-device'",
"if",
"name",
"==",
"'Tensor'",
":",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | get_source_link | Returns github link for given file | fastai/gen_doc/nbdoc.py | def get_source_link(file, line, display_text="[source]", **kwargs)->str:
"Returns github link for given file"
link = f"{SOURCE_URL}{file}#L{line}"
if display_text is None: return link
return f'<a href="{link}" class="source_link" style="float:right">{display_text}</a>' | def get_source_link(file, line, display_text="[source]", **kwargs)->str:
"Returns github link for given file"
link = f"{SOURCE_URL}{file}#L{line}"
if display_text is None: return link
return f'<a href="{link}" class="source_link" style="float:right">{display_text}</a>' | [
"Returns",
"github",
"link",
"for",
"given",
"file"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L310-L314 | [
"def",
"get_source_link",
"(",
"file",
",",
"line",
",",
"display_text",
"=",
"\"[source]\"",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"link",
"=",
"f\"{SOURCE_URL}{file}#L{line}\"",
"if",
"display_text",
"is",
"None",
":",
"return",
"link",
"return",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | get_function_source | Returns link to `ft` in source code. | fastai/gen_doc/nbdoc.py | def get_function_source(ft, **kwargs)->str:
"Returns link to `ft` in source code."
try: line = inspect.getsourcelines(ft)[1]
except Exception: return ''
mod_path = get_module_name(ft).replace('.', '/') + '.py'
return get_source_link(mod_path, line, **kwargs) | def get_function_source(ft, **kwargs)->str:
"Returns link to `ft` in source code."
try: line = inspect.getsourcelines(ft)[1]
except Exception: return ''
mod_path = get_module_name(ft).replace('.', '/') + '.py'
return get_source_link(mod_path, line, **kwargs) | [
"Returns",
"link",
"to",
"ft",
"in",
"source",
"code",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L316-L321 | [
"def",
"get_function_source",
"(",
"ft",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"try",
":",
"line",
"=",
"inspect",
".",
"getsourcelines",
"(",
"ft",
")",
"[",
"1",
"]",
"except",
"Exception",
":",
"return",
"''",
"mod_path",
"=",
"get_module_... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | find_comment_markers | Look through the cell source for comments which affect nbval's behaviour
Yield an iterable of ``(MARKER_TYPE, True)``. | docs_src/nbval/plugin.py | def find_comment_markers(cellsource):
"""Look through the cell source for comments which affect nbval's behaviour
Yield an iterable of ``(MARKER_TYPE, True)``.
"""
found = {}
for line in cellsource.splitlines():
line = line.strip()
if line.startswith('#'):
# print("Found... | def find_comment_markers(cellsource):
"""Look through the cell source for comments which affect nbval's behaviour
Yield an iterable of ``(MARKER_TYPE, True)``.
"""
found = {}
for line in cellsource.splitlines():
line = line.strip()
if line.startswith('#'):
# print("Found... | [
"Look",
"through",
"the",
"cell",
"source",
"for",
"comments",
"which",
"affect",
"nbval",
"s",
"behaviour"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L135-L160 | [
"def",
"find_comment_markers",
"(",
"cellsource",
")",
":",
"found",
"=",
"{",
"}",
"for",
"line",
"in",
"cellsource",
".",
"splitlines",
"(",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | coalesce_streams | Merge all stream outputs with shared names into single streams
to ensure deterministic outputs.
Parameters
----------
outputs : iterable of NotebookNodes
Outputs being processed | docs_src/nbval/plugin.py | def coalesce_streams(outputs):
"""
Merge all stream outputs with shared names into single streams
to ensure deterministic outputs.
Parameters
----------
outputs : iterable of NotebookNodes
Outputs being processed
"""
if not outputs:
return outputs
new_outputs = []
... | def coalesce_streams(outputs):
"""
Merge all stream outputs with shared names into single streams
to ensure deterministic outputs.
Parameters
----------
outputs : iterable of NotebookNodes
Outputs being processed
"""
if not outputs:
return outputs
new_outputs = []
... | [
"Merge",
"all",
"stream",
"outputs",
"with",
"shared",
"names",
"into",
"single",
"streams",
"to",
"ensure",
"deterministic",
"outputs",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L796-L831 | [
"def",
"coalesce_streams",
"(",
"outputs",
")",
":",
"if",
"not",
"outputs",
":",
"return",
"outputs",
"new_outputs",
"=",
"[",
"]",
"streams",
"=",
"{",
"}",
"for",
"output",
"in",
"outputs",
":",
"if",
"(",
"output",
".",
"output_type",
"==",
"'stream'... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | transform_streams_for_comparison | Makes failure output for streams better by having key be the stream name | docs_src/nbval/plugin.py | def transform_streams_for_comparison(outputs):
"""Makes failure output for streams better by having key be the stream name"""
new_outputs = []
for output in outputs:
if (output.output_type == 'stream'):
# Transform output
new_outputs.append({
'output_type': 's... | def transform_streams_for_comparison(outputs):
"""Makes failure output for streams better by having key be the stream name"""
new_outputs = []
for output in outputs:
if (output.output_type == 'stream'):
# Transform output
new_outputs.append({
'output_type': 's... | [
"Makes",
"failure",
"output",
"for",
"streams",
"better",
"by",
"having",
"key",
"be",
"the",
"stream",
"name"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L834-L846 | [
"def",
"transform_streams_for_comparison",
"(",
"outputs",
")",
":",
"new_outputs",
"=",
"[",
"]",
"for",
"output",
"in",
"outputs",
":",
"if",
"(",
"output",
".",
"output_type",
"==",
"'stream'",
")",
":",
"# Transform output",
"new_outputs",
".",
"append",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _trim_base64 | Trim and hash base64 strings | docs_src/nbval/plugin.py | def _trim_base64(s):
"""Trim and hash base64 strings"""
if len(s) > 64 and _base64.match(s.replace('\n', '')):
h = hash_string(s)
s = '%s...<snip base64, md5=%s...>' % (s[:8], h[:16])
return s | def _trim_base64(s):
"""Trim and hash base64 strings"""
if len(s) > 64 and _base64.match(s.replace('\n', '')):
h = hash_string(s)
s = '%s...<snip base64, md5=%s...>' % (s[:8], h[:16])
return s | [
"Trim",
"and",
"hash",
"base64",
"strings"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L873-L878 | [
"def",
"_trim_base64",
"(",
"s",
")",
":",
"if",
"len",
"(",
"s",
")",
">",
"64",
"and",
"_base64",
".",
"match",
"(",
"s",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
")",
":",
"h",
"=",
"hash_string",
"(",
"s",
")",
"s",
"=",
"'%s...<snip b... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _indent | Intent each line with indent | docs_src/nbval/plugin.py | def _indent(s, indent=' '):
"""Intent each line with indent"""
if isinstance(s, six.string_types):
return '\n'.join(('%s%s' % (indent, line) for line in s.splitlines()))
return s | def _indent(s, indent=' '):
"""Intent each line with indent"""
if isinstance(s, six.string_types):
return '\n'.join(('%s%s' % (indent, line) for line in s.splitlines()))
return s | [
"Intent",
"each",
"line",
"with",
"indent"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L881-L885 | [
"def",
"_indent",
"(",
"s",
",",
"indent",
"=",
"' '",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"string_types",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"(",
"'%s%s'",
"%",
"(",
"indent",
",",
"line",
")",
"for",
"line",
"i... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | IPyNbFile.setup | Called by pytest to setup the collector cells in .
Here we start a kernel and setup the sanitize patterns. | docs_src/nbval/plugin.py | def setup(self):
"""
Called by pytest to setup the collector cells in .
Here we start a kernel and setup the sanitize patterns.
"""
if self.parent.config.option.current_env:
kernel_name = CURRENT_ENV_KERNEL_NAME
else:
kernel_name = self.nb.metadat... | def setup(self):
"""
Called by pytest to setup the collector cells in .
Here we start a kernel and setup the sanitize patterns.
"""
if self.parent.config.option.current_env:
kernel_name = CURRENT_ENV_KERNEL_NAME
else:
kernel_name = self.nb.metadat... | [
"Called",
"by",
"pytest",
"to",
"setup",
"the",
"collector",
"cells",
"in",
".",
"Here",
"we",
"start",
"a",
"kernel",
"and",
"setup",
"the",
"sanitize",
"patterns",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L221-L235 | [
"def",
"setup",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
".",
"config",
".",
"option",
".",
"current_env",
":",
"kernel_name",
"=",
"CURRENT_ENV_KERNEL_NAME",
"else",
":",
"kernel_name",
"=",
"self",
".",
"nb",
".",
"metadata",
".",
"get",
"("... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | IPyNbFile.setup_sanitize_files | For each of the sanitize files that were specified as command line options
load the contents of the file into the sanitise patterns dictionary. | docs_src/nbval/plugin.py | def setup_sanitize_files(self):
"""
For each of the sanitize files that were specified as command line options
load the contents of the file into the sanitise patterns dictionary.
"""
for fname in self.get_sanitize_files():
with open(fname, 'r') as f:
... | def setup_sanitize_files(self):
"""
For each of the sanitize files that were specified as command line options
load the contents of the file into the sanitise patterns dictionary.
"""
for fname in self.get_sanitize_files():
with open(fname, 'r') as f:
... | [
"For",
"each",
"of",
"the",
"sanitize",
"files",
"that",
"were",
"specified",
"as",
"command",
"line",
"options",
"load",
"the",
"contents",
"of",
"the",
"file",
"into",
"the",
"sanitise",
"patterns",
"dictionary",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L238-L245 | [
"def",
"setup_sanitize_files",
"(",
"self",
")",
":",
"for",
"fname",
"in",
"self",
".",
"get_sanitize_files",
"(",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'r'",
")",
"as",
"f",
":",
"self",
".",
"sanitize_patterns",
".",
"update",
"(",
"get_saniti... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | IPyNbFile.get_sanitize_files | Return list of all sanitize files provided by the user on the command line.
N.B.: We only support one sanitize file at the moment, but
this is likely to change in the future | docs_src/nbval/plugin.py | def get_sanitize_files(self):
"""
Return list of all sanitize files provided by the user on the command line.
N.B.: We only support one sanitize file at the moment, but
this is likely to change in the future
"""
if self.parent.config.option.sanitize_with is not No... | def get_sanitize_files(self):
"""
Return list of all sanitize files provided by the user on the command line.
N.B.: We only support one sanitize file at the moment, but
this is likely to change in the future
"""
if self.parent.config.option.sanitize_with is not No... | [
"Return",
"list",
"of",
"all",
"sanitize",
"files",
"provided",
"by",
"the",
"user",
"on",
"the",
"command",
"line",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L248-L259 | [
"def",
"get_sanitize_files",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
".",
"config",
".",
"option",
".",
"sanitize_with",
"is",
"not",
"None",
":",
"return",
"[",
"self",
".",
"parent",
".",
"config",
".",
"option",
".",
"sanitize_with",
"]",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | IPyNbFile.get_kernel_message | Gets a message from the iopub channel of the notebook kernel. | docs_src/nbval/plugin.py | def get_kernel_message(self, timeout=None, stream='iopub'):
"""
Gets a message from the iopub channel of the notebook kernel.
"""
return self.kernel.get_message(stream, timeout=timeout) | def get_kernel_message(self, timeout=None, stream='iopub'):
"""
Gets a message from the iopub channel of the notebook kernel.
"""
return self.kernel.get_message(stream, timeout=timeout) | [
"Gets",
"a",
"message",
"from",
"the",
"iopub",
"channel",
"of",
"the",
"notebook",
"kernel",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L261-L265 | [
"def",
"get_kernel_message",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"stream",
"=",
"'iopub'",
")",
":",
"return",
"self",
".",
"kernel",
".",
"get_message",
"(",
"stream",
",",
"timeout",
"=",
"timeout",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | IPyNbFile.collect | The collect function is required by pytest and is used to yield pytest
Item objects. We specify an Item for each code cell in the notebook. | docs_src/nbval/plugin.py | def collect(self):
"""
The collect function is required by pytest and is used to yield pytest
Item objects. We specify an Item for each code cell in the notebook.
"""
self.nb = nbformat.read(str(self.fspath), as_version=4)
# Start the cell count
cell_num = 0
... | def collect(self):
"""
The collect function is required by pytest and is used to yield pytest
Item objects. We specify an Item for each code cell in the notebook.
"""
self.nb = nbformat.read(str(self.fspath), as_version=4)
# Start the cell count
cell_num = 0
... | [
"The",
"collect",
"function",
"is",
"required",
"by",
"pytest",
"and",
"is",
"used",
"to",
"yield",
"pytest",
"Item",
"objects",
".",
"We",
"specify",
"an",
"Item",
"for",
"each",
"code",
"cell",
"in",
"the",
"notebook",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L269-L309 | [
"def",
"collect",
"(",
"self",
")",
":",
"self",
".",
"nb",
"=",
"nbformat",
".",
"read",
"(",
"str",
"(",
"self",
".",
"fspath",
")",
",",
"as_version",
"=",
"4",
")",
"# Start the cell count",
"cell_num",
"=",
"0",
"# Iterate over the cells in the notebook... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | IPyNbCell.repr_failure | called when self.runtest() raises an exception. | docs_src/nbval/plugin.py | def repr_failure(self, excinfo):
""" called when self.runtest() raises an exception. """
exc = excinfo.value
cc = self.colors
if isinstance(exc, NbCellError):
msg_items = [
cc.FAIL + "Notebook cell execution failed" + cc.ENDC]
formatstring = (
... | def repr_failure(self, excinfo):
""" called when self.runtest() raises an exception. """
exc = excinfo.value
cc = self.colors
if isinstance(exc, NbCellError):
msg_items = [
cc.FAIL + "Notebook cell execution failed" + cc.ENDC]
formatstring = (
... | [
"called",
"when",
"self",
".",
"runtest",
"()",
"raises",
"an",
"exception",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L340-L361 | [
"def",
"repr_failure",
"(",
"self",
",",
"excinfo",
")",
":",
"exc",
"=",
"excinfo",
".",
"value",
"cc",
"=",
"self",
".",
"colors",
"if",
"isinstance",
"(",
"exc",
",",
"NbCellError",
")",
":",
"msg_items",
"=",
"[",
"cc",
".",
"FAIL",
"+",
"\"Noteb... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | IPyNbCell.format_output_compare | Format an output for printing | docs_src/nbval/plugin.py | def format_output_compare(self, key, left, right):
"""Format an output for printing"""
if isinstance(left, six.string_types):
left = _trim_base64(left)
if isinstance(right, six.string_types):
right = _trim_base64(right)
cc = self.colors
self.comparison_t... | def format_output_compare(self, key, left, right):
"""Format an output for printing"""
if isinstance(left, six.string_types):
left = _trim_base64(left)
if isinstance(right, six.string_types):
right = _trim_base64(right)
cc = self.colors
self.comparison_t... | [
"Format",
"an",
"output",
"for",
"printing"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L480-L517 | [
"def",
"format_output_compare",
"(",
"self",
",",
"key",
",",
"left",
",",
"right",
")",
":",
"if",
"isinstance",
"(",
"left",
",",
"six",
".",
"string_types",
")",
":",
"left",
"=",
"_trim_base64",
"(",
"left",
")",
"if",
"isinstance",
"(",
"right",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | IPyNbCell.sanitize | sanitize a string for comparison. | docs_src/nbval/plugin.py | def sanitize(self, s):
"""sanitize a string for comparison.
"""
if not isinstance(s, six.string_types):
return s
"""
re.sub matches a regex and replaces it with another.
The regex replacements are taken from a file if the option
is passed when py.test... | def sanitize(self, s):
"""sanitize a string for comparison.
"""
if not isinstance(s, six.string_types):
return s
"""
re.sub matches a regex and replaces it with another.
The regex replacements are taken from a file if the option
is passed when py.test... | [
"sanitize",
"a",
"string",
"for",
"comparison",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L775-L789 | [
"def",
"sanitize",
"(",
"self",
",",
"s",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"six",
".",
"string_types",
")",
":",
"return",
"s",
"\"\"\"\n re.sub matches a regex and replaces it with another.\n The regex replacements are taken from a file if ... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _tta_only | Computes the outputs for several augmented inputs for TTA | fastai/vision/tta.py | def _tta_only(learn:Learner, ds_type:DatasetType=DatasetType.Valid, scale:float=1.35) -> Iterator[List[Tensor]]:
"Computes the outputs for several augmented inputs for TTA"
dl = learn.dl(ds_type)
ds = dl.dataset
old = ds.tfms
augm_tfm = [o for o in learn.data.train_ds.tfms if o.tfm not in
... | def _tta_only(learn:Learner, ds_type:DatasetType=DatasetType.Valid, scale:float=1.35) -> Iterator[List[Tensor]]:
"Computes the outputs for several augmented inputs for TTA"
dl = learn.dl(ds_type)
ds = dl.dataset
old = ds.tfms
augm_tfm = [o for o in learn.data.train_ds.tfms if o.tfm not in
... | [
"Computes",
"the",
"outputs",
"for",
"several",
"augmented",
"inputs",
"for",
"TTA"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/tta.py#L10-L28 | [
"def",
"_tta_only",
"(",
"learn",
":",
"Learner",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Valid",
",",
"scale",
":",
"float",
"=",
"1.35",
")",
"->",
"Iterator",
"[",
"List",
"[",
"Tensor",
"]",
"]",
":",
"dl",
"=",
"learn",
"."... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _TTA | Applies TTA to predict on `ds_type` dataset. | fastai/vision/tta.py | def _TTA(learn:Learner, beta:float=0.4, scale:float=1.35, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False) -> Tensors:
"Applies TTA to predict on `ds_type` dataset."
preds,y = learn.get_preds(ds_type)
all_preds = list(learn.tta_only(scale=scale, ds_type=ds_type))
avg_preds = torch.stack(all_... | def _TTA(learn:Learner, beta:float=0.4, scale:float=1.35, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False) -> Tensors:
"Applies TTA to predict on `ds_type` dataset."
preds,y = learn.get_preds(ds_type)
all_preds = list(learn.tta_only(scale=scale, ds_type=ds_type))
avg_preds = torch.stack(all_... | [
"Applies",
"TTA",
"to",
"predict",
"on",
"ds_type",
"dataset",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/tta.py#L32-L43 | [
"def",
"_TTA",
"(",
"learn",
":",
"Learner",
",",
"beta",
":",
"float",
"=",
"0.4",
",",
"scale",
":",
"float",
"=",
"1.35",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Valid",
",",
"with_loss",
":",
"bool",
"=",
"False",
")",
"->",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | fbeta | Computes the f_beta between `preds` and `targets` | fastai/metrics.py | def fbeta(y_pred:Tensor, y_true:Tensor, thresh:float=0.2, beta:float=2, eps:float=1e-9, sigmoid:bool=True)->Rank0Tensor:
"Computes the f_beta between `preds` and `targets`"
beta2 = beta ** 2
if sigmoid: y_pred = y_pred.sigmoid()
y_pred = (y_pred>thresh).float()
y_true = y_true.float()
TP = (y_pr... | def fbeta(y_pred:Tensor, y_true:Tensor, thresh:float=0.2, beta:float=2, eps:float=1e-9, sigmoid:bool=True)->Rank0Tensor:
"Computes the f_beta between `preds` and `targets`"
beta2 = beta ** 2
if sigmoid: y_pred = y_pred.sigmoid()
y_pred = (y_pred>thresh).float()
y_true = y_true.float()
TP = (y_pr... | [
"Computes",
"the",
"f_beta",
"between",
"preds",
"and",
"targets"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L12-L22 | [
"def",
"fbeta",
"(",
"y_pred",
":",
"Tensor",
",",
"y_true",
":",
"Tensor",
",",
"thresh",
":",
"float",
"=",
"0.2",
",",
"beta",
":",
"float",
"=",
"2",
",",
"eps",
":",
"float",
"=",
"1e-9",
",",
"sigmoid",
":",
"bool",
"=",
"True",
")",
"->",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | accuracy | Compute accuracy with `targs` when `input` is bs * n_classes. | fastai/metrics.py | def accuracy(input:Tensor, targs:Tensor)->Rank0Tensor:
"Compute accuracy with `targs` when `input` is bs * n_classes."
n = targs.shape[0]
input = input.argmax(dim=-1).view(n,-1)
targs = targs.view(n,-1)
return (input==targs).float().mean() | def accuracy(input:Tensor, targs:Tensor)->Rank0Tensor:
"Compute accuracy with `targs` when `input` is bs * n_classes."
n = targs.shape[0]
input = input.argmax(dim=-1).view(n,-1)
targs = targs.view(n,-1)
return (input==targs).float().mean() | [
"Compute",
"accuracy",
"with",
"targs",
"when",
"input",
"is",
"bs",
"*",
"n_classes",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L24-L29 | [
"def",
"accuracy",
"(",
"input",
":",
"Tensor",
",",
"targs",
":",
"Tensor",
")",
"->",
"Rank0Tensor",
":",
"n",
"=",
"targs",
".",
"shape",
"[",
"0",
"]",
"input",
"=",
"input",
".",
"argmax",
"(",
"dim",
"=",
"-",
"1",
")",
".",
"view",
"(",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | accuracy_thresh | Compute accuracy when `y_pred` and `y_true` are the same size. | fastai/metrics.py | def accuracy_thresh(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor:
"Compute accuracy when `y_pred` and `y_true` are the same size."
if sigmoid: y_pred = y_pred.sigmoid()
return ((y_pred>thresh)==y_true.byte()).float().mean() | def accuracy_thresh(y_pred:Tensor, y_true:Tensor, thresh:float=0.5, sigmoid:bool=True)->Rank0Tensor:
"Compute accuracy when `y_pred` and `y_true` are the same size."
if sigmoid: y_pred = y_pred.sigmoid()
return ((y_pred>thresh)==y_true.byte()).float().mean() | [
"Compute",
"accuracy",
"when",
"y_pred",
"and",
"y_true",
"are",
"the",
"same",
"size",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L31-L34 | [
"def",
"accuracy_thresh",
"(",
"y_pred",
":",
"Tensor",
",",
"y_true",
":",
"Tensor",
",",
"thresh",
":",
"float",
"=",
"0.5",
",",
"sigmoid",
":",
"bool",
"=",
"True",
")",
"->",
"Rank0Tensor",
":",
"if",
"sigmoid",
":",
"y_pred",
"=",
"y_pred",
".",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | top_k_accuracy | Computes the Top-k accuracy (target is in the top k predictions). | fastai/metrics.py | def top_k_accuracy(input:Tensor, targs:Tensor, k:int=5)->Rank0Tensor:
"Computes the Top-k accuracy (target is in the top k predictions)."
input = input.topk(k=k, dim=-1)[1]
targs = targs.unsqueeze(dim=-1).expand_as(input)
return (input == targs).max(dim=-1)[0].float().mean() | def top_k_accuracy(input:Tensor, targs:Tensor, k:int=5)->Rank0Tensor:
"Computes the Top-k accuracy (target is in the top k predictions)."
input = input.topk(k=k, dim=-1)[1]
targs = targs.unsqueeze(dim=-1).expand_as(input)
return (input == targs).max(dim=-1)[0].float().mean() | [
"Computes",
"the",
"Top",
"-",
"k",
"accuracy",
"(",
"target",
"is",
"in",
"the",
"top",
"k",
"predictions",
")",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L36-L40 | [
"def",
"top_k_accuracy",
"(",
"input",
":",
"Tensor",
",",
"targs",
":",
"Tensor",
",",
"k",
":",
"int",
"=",
"5",
")",
"->",
"Rank0Tensor",
":",
"input",
"=",
"input",
".",
"topk",
"(",
"k",
"=",
"k",
",",
"dim",
"=",
"-",
"1",
")",
"[",
"1",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | dice | Dice coefficient metric for binary target. If iou=True, returns iou metric, classic for segmentation problems. | fastai/metrics.py | def dice(input:Tensor, targs:Tensor, iou:bool=False)->Rank0Tensor:
"Dice coefficient metric for binary target. If iou=True, returns iou metric, classic for segmentation problems."
n = targs.shape[0]
input = input.argmax(dim=1).view(n,-1)
targs = targs.view(n,-1)
intersect = (input * targs).sum().flo... | def dice(input:Tensor, targs:Tensor, iou:bool=False)->Rank0Tensor:
"Dice coefficient metric for binary target. If iou=True, returns iou metric, classic for segmentation problems."
n = targs.shape[0]
input = input.argmax(dim=1).view(n,-1)
targs = targs.view(n,-1)
intersect = (input * targs).sum().flo... | [
"Dice",
"coefficient",
"metric",
"for",
"binary",
"target",
".",
"If",
"iou",
"=",
"True",
"returns",
"iou",
"metric",
"classic",
"for",
"segmentation",
"problems",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L46-L54 | [
"def",
"dice",
"(",
"input",
":",
"Tensor",
",",
"targs",
":",
"Tensor",
",",
"iou",
":",
"bool",
"=",
"False",
")",
"->",
"Rank0Tensor",
":",
"n",
"=",
"targs",
".",
"shape",
"[",
"0",
"]",
"input",
"=",
"input",
".",
"argmax",
"(",
"dim",
"=",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | exp_rmspe | Exp RMSE between `pred` and `targ`. | fastai/metrics.py | def exp_rmspe(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Exp RMSE between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
pred, targ = torch.exp(pred), torch.exp(targ)
pct_var = (targ - pred)/targ
return torch.sqrt((pct_var**2).mean()) | def exp_rmspe(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Exp RMSE between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
pred, targ = torch.exp(pred), torch.exp(targ)
pct_var = (targ - pred)/targ
return torch.sqrt((pct_var**2).mean()) | [
"Exp",
"RMSE",
"between",
"pred",
"and",
"targ",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L56-L61 | [
"def",
"exp_rmspe",
"(",
"pred",
":",
"Tensor",
",",
"targ",
":",
"Tensor",
")",
"->",
"Rank0Tensor",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"pred",
",",
"targ",
"=",
"torch",
".",
"exp",
"(",
"pred",
")",
",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | mean_absolute_error | Mean absolute error between `pred` and `targ`. | fastai/metrics.py | def mean_absolute_error(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Mean absolute error between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
return torch.abs(targ - pred).mean() | def mean_absolute_error(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Mean absolute error between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
return torch.abs(targ - pred).mean() | [
"Mean",
"absolute",
"error",
"between",
"pred",
"and",
"targ",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L63-L66 | [
"def",
"mean_absolute_error",
"(",
"pred",
":",
"Tensor",
",",
"targ",
":",
"Tensor",
")",
"->",
"Rank0Tensor",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"return",
"torch",
".",
"abs",
"(",
"targ",
"-",
"pred",
")",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | mean_squared_error | Mean squared error between `pred` and `targ`. | fastai/metrics.py | def mean_squared_error(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Mean squared error between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
return F.mse_loss(pred, targ) | def mean_squared_error(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Mean squared error between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
return F.mse_loss(pred, targ) | [
"Mean",
"squared",
"error",
"between",
"pred",
"and",
"targ",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L68-L71 | [
"def",
"mean_squared_error",
"(",
"pred",
":",
"Tensor",
",",
"targ",
":",
"Tensor",
")",
"->",
"Rank0Tensor",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"return",
"F",
".",
"mse_loss",
"(",
"pred",
",",
"targ",
")"
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | root_mean_squared_error | Root mean squared error between `pred` and `targ`. | fastai/metrics.py | def root_mean_squared_error(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Root mean squared error between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
return torch.sqrt(F.mse_loss(pred, targ)) | def root_mean_squared_error(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Root mean squared error between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
return torch.sqrt(F.mse_loss(pred, targ)) | [
"Root",
"mean",
"squared",
"error",
"between",
"pred",
"and",
"targ",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L73-L76 | [
"def",
"root_mean_squared_error",
"(",
"pred",
":",
"Tensor",
",",
"targ",
":",
"Tensor",
")",
"->",
"Rank0Tensor",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"return",
"torch",
".",
"sqrt",
"(",
"F",
".",
"mse_loss",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | mean_squared_logarithmic_error | Mean squared logarithmic error between `pred` and `targ`. | fastai/metrics.py | def mean_squared_logarithmic_error(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Mean squared logarithmic error between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
return F.mse_loss(torch.log(1 + pred), torch.log(1 + targ)) | def mean_squared_logarithmic_error(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Mean squared logarithmic error between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
return F.mse_loss(torch.log(1 + pred), torch.log(1 + targ)) | [
"Mean",
"squared",
"logarithmic",
"error",
"between",
"pred",
"and",
"targ",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L78-L81 | [
"def",
"mean_squared_logarithmic_error",
"(",
"pred",
":",
"Tensor",
",",
"targ",
":",
"Tensor",
")",
"->",
"Rank0Tensor",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"return",
"F",
".",
"mse_loss",
"(",
"torch",
".",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | explained_variance | Explained variance between `pred` and `targ`. | fastai/metrics.py | def explained_variance(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Explained variance between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
var_pct = torch.var(targ - pred) / torch.var(targ)
return 1 - var_pct | def explained_variance(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Explained variance between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
var_pct = torch.var(targ - pred) / torch.var(targ)
return 1 - var_pct | [
"Explained",
"variance",
"between",
"pred",
"and",
"targ",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L83-L87 | [
"def",
"explained_variance",
"(",
"pred",
":",
"Tensor",
",",
"targ",
":",
"Tensor",
")",
"->",
"Rank0Tensor",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"var_pct",
"=",
"torch",
".",
"var",
"(",
"targ",
"-",
"pred",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | r2_score | R2 score (coefficient of determination) between `pred` and `targ`. | fastai/metrics.py | def r2_score(pred:Tensor, targ:Tensor)->Rank0Tensor:
"R2 score (coefficient of determination) between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
u = torch.sum((targ - pred) ** 2)
d = torch.sum((targ - targ.mean()) ** 2)
return 1 - u / d | def r2_score(pred:Tensor, targ:Tensor)->Rank0Tensor:
"R2 score (coefficient of determination) between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
u = torch.sum((targ - pred) ** 2)
d = torch.sum((targ - targ.mean()) ** 2)
return 1 - u / d | [
"R2",
"score",
"(",
"coefficient",
"of",
"determination",
")",
"between",
"pred",
"and",
"targ",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L89-L94 | [
"def",
"r2_score",
"(",
"pred",
":",
"Tensor",
",",
"targ",
":",
"Tensor",
")",
"->",
"Rank0Tensor",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"u",
"=",
"torch",
".",
"sum",
"(",
"(",
"targ",
"-",
"pred",
")",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | auc_roc_score | Using trapezoid method to calculate the area under roc curve | fastai/metrics.py | def auc_roc_score(input:Tensor, targ:Tensor):
"Using trapezoid method to calculate the area under roc curve"
fpr, tpr = roc_curve(input, targ)
d = fpr[1:] - fpr[:-1]
sl1, sl2 = [slice(None)], [slice(None)]
sl1[-1], sl2[-1] = slice(1, None), slice(None, -1)
return (d * (tpr[tuple(sl1)] + tpr[tupl... | def auc_roc_score(input:Tensor, targ:Tensor):
"Using trapezoid method to calculate the area under roc curve"
fpr, tpr = roc_curve(input, targ)
d = fpr[1:] - fpr[:-1]
sl1, sl2 = [slice(None)], [slice(None)]
sl1[-1], sl2[-1] = slice(1, None), slice(None, -1)
return (d * (tpr[tuple(sl1)] + tpr[tupl... | [
"Using",
"trapezoid",
"method",
"to",
"calculate",
"the",
"area",
"under",
"roc",
"curve"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L266-L272 | [
"def",
"auc_roc_score",
"(",
"input",
":",
"Tensor",
",",
"targ",
":",
"Tensor",
")",
":",
"fpr",
",",
"tpr",
"=",
"roc_curve",
"(",
"input",
",",
"targ",
")",
"d",
"=",
"fpr",
"[",
"1",
":",
"]",
"-",
"fpr",
"[",
":",
"-",
"1",
"]",
"sl1",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | roc_curve | Returns the false positive and true positive rates | fastai/metrics.py | def roc_curve(input:Tensor, targ:Tensor):
"Returns the false positive and true positive rates"
targ = (targ == 1)
desc_score_indices = torch.flip(input.argsort(-1), [-1])
input = input[desc_score_indices]
targ = targ[desc_score_indices]
d = input[1:] - input[:-1]
distinct_value_indices = tor... | def roc_curve(input:Tensor, targ:Tensor):
"Returns the false positive and true positive rates"
targ = (targ == 1)
desc_score_indices = torch.flip(input.argsort(-1), [-1])
input = input[desc_score_indices]
targ = targ[desc_score_indices]
d = input[1:] - input[:-1]
distinct_value_indices = tor... | [
"Returns",
"the",
"false",
"positive",
"and",
"true",
"positive",
"rates"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L274-L289 | [
"def",
"roc_curve",
"(",
"input",
":",
"Tensor",
",",
"targ",
":",
"Tensor",
")",
":",
"targ",
"=",
"(",
"targ",
"==",
"1",
")",
"desc_score_indices",
"=",
"torch",
".",
"flip",
"(",
"input",
".",
"argsort",
"(",
"-",
"1",
")",
",",
"[",
"-",
"1"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | A | convert iterable object into numpy array | old/fastai/core.py | def A(*a):
"""convert iterable object into numpy array"""
return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a] | def A(*a):
"""convert iterable object into numpy array"""
return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a] | [
"convert",
"iterable",
"object",
"into",
"numpy",
"array"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L25-L27 | [
"def",
"A",
"(",
"*",
"a",
")",
":",
"return",
"np",
".",
"array",
"(",
"a",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"a",
")",
"==",
"1",
"else",
"[",
"np",
".",
"array",
"(",
"o",
")",
"for",
"o",
"in",
"a",
"]"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | T | Convert numpy array into a pytorch tensor.
if Cuda is available and USE_GPU=True, store resulting tensor in GPU. | old/fastai/core.py | def T(a, half=False, cuda=True):
"""
Convert numpy array into a pytorch tensor.
if Cuda is available and USE_GPU=True, store resulting tensor in GPU.
"""
if not torch.is_tensor(a):
a = np.array(np.ascontiguousarray(a))
if a.dtype in (np.int8, np.int16, np.int32, np.int64):
... | def T(a, half=False, cuda=True):
"""
Convert numpy array into a pytorch tensor.
if Cuda is available and USE_GPU=True, store resulting tensor in GPU.
"""
if not torch.is_tensor(a):
a = np.array(np.ascontiguousarray(a))
if a.dtype in (np.int8, np.int16, np.int32, np.int64):
... | [
"Convert",
"numpy",
"array",
"into",
"a",
"pytorch",
"tensor",
".",
"if",
"Cuda",
"is",
"available",
"and",
"USE_GPU",
"=",
"True",
"store",
"resulting",
"tensor",
"in",
"GPU",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L29-L42 | [
"def",
"T",
"(",
"a",
",",
"half",
"=",
"False",
",",
"cuda",
"=",
"True",
")",
":",
"if",
"not",
"torch",
".",
"is_tensor",
"(",
"a",
")",
":",
"a",
"=",
"np",
".",
"array",
"(",
"np",
".",
"ascontiguousarray",
"(",
"a",
")",
")",
"if",
"a",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | V_ | equivalent to create_variable, which creates a pytorch tensor | old/fastai/core.py | def V_(x, requires_grad=False, volatile=False):
'''equivalent to create_variable, which creates a pytorch tensor'''
return create_variable(x, volatile=volatile, requires_grad=requires_grad) | def V_(x, requires_grad=False, volatile=False):
'''equivalent to create_variable, which creates a pytorch tensor'''
return create_variable(x, volatile=volatile, requires_grad=requires_grad) | [
"equivalent",
"to",
"create_variable",
"which",
"creates",
"a",
"pytorch",
"tensor"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L56-L58 | [
"def",
"V_",
"(",
"x",
",",
"requires_grad",
"=",
"False",
",",
"volatile",
"=",
"False",
")",
":",
"return",
"create_variable",
"(",
"x",
",",
"volatile",
"=",
"volatile",
",",
"requires_grad",
"=",
"requires_grad",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | V | creates a single or a list of pytorch tensors, depending on input x. | old/fastai/core.py | def V(x, requires_grad=False, volatile=False):
'''creates a single or a list of pytorch tensors, depending on input x. '''
return map_over(x, lambda o: V_(o, requires_grad, volatile)) | def V(x, requires_grad=False, volatile=False):
'''creates a single or a list of pytorch tensors, depending on input x. '''
return map_over(x, lambda o: V_(o, requires_grad, volatile)) | [
"creates",
"a",
"single",
"or",
"a",
"list",
"of",
"pytorch",
"tensors",
"depending",
"on",
"input",
"x",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L59-L61 | [
"def",
"V",
"(",
"x",
",",
"requires_grad",
"=",
"False",
",",
"volatile",
"=",
"False",
")",
":",
"return",
"map_over",
"(",
"x",
",",
"lambda",
"o",
":",
"V_",
"(",
"o",
",",
"requires_grad",
",",
"volatile",
")",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | to_np | returns an np.array object given an input of np.array, list, tuple, torch variable or tensor. | old/fastai/core.py | def to_np(v):
'''returns an np.array object given an input of np.array, list, tuple, torch variable or tensor.'''
if isinstance(v, float): return np.array(v)
if isinstance(v, (np.ndarray, np.generic)): return v
if isinstance(v, (list,tuple)): return [to_np(o) for o in v]
if isinstance(v, Variable): ... | def to_np(v):
'''returns an np.array object given an input of np.array, list, tuple, torch variable or tensor.'''
if isinstance(v, float): return np.array(v)
if isinstance(v, (np.ndarray, np.generic)): return v
if isinstance(v, (list,tuple)): return [to_np(o) for o in v]
if isinstance(v, Variable): ... | [
"returns",
"an",
"np",
".",
"array",
"object",
"given",
"an",
"input",
"of",
"np",
".",
"array",
"list",
"tuple",
"torch",
"variable",
"or",
"tensor",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L71-L80 | [
"def",
"to_np",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"float",
")",
":",
"return",
"np",
".",
"array",
"(",
"v",
")",
"if",
"isinstance",
"(",
"v",
",",
"(",
"np",
".",
"ndarray",
",",
"np",
".",
"generic",
")",
")",
":",
"re... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | to_gpu | puts pytorch variable to gpu, if cuda is available and USE_GPU is set to true. | old/fastai/core.py | def to_gpu(x, *args, **kwargs):
'''puts pytorch variable to gpu, if cuda is available and USE_GPU is set to true. '''
return x.cuda(*args, **kwargs) if USE_GPU else x | def to_gpu(x, *args, **kwargs):
'''puts pytorch variable to gpu, if cuda is available and USE_GPU is set to true. '''
return x.cuda(*args, **kwargs) if USE_GPU else x | [
"puts",
"pytorch",
"variable",
"to",
"gpu",
"if",
"cuda",
"is",
"available",
"and",
"USE_GPU",
"is",
"set",
"to",
"true",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L88-L90 | [
"def",
"to_gpu",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"x",
".",
"cuda",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"USE_GPU",
"else",
"x"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | split_by_idxs | A generator that returns sequence pieces, seperated by indexes specified in idxs. | old/fastai/core.py | 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[... | 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[... | [
"A",
"generator",
"that",
"returns",
"sequence",
"pieces",
"seperated",
"by",
"indexes",
"specified",
"in",
"idxs",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L94-L102 | [
"def",
"split_by_idxs",
"(",
"seq",
",",
"idxs",
")",
":",
"last",
"=",
"0",
"for",
"idx",
"in",
"idxs",
":",
"if",
"not",
"(",
"-",
"len",
"(",
"seq",
")",
"<=",
"idx",
"<",
"len",
"(",
"seq",
")",
")",
":",
"raise",
"KeyError",
"(",
"f'Idx {i... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | partition | splits iterables a in equal parts of size sz | old/fastai/core.py | 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):
"""splits iterables a in equal parts of size sz"""
return [a[i:i+sz] for i in range(0, len(a), sz)] | [
"splits",
"iterables",
"a",
"in",
"equal",
"parts",
"of",
"size",
"sz"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L131-L133 | [
"def",
"partition",
"(",
"a",
",",
"sz",
")",
":",
"return",
"[",
"a",
"[",
"i",
":",
"i",
"+",
"sz",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"a",
")",
",",
"sz",
")",
"]"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | chunk_iter | A generator that yields chunks of iterable, chunk_size at a time. | old/fastai/core.py | 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
... | 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
... | [
"A",
"generator",
"that",
"yields",
"chunks",
"of",
"iterable",
"chunk_size",
"at",
"a",
"time",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L184-L193 | [
"def",
"chunk_iter",
"(",
"iterable",
",",
"chunk_size",
")",
":",
"while",
"True",
":",
"chunk",
"=",
"[",
"]",
"try",
":",
"for",
"_",
"in",
"range",
"(",
"chunk_size",
")",
":",
"chunk",
".",
"append",
"(",
"next",
"(",
"iterable",
")",
")",
"yi... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _brightness | Apply `change` in brightness of image `x`. | fastai/vision/transform.py | def _brightness(x, change:uniform):
"Apply `change` in brightness of image `x`."
return x.add_(scipy.special.logit(change)) | def _brightness(x, change:uniform):
"Apply `change` in brightness of image `x`."
return x.add_(scipy.special.logit(change)) | [
"Apply",
"change",
"in",
"brightness",
"of",
"image",
"x",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L15-L17 | [
"def",
"_brightness",
"(",
"x",
",",
"change",
":",
"uniform",
")",
":",
"return",
"x",
".",
"add_",
"(",
"scipy",
".",
"special",
".",
"logit",
"(",
"change",
")",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _rotate | Rotate image by `degrees`. | fastai/vision/transform.py | 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):
"Rotate image by `degrees`."
angle = degrees * math.pi / 180
return [[cos(angle), -sin(angle), 0.],
[sin(angle), cos(angle), 0.],
[0. , 0. , 1.]] | [
"Rotate",
"image",
"by",
"degrees",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L25-L30 | [
"def",
"_rotate",
"(",
"degrees",
":",
"uniform",
")",
":",
"angle",
"=",
"degrees",
"*",
"math",
".",
"pi",
"/",
"180",
"return",
"[",
"[",
"cos",
"(",
"angle",
")",
",",
"-",
"sin",
"(",
"angle",
")",
",",
"0.",
"]",
",",
"[",
"sin",
"(",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _get_zoom_mat | `sw`,`sh` scale width,height - `c`,`r` focus col,row. | fastai/vision/transform.py | 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:
"`sw`,`sh` scale width,height - `c`,`r` focus col,row."
return [[sw, 0, c],
[0, sh, r],
[0, 0, 1.]] | [
"sw",
"sh",
"scale",
"width",
"height",
"-",
"c",
"r",
"focus",
"col",
"row",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L33-L37 | [
"def",
"_get_zoom_mat",
"(",
"sw",
":",
"float",
",",
"sh",
":",
"float",
",",
"c",
":",
"float",
",",
"r",
":",
"float",
")",
"->",
"AffineMatrix",
":",
"return",
"[",
"[",
"sw",
",",
"0",
",",
"c",
"]",
",",
"[",
"0",
",",
"sh",
",",
"r",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _zoom | Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom. | fastai/vision/transform.py | 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):
"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) | [
"Zoom",
"image",
"by",
"scale",
".",
"row_pct",
"col_pct",
"select",
"focal",
"point",
"of",
"zoom",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L39-L44 | [
"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",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _squish | Squish image by `scale`. `row_pct`,`col_pct` select focal point of zoom. | fastai/vision/transform.py | 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... | 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... | [
"Squish",
"image",
"by",
"scale",
".",
"row_pct",
"col_pct",
"select",
"focal",
"point",
"of",
"zoom",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L47-L54 | [
"def",
"_squish",
"(",
"scale",
":",
"uniform",
"=",
"1.0",
",",
"row_pct",
":",
"uniform",
"=",
"0.5",
",",
"col_pct",
":",
"uniform",
"=",
"0.5",
")",
":",
"if",
"scale",
"<=",
"1",
":",
"col_c",
"=",
"(",
"1",
"-",
"scale",
")",
"*",
"(",
"2... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _jitter | Replace pixels by random neighbors at `magnitude`. | fastai/vision/transform.py | 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):
"Replace pixels by random neighbors at `magnitude`."
c.flow.add_((torch.rand_like(c.flow)-0.5)*magnitude*2)
return c | [
"Replace",
"pixels",
"by",
"random",
"neighbors",
"at",
"magnitude",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L57-L60 | [
"def",
"_jitter",
"(",
"c",
",",
"magnitude",
":",
"uniform",
")",
":",
"c",
".",
"flow",
".",
"add_",
"(",
"(",
"torch",
".",
"rand_like",
"(",
"c",
".",
"flow",
")",
"-",
"0.5",
")",
"*",
"magnitude",
"*",
"2",
")",
"return",
"c"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _flip_lr | Flip `x` horizontally. | fastai/vision/transform.py | 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):
"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])) | [
"Flip",
"x",
"horizontally",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L63-L69 | [
"def",
"_flip_lr",
"(",
"x",
")",
":",
"#return x.flip(2)",
"if",
"isinstance",
"(",
"x",
",",
"ImagePoints",
")",
":",
"x",
".",
"flow",
".",
"flow",
"[",
"...",
",",
"0",
"]",
"*=",
"-",
"1",
"return",
"x",
"return",
"tensor",
"(",
"np",
".",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _dihedral | Randomly flip `x` image based on `k`. | fastai/vision/transform.py | 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)):
"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() | [
"Randomly",
"flip",
"x",
"image",
"based",
"on",
"k",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L79-L86 | [
"def",
"_dihedral",
"(",
"x",
",",
"k",
":",
"partial",
"(",
"uniform_int",
",",
"0",
",",
"7",
")",
")",
":",
"flips",
"=",
"[",
"]",
"if",
"k",
"&",
"1",
":",
"flips",
".",
"append",
"(",
"1",
")",
"if",
"k",
"&",
"2",
":",
"flips",
".",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _dihedral_affine | Randomly flip `x` image based on `k`. | fastai/vision/transform.py | 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)):
"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.]] | [
"Randomly",
"flip",
"x",
"image",
"based",
"on",
"k",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L89-L98 | [
"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",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _pad_default | Pad `x` with `padding` pixels. `mode` fills in space ('zeros','reflection','border'). | fastai/vision/transform.py | 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'):
"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] | [
"Pad",
"x",
"with",
"padding",
"pixels",
".",
"mode",
"fills",
"in",
"space",
"(",
"zeros",
"reflection",
"border",
")",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L108-L111 | [
"def",
"_pad_default",
"(",
"x",
",",
"padding",
":",
"int",
",",
"mode",
"=",
"'reflection'",
")",
":",
"mode",
"=",
"_pad_mode_convert",
"[",
"mode",
"]",
"return",
"F",
".",
"pad",
"(",
"x",
"[",
"None",
"]",
",",
"(",
"padding",
",",
")",
"*",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _cutout | Cut out `n_holes` number of square holes of size `length` in image at random locations. | fastai/vision/transform.py | 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... | 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... | [
"Cut",
"out",
"n_holes",
"number",
"of",
"square",
"holes",
"of",
"size",
"length",
"in",
"image",
"at",
"random",
"locations",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L122-L133 | [
"def",
"_cutout",
"(",
"x",
",",
"n_holes",
":",
"uniform_int",
"=",
"1",
",",
"length",
":",
"uniform_int",
"=",
"40",
")",
":",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"1",
":",
"]",
"for",
"n",
"in",
"range",
"(",
"n_holes",
")",
":",
... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _rgb_randomize | Randomize one of the channels of the input image | fastai/vision/transform.py | 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):
"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 | [
"Randomize",
"one",
"of",
"the",
"channels",
"of",
"the",
"input",
"image"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L137-L141 | [
"def",
"_rgb_randomize",
"(",
"x",
",",
"channel",
":",
"int",
"=",
"None",
",",
"thresh",
":",
"float",
"=",
"0.3",
")",
":",
"if",
"channel",
"is",
"None",
":",
"channel",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"x",
".",
"shap... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _crop_default | Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop. | fastai/vision/transform.py | 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... | 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... | [
"Crop",
"x",
"to",
"size",
"pixels",
".",
"row_pct",
"col_pct",
"select",
"focal",
"point",
"of",
"crop",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L150-L156 | [
"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",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _crop_pad_default | Crop and pad tfm - `row_pct`,`col_pct` sets focal point. | fastai/vision/transform.py | 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... | 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... | [
"Crop",
"and",
"pad",
"tfm",
"-",
"row_pct",
"col_pct",
"sets",
"focal",
"point",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L175-L189 | [
"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",
"]",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | rand_pad | Fixed `mode` `padding` and random crop of `size` | fastai/vision/transform.py | 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'):
"Fixed `mode` `padding` and random crop of `size`"
return [pad(padding=padding,mode=mode),
crop(size=size, **rand_pos)] | [
"Fixed",
"mode",
"padding",
"and",
"random",
"crop",
"of",
"size"
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L213-L216 | [
"def",
"rand_pad",
"(",
"padding",
":",
"int",
",",
"size",
":",
"int",
",",
"mode",
":",
"str",
"=",
"'reflection'",
")",
":",
"return",
"[",
"pad",
"(",
"padding",
"=",
"padding",
",",
"mode",
"=",
"mode",
")",
",",
"crop",
"(",
"size",
"=",
"s... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | rand_zoom | Randomized version of `zoom`. | fastai/vision/transform.py | 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.):
"Randomized version of `zoom`."
return zoom(scale=scale, **rand_pos, p=p) | [
"Randomized",
"version",
"of",
"zoom",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L218-L220 | [
"def",
"rand_zoom",
"(",
"scale",
":",
"uniform",
"=",
"1.0",
",",
"p",
":",
"float",
"=",
"1.",
")",
":",
"return",
"zoom",
"(",
"scale",
"=",
"scale",
",",
"*",
"*",
"rand_pos",
",",
"p",
"=",
"p",
")"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | rand_crop | Randomized version of `crop_pad`. | fastai/vision/transform.py | 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.):
"Randomized version of `crop_pad`."
return crop_pad(*args, **rand_pos, padding_mode=padding_mode, p=p) | [
"Randomized",
"version",
"of",
"crop_pad",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L222-L224 | [
"def",
"rand_crop",
"(",
"*",
"args",
",",
"padding_mode",
"=",
"'reflection'",
",",
"p",
":",
"float",
"=",
"1.",
")",
":",
"return",
"crop_pad",
"(",
"*",
"args",
",",
"*",
"*",
"rand_pos",
",",
"padding_mode",
"=",
"padding_mode",
",",
"p",
"=",
"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | zoom_crop | Randomly zoom and/or crop. | fastai/vision/transform.py | 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):
"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()] | [
"Randomly",
"zoom",
"and",
"/",
"or",
"crop",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L226-L230 | [
"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",... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _find_coeffs | Find 8 coeff mentioned [here](https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/). | fastai/vision/transform.py | 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,... | 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,... | [
"Find",
"8",
"coeff",
"mentioned",
"[",
"here",
"]",
"(",
"https",
":",
"//",
"web",
".",
"archive",
".",
"org",
"/",
"web",
"/",
"20150222120106",
"/",
"xenia",
".",
"media",
".",
"mit",
".",
"edu",
"/",
"~cwren",
"/",
"interpolator",
"/",
")",
".... | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L235-L246 | [
"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",
")",
":"... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _apply_perspective | Transform `coords` with `coeffs`. | fastai/vision/transform.py | 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 b... | 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 b... | [
"Transform",
"coords",
"with",
"coeffs",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L248-L258 | [
"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... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
train | _do_perspective_warp | Apply warp to `targ_pts` from `_orig_pts` to `c` `FlowField`. | fastai/vision/transform.py | 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):
"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)) | [
"Apply",
"warp",
"to",
"targ_pts",
"from",
"_orig_pts",
"to",
"c",
"FlowField",
"."
] | fastai/fastai | python | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L262-L265 | [
"def",
"_do_perspective_warp",
"(",
"c",
":",
"FlowField",
",",
"targ_pts",
":",
"Points",
",",
"invert",
"=",
"False",
")",
":",
"if",
"invert",
":",
"return",
"_apply_perspective",
"(",
"c",
",",
"_find_coeffs",
"(",
"targ_pts",
",",
"_orig_pts",
")",
")... | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.