id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
20,900 | fastai/fastai | old/fastai/text.py | numericalize_tok | def numericalize_tok(tokens, max_vocab=50000, min_freq=0, unk_tok="_unk_", pad_tok="_pad_", bos_tok="_bos_", eos_tok="_eos_"):
"""Takes in text tokens and returns int2tok and tok2int converters
Arguments:
tokens(list): List of tokens. Can be a list of strings, or a list of lists of strings.
... | python | def numericalize_tok(tokens, max_vocab=50000, min_freq=0, unk_tok="_unk_", pad_tok="_pad_", bos_tok="_bos_", eos_tok="_eos_"):
"""Takes in text tokens and returns int2tok and tok2int converters
Arguments:
tokens(list): List of tokens. Can be a list of strings, or a list of lists of strings.
... | [
"def",
"numericalize_tok",
"(",
"tokens",
",",
"max_vocab",
"=",
"50000",
",",
"min_freq",
"=",
"0",
",",
"unk_tok",
"=",
"\"_unk_\"",
",",
"pad_tok",
"=",
"\"_pad_\"",
",",
"bos_tok",
"=",
"\"_bos_\"",
",",
"eos_tok",
"=",
"\"_eos_\"",
")",
":",
"if",
"... | Takes in text tokens and returns int2tok and tok2int converters
Arguments:
tokens(list): List of tokens. Can be a list of strings, or a list of lists of strings.
max_vocab(int): Number of tokens to return in the vocab (sorted by frequency)
min_freq(int): Minimum number of instances a to... | [
"Takes",
"in",
"text",
"tokens",
"and",
"returns",
"int2tok",
"and",
"tok2int",
"converters"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/text.py#L19-L41 |
20,901 | fastai/fastai | fastai/text/models/qrnn.py | QRNN.reset | def reset(self):
"If your convolutional window is greater than 1 and you save previous xs, you must reset at the beginning of each new sequence."
for layer in self.layers: layer.reset()
if self.bidirectional:
for layer in self.layers_bwd: layer.reset() | python | def reset(self):
"If your convolutional window is greater than 1 and you save previous xs, you must reset at the beginning of each new sequence."
for layer in self.layers: layer.reset()
if self.bidirectional:
for layer in self.layers_bwd: layer.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"for",
"layer",
"in",
"self",
".",
"layers",
":",
"layer",
".",
"reset",
"(",
")",
"if",
"self",
".",
"bidirectional",
":",
"for",
"layer",
"in",
"self",
".",
"layers_bwd",
":",
"layer",
".",
"reset",
"(",
")"... | If your convolutional window is greater than 1 and you save previous xs, you must reset at the beginning of each new sequence. | [
"If",
"your",
"convolutional",
"window",
"is",
"greater",
"than",
"1",
"and",
"you",
"save",
"previous",
"xs",
"you",
"must",
"reset",
"at",
"the",
"beginning",
"of",
"each",
"new",
"sequence",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/models/qrnn.py#L148-L152 |
20,902 | fastai/fastai | docs_src/nbval/kernel.py | start_new_kernel | def start_new_kernel(startup_timeout=60, kernel_name='python', **kwargs):
"""Start a new kernel, and return its Manager and Client"""
logger.debug('Starting new kernel: "%s"' % kernel_name)
km = KernelManager(kernel_name=kernel_name,
kernel_spec_manager=NbvalKernelspecManager())
k... | python | def start_new_kernel(startup_timeout=60, kernel_name='python', **kwargs):
"""Start a new kernel, and return its Manager and Client"""
logger.debug('Starting new kernel: "%s"' % kernel_name)
km = KernelManager(kernel_name=kernel_name,
kernel_spec_manager=NbvalKernelspecManager())
k... | [
"def",
"start_new_kernel",
"(",
"startup_timeout",
"=",
"60",
",",
"kernel_name",
"=",
"'python'",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"'Starting new kernel: \"%s\"'",
"%",
"kernel_name",
")",
"km",
"=",
"KernelManager",
"(",
"kerne... | Start a new kernel, and return its Manager and Client | [
"Start",
"a",
"new",
"kernel",
"and",
"return",
"its",
"Manager",
"and",
"Client"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/kernel.py#L48-L64 |
20,903 | fastai/fastai | docs_src/nbval/kernel.py | RunningKernel.get_message | def get_message(self, stream, timeout=None):
"""
Function is used to get a message from the iopub channel.
Timeout is None by default
When timeout is reached
"""
try:
if stream == 'iopub':
msg = self.kc.get_iopub_msg(timeout=timeout)
... | python | def get_message(self, stream, timeout=None):
"""
Function is used to get a message from the iopub channel.
Timeout is None by default
When timeout is reached
"""
try:
if stream == 'iopub':
msg = self.kc.get_iopub_msg(timeout=timeout)
... | [
"def",
"get_message",
"(",
"self",
",",
"stream",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"if",
"stream",
"==",
"'iopub'",
":",
"msg",
"=",
"self",
".",
"kc",
".",
"get_iopub_msg",
"(",
"timeout",
"=",
"timeout",
")",
"elif",
"stream",
"==... | Function is used to get a message from the iopub channel.
Timeout is None by default
When timeout is reached | [
"Function",
"is",
"used",
"to",
"get",
"a",
"message",
"from",
"the",
"iopub",
"channel",
".",
"Timeout",
"is",
"None",
"by",
"default",
"When",
"timeout",
"is",
"reached"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/kernel.py#L115-L132 |
20,904 | fastai/fastai | docs_src/nbval/kernel.py | RunningKernel.execute_cell_input | def execute_cell_input(self, cell_input, allow_stdin=None):
"""
Executes a string of python code in cell input.
We do not allow the kernel to make requests to the stdin
this is the norm for notebooks
Function returns a unique message id of the reply from
the kernel.... | python | def execute_cell_input(self, cell_input, allow_stdin=None):
"""
Executes a string of python code in cell input.
We do not allow the kernel to make requests to the stdin
this is the norm for notebooks
Function returns a unique message id of the reply from
the kernel.... | [
"def",
"execute_cell_input",
"(",
"self",
",",
"cell_input",
",",
"allow_stdin",
"=",
"None",
")",
":",
"if",
"cell_input",
":",
"logger",
".",
"debug",
"(",
"'Executing cell: \"%s\"...'",
",",
"cell_input",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
"[",
... | Executes a string of python code in cell input.
We do not allow the kernel to make requests to the stdin
this is the norm for notebooks
Function returns a unique message id of the reply from
the kernel. | [
"Executes",
"a",
"string",
"of",
"python",
"code",
"in",
"cell",
"input",
".",
"We",
"do",
"not",
"allow",
"the",
"kernel",
"to",
"make",
"requests",
"to",
"the",
"stdin",
"this",
"is",
"the",
"norm",
"for",
"notebooks"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/kernel.py#L134-L147 |
20,905 | fastai/fastai | docs_src/nbval/kernel.py | RunningKernel.await_idle | def await_idle(self, parent_id, timeout):
"""Poll the iopub stream until an idle message is received for the given parent ID"""
while True:
# Get a message from the kernel iopub channel
msg = self.get_message(timeout=timeout, stream='iopub') # raises Empty on timeout!
... | python | def await_idle(self, parent_id, timeout):
"""Poll the iopub stream until an idle message is received for the given parent ID"""
while True:
# Get a message from the kernel iopub channel
msg = self.get_message(timeout=timeout, stream='iopub') # raises Empty on timeout!
... | [
"def",
"await_idle",
"(",
"self",
",",
"parent_id",
",",
"timeout",
")",
":",
"while",
"True",
":",
"# Get a message from the kernel iopub channel",
"msg",
"=",
"self",
".",
"get_message",
"(",
"timeout",
"=",
"timeout",
",",
"stream",
"=",
"'iopub'",
")",
"# ... | Poll the iopub stream until an idle message is received for the given parent ID | [
"Poll",
"the",
"iopub",
"stream",
"until",
"an",
"idle",
"message",
"is",
"received",
"for",
"the",
"given",
"parent",
"ID"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/kernel.py#L166-L176 |
20,906 | fastai/fastai | docs_src/nbval/kernel.py | RunningKernel.stop | def stop(self):
"""
Instructs the kernel process to stop channels
and the kernel manager to then shutdown the process.
"""
logger.debug('Stopping kernel')
self.kc.stop_channels()
self.km.shutdown_kernel(now=True)
del self.km | python | def stop(self):
"""
Instructs the kernel process to stop channels
and the kernel manager to then shutdown the process.
"""
logger.debug('Stopping kernel')
self.kc.stop_channels()
self.km.shutdown_kernel(now=True)
del self.km | [
"def",
"stop",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Stopping kernel'",
")",
"self",
".",
"kc",
".",
"stop_channels",
"(",
")",
"self",
".",
"km",
".",
"shutdown_kernel",
"(",
"now",
"=",
"True",
")",
"del",
"self",
".",
"km"
] | Instructs the kernel process to stop channels
and the kernel manager to then shutdown the process. | [
"Instructs",
"the",
"kernel",
"process",
"to",
"stop",
"channels",
"and",
"the",
"kernel",
"manager",
"to",
"then",
"shutdown",
"the",
"process",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/kernel.py#L200-L208 |
20,907 | fastai/fastai | old/fastai/dataset.py | resize_img | def resize_img(fname, targ, path, new_path, fn=None):
"""
Enlarge or shrink a single image to scale, such that the smaller of the height or width dimension is equal to targ.
"""
if fn is None:
fn = resize_fn(targ)
dest = os.path.join(path_for(path, new_path, targ), fname)
if os.path.exis... | python | def resize_img(fname, targ, path, new_path, fn=None):
"""
Enlarge or shrink a single image to scale, such that the smaller of the height or width dimension is equal to targ.
"""
if fn is None:
fn = resize_fn(targ)
dest = os.path.join(path_for(path, new_path, targ), fname)
if os.path.exis... | [
"def",
"resize_img",
"(",
"fname",
",",
"targ",
",",
"path",
",",
"new_path",
",",
"fn",
"=",
"None",
")",
":",
"if",
"fn",
"is",
"None",
":",
"fn",
"=",
"resize_fn",
"(",
"targ",
")",
"dest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_for",... | Enlarge or shrink a single image to scale, such that the smaller of the height or width dimension is equal to targ. | [
"Enlarge",
"or",
"shrink",
"a",
"single",
"image",
"to",
"scale",
"such",
"that",
"the",
"smaller",
"of",
"the",
"height",
"or",
"width",
"dimension",
"is",
"equal",
"to",
"targ",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L34-L44 |
20,908 | fastai/fastai | old/fastai/dataset.py | read_dir | 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]
... | python | 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",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"folder",
")",
"fnames",
"=",
"glob",
"(",
"f\"{full_path}/*.*\"",
")",
"directories",
"=",
"glob",
"(",
"f\"{full_path}/*/\"",
"... | Returns a list of relative file paths to `path` for all files within `folder` | [
"Returns",
"a",
"list",
"of",
"relative",
"file",
"paths",
"to",
"path",
"for",
"all",
"files",
"within",
"folder"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L89-L99 |
20,909 | fastai/fastai | old/fastai/dataset.py | read_dirs | 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... | python | 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",
")",
":",
"lbls",
",",
"fnames",
",",
"all_lbls",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"folder",
")",
"for",
"lbl",
"in"... | Fetches name of all files in path in long form, and labels associated by extrapolation of directory names. | [
"Fetches",
"name",
"of",
"all",
"files",
"in",
"path",
"in",
"long",
"form",
"and",
"labels",
"associated",
"by",
"extrapolation",
"of",
"directory",
"names",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L101-L114 |
20,910 | fastai/fastai | old/fastai/dataset.py | n_hot | 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 | python | 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",
")",
":",
"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 | [
"one",
"hot",
"encoding",
"by",
"index",
".",
"Returns",
"array",
"of",
"length",
"c",
"where",
"all",
"entries",
"are",
"0",
"except",
"for",
"the",
"indecies",
"in",
"ids"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L116-L122 |
20,911 | fastai/fastai | old/fastai/dataset.py | parse_csv_labels | 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... | python | 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",
"=",
"' '",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"fn",
",",
"index_col",
"=",
"0",
",",
"header",
"=",
"0",
"if",
"skip_header",
"else",
"None",
... | 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... | [
"Parse",
"filenames",
"and",
"label",
"sets",
"from",
"a",
"CSV",
"file",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L140-L162 |
20,912 | fastai/fastai | old/fastai/dataset.py | isdicom | 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' | python | 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",
")",
":",
"fn",
"=",
"str",
"(",
"fn",
")",
"if",
"fn",
".",
"endswith",
"(",
"'.dcm'",
")",
":",
"return",
"True",
"# Dicom signature from the dicom spec.",
"with",
"open",
"(",
"fn",
",",
"'rb'",
")",
"as",
"fh",
":",
"... | True if the fn points to a DICOM image | [
"True",
"if",
"the",
"fn",
"points",
"to",
"a",
"DICOM",
"image"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L245-L253 |
20,913 | fastai/fastai | old/fastai/dataset.py | open_image | 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... | python | 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",
")",
":",
"flags",
"=",
"cv2",
".",
"IMREAD_UNCHANGED",
"+",
"cv2",
".",
"IMREAD_ANYDEPTH",
"+",
"cv2",
".",
"IMREAD_ANYCOLOR",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
"and",
"not",
"str",
"(",
"... | 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 | [
"Opens",
"an",
"image",
"using",
"OpenCV",
"given",
"the",
"file",
"path",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L255-L293 |
20,914 | fastai/fastai | old/fastai/dataset.py | FilesDataset.denorm | 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... | python | 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",
")",
":",
"if",
"type",
"(",
"arr",
")",
"is",
"not",
"np",
".",
"ndarray",
":",
"arr",
"=",
"to_np",
"(",
"arr",
")",
"if",
"len",
"(",
"arr",
".",
"shape",
")",
"==",
"3",
":",
"arr",
"=",
"arr",
... | Reverse the normalization done to a batch of images.
Arguments:
arr: of shape/size (N,3,sz,sz) | [
"Reverse",
"the",
"normalization",
"done",
"to",
"a",
"batch",
"of",
"images",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L317-L325 |
20,915 | fastai/fastai | old/fastai/dataset.py | ImageData.resized | 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 | python | 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",
"dl",
".",
"dataset",
".",
"resize_imgs",
"(",
"targ",
",",
"new_path",
",",
"resume",
"=",
"resume",
",... | Return a copy of this dataset resized | [
"Return",
"a",
"copy",
"of",
"this",
"dataset",
"resized"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L423-L427 |
20,916 | fastai/fastai | old/fastai/dataset.py | ImageData.resize | 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... | python | 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",
")",
":",
"new_ds",
"=",
"[",
"]",
"dls",
"=",
"[",
"self",
".",
"trn_dl",
",",
"self",
".",
"val_dl",
",",
"self",
... | 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... | [
"Resizes",
"all",
"the",
"images",
"in",
"the",
"train",
"valid",
"test",
"folders",
"to",
"a",
"given",
"size",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L429-L447 |
20,917 | fastai/fastai | old/fastai/dataset.py | ImageClassifierData.from_arrays | 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)
... | python | 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",
... | 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 ... | [
"Read",
"in",
"images",
"and",
"their",
"labels",
"given",
"as",
"numpy",
"arrays"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L476-L495 |
20,918 | fastai/fastai | old/fastai/dataset.py | ImageClassifierData.from_paths | 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... | python | 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... | 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:... | [
"Read",
"in",
"images",
"and",
"their",
"labels",
"given",
"as",
"sub",
"-",
"folder",
"names"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L498-L519 |
20,919 | fastai/fastai | old/fastai/dataset.py | ImageClassifierData.from_csv | 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... | python | 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",
",",
"conti... | 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)
... | [
"Read",
"in",
"images",
"and",
"their",
"labels",
"given",
"as",
"a",
"CSV",
"file",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L522-L553 |
20,920 | fastai/fastai | old/fastai/dataset.py | ImageClassifierData.from_path_and_array | 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... | python | 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",
")",
... | 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... | [
"Read",
"in",
"images",
"given",
"a",
"sub",
"-",
"folder",
"and",
"their",
"labels",
"given",
"a",
"numpy",
"array"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/dataset.py#L556-L578 |
20,921 | fastai/fastai | fastai/utils/ipython.py | gpu_mem_restore | 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... | python | 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",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tb_clear_frames",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'FASTAI_TB_CLEAR_F... | Reclaim GPU RAM if CUDA out of memory happened, or execution was interrupted | [
"Reclaim",
"GPU",
"RAM",
"if",
"CUDA",
"out",
"of",
"memory",
"happened",
"or",
"execution",
"was",
"interrupted"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/utils/ipython.py#L35-L55 |
20,922 | fastai/fastai | fastai/gen_doc/nbdoc.py | link_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)})'... | python | 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",
")",
":",
"arg_name",
"=",
"arg_name",
"or",
"fn_name",
"(",
"arg_type",
")",
"if",
"include_bt",
":",
"arg_name",
"=",
"code_esc",
"(",
"arg_... | Create link to documentation. | [
"Create",
"link",
"to",
"documentation",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L31-L37 |
20,923 | fastai/fastai | fastai/gen_doc/nbdoc.py | belongs_to_module | 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) | python | 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",
")",
":",
"if",
"hasattr",
"(",
"t",
",",
"'__func__'",
")",
":",
"return",
"belongs_to_module",
"(",
"t",
".",
"__func__",
",",
"module_name",
")",
"if",
"not",
"inspect",
".",
"getmodule",
"(",
... | Check if `t` belongs to `module_name`. | [
"Check",
"if",
"t",
"belongs",
"to",
"module_name",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L41-L45 |
20,924 | fastai/fastai | fastai/gen_doc/nbdoc.py | format_ft_def | 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... | python | 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",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"name",
"=",
"f'<code>{full_name or func.__name__}</code>'",
"fmt_params",
"=",
"[",
"format_param... | Format and link `func` definition to show in documentation | [
"Format",
"and",
"link",
"func",
"definition",
"to",
"show",
"in",
"documentation"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L79-L89 |
20,925 | fastai/fastai | fastai/gen_doc/nbdoc.py | get_enum_doc | 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}]' | python | 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",
":",
"vals",
"=",
"', '",
".",
"join",
"(",
"elt",
".",
"__members__",
".",
"keys",
"(",
")",
")",
"return",
"f'{code_esc(full_name)}'",
",",
"f'<code>Enum</code> = [{vals}]'"... | Formatted enum documentation. | [
"Formatted",
"enum",
"documentation",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L91-L94 |
20,926 | fastai/fastai | fastai/gen_doc/nbdoc.py | get_cls_doc | 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 | python | 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",
":",
"parent_class",
"=",
"inspect",
".",
"getclasstree",
"(",
"[",
"elt",
"]",
")",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
"0",
"]",
"name",
",",... | Class definition. | [
"Class",
"definition",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L96-L101 |
20,927 | fastai/fastai | fastai/gen_doc/nbdoc.py | doc | 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... | python | 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",
")",
":",
"global",
"use_relative_links",
"use_relative_links",
"=",
"False",
"elt",
"=",
"getattr",
"(",
"elt",
",",
"'__func__'",
",",
"elt",
")",
"md",
"=",
"show_doc",
"(",
"elt",
",",
"markdown",
"=",
"False",
")",
"if",
... | Show `show_doc` info in preview window along with link to full docs. | [
"Show",
"show_doc",
"info",
"in",
"preview",
"window",
"along",
"with",
"link",
"to",
"full",
"docs",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L126-L139 |
20,928 | fastai/fastai | fastai/gen_doc/nbdoc.py | format_docstring | 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']} {... | python | 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",
":",
"parsed",
"=",
"\"\"",
"doc",
"=",
"parse_docstr... | Merge and format the docstring definition with `arg_comments` and `alt_doc_string`. | [
"Merge",
"and",
"format",
"the",
"docstring",
"definition",
"with",
"arg_comments",
"and",
"alt_doc_string",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L141-L157 |
20,929 | fastai/fastai | fastai/gen_doc/nbdoc.py | link_docstring | 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... | python | 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",
":",
"mods",
"=",
"listify",
"(",
"modules",
")",
"for",
"mod",
"in",
"mods",
":",
"_modvars",
".",
"update",
"(",
"... | Search `docstring` for backticks and attempt to link those functions to respective documentation. | [
"Search",
"docstring",
"for",
"backticks",
"and",
"attempt",
"to",
"link",
"those",
"functions",
"to",
"respective",
"documentation",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L169-L173 |
20,930 | fastai/fastai | fastai/gen_doc/nbdoc.py | find_elt | 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... | python | 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",
")",
":",
"keyword",
"=",
"strip_fastai",
"(",
"keyword",
")",
"if",
"keyword",
"in",
"modvars",
":",
"return",
"modvars",
"[",
"keyword",
"]",
"comps",
"=",
"keyword",
"... | Attempt to resolve keywords such as Learner.lr_find. `match_last` starts matching from last component. | [
"Attempt",
"to",
"resolve",
"keywords",
"such",
"as",
"Learner",
".",
"lr_find",
".",
"match_last",
"starts",
"matching",
"from",
"last",
"component",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L175-L181 |
20,931 | fastai/fastai | fastai/gen_doc/nbdoc.py | import_mod | 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:
... | python | 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",
")",
":",
"splits",
"=",
"str",
".",
"split",
"(",
"mod_name",
",",
"'.'",
")",
"try",
":",
"if",
"len",
"(",
"splits",
")",
">",
"1",
":",
"mod",
"=",
"importlib... | Return module from `mod_name`. | [
"Return",
"module",
"from",
"mod_name",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L183-L191 |
20,932 | fastai/fastai | fastai/gen_doc/nbdoc.py | show_doc_from_name | 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... | python | 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",
"=",
"''",
")",
":",
"mod",
"=",
"import_mod",
"(... | Show documentation for `ft_name`, see `show_doc`. | [
"Show",
"documentation",
"for",
"ft_name",
"see",
"show_doc",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L193-L202 |
20,933 | fastai/fastai | fastai/gen_doc/nbdoc.py | get_ft_names | 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... | python | 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",
"]",
":",
"# If the module has an attribute __all__, it picks those.",
"# Otherwise, it returns all the functions defined inside a module.",
"fn_names",
"=",
"[",
"]",
"for... | Return all the functions of module `mod`. | [
"Return",
"all",
"the",
"functions",
"of",
"module",
"mod",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L209-L228 |
20,934 | fastai/fastai | fastai/gen_doc/nbdoc.py | get_inner_fts | 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... | python | 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",
"]",
":",
"fts",
"=",
"[",
"]",
"for",
"ft_name",
"in",
"elt",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"if",
"ft_name",
".",
"startswith",
"(",
"'_'",
")",
":",
"continue",
"... | List the inner functions of a class. | [
"List",
"the",
"inner",
"functions",
"of",
"a",
"class",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L230-L239 |
20,935 | fastai/fastai | fastai/gen_doc/nbdoc.py | get_module_toc | 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'
... | python | 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",
")",
":",
"mod",
"=",
"import_mod",
"(",
"mod_name",
")",
"ft_names",
"=",
"mod",
".",
"__all__",
"if",
"hasattr",
"(",
"mod",
",",
"'__all__'",
")",
"else",
"get_ft_names",
"(",
"mod",
")",
"ft_names",
".",
"sor... | Display table of contents for given `mod_name`. | [
"Display",
"table",
"of",
"contents",
"for",
"given",
"mod_name",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L241-L254 |
20,936 | fastai/fastai | fastai/gen_doc/nbdoc.py | get_fn_link | 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... | python | 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",
":",
"ft",
"=",
"getattr",
"(",
"ft",
",",
"'__func__'",
",",
"ft",
")",
"anchor",
"=",
"strip_fastai",
"(",
"get_anchor",
"(",
"ft",
")",
")",
"module_name",
"=",
"strip_fastai",
"(",
"get_module_name",... | Return function link to notebook documentation of `ft`. Private functions link to source code | [
"Return",
"function",
"link",
"to",
"notebook",
"documentation",
"of",
"ft",
".",
"Private",
"functions",
"link",
"to",
"source",
"code"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L278-L284 |
20,937 | fastai/fastai | fastai/gen_doc/nbdoc.py | get_pytorch_link | 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'):
... | python | 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",
":",
"name",
"=",
"ft",
".",
"__name__",
"ext",
"=",
"'.html'",
"if",
"name",
"==",
"'device'",
":",
"return",
"f'{PYTORCH_DOCS}tensor_attributes{ext}#torch-device'",
"if",
"name",
"==",
"'Tensor'",
":",
... | Returns link to pytorch docs of `ft`. | [
"Returns",
"link",
"to",
"pytorch",
"docs",
"of",
"ft",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L288-L308 |
20,938 | fastai/fastai | fastai/gen_doc/nbdoc.py | get_source_link | 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>' | python | 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",
":",
"link",
"=",
"f\"{SOURCE_URL}{file}#L{line}\"",
"if",
"display_text",
"is",
"None",
":",
"return",
"link",
"return",
... | Returns github link for given file | [
"Returns",
"github",
"link",
"for",
"given",
"file"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L310-L314 |
20,939 | fastai/fastai | fastai/gen_doc/nbdoc.py | get_function_source | 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) | python | 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",
":",
"try",
":",
"line",
"=",
"inspect",
".",
"getsourcelines",
"(",
"ft",
")",
"[",
"1",
"]",
"except",
"Exception",
":",
"return",
"''",
"mod_path",
"=",
"get_module_... | Returns link to `ft` in source code. | [
"Returns",
"link",
"to",
"ft",
"in",
"source",
"code",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/nbdoc.py#L316-L321 |
20,940 | fastai/fastai | docs_src/nbval/plugin.py | find_comment_markers | 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... | python | 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",
")",
":",
"found",
"=",
"{",
"}",
"for",
"line",
"in",
"cellsource",
".",
"splitlines",
"(",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":... | Look through the cell source for comments which affect nbval's behaviour
Yield an iterable of ``(MARKER_TYPE, True)``. | [
"Look",
"through",
"the",
"cell",
"source",
"for",
"comments",
"which",
"affect",
"nbval",
"s",
"behaviour"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L135-L160 |
20,941 | fastai/fastai | docs_src/nbval/plugin.py | coalesce_streams | 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 = []
... | python | 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",
")",
":",
"if",
"not",
"outputs",
":",
"return",
"outputs",
"new_outputs",
"=",
"[",
"]",
"streams",
"=",
"{",
"}",
"for",
"output",
"in",
"outputs",
":",
"if",
"(",
"output",
".",
"output_type",
"==",
"'stream'... | Merge all stream outputs with shared names into single streams
to ensure deterministic outputs.
Parameters
----------
outputs : iterable of NotebookNodes
Outputs being processed | [
"Merge",
"all",
"stream",
"outputs",
"with",
"shared",
"names",
"into",
"single",
"streams",
"to",
"ensure",
"deterministic",
"outputs",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L796-L831 |
20,942 | fastai/fastai | docs_src/nbval/plugin.py | transform_streams_for_comparison | 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... | python | 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",
")",
":",
"new_outputs",
"=",
"[",
"]",
"for",
"output",
"in",
"outputs",
":",
"if",
"(",
"output",
".",
"output_type",
"==",
"'stream'",
")",
":",
"# Transform output",
"new_outputs",
".",
"append",
"... | Makes failure output for streams better by having key be the stream name | [
"Makes",
"failure",
"output",
"for",
"streams",
"better",
"by",
"having",
"key",
"be",
"the",
"stream",
"name"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L834-L846 |
20,943 | fastai/fastai | docs_src/nbval/plugin.py | _trim_base64 | 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 | python | 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",
")",
":",
"if",
"len",
"(",
"s",
")",
">",
"64",
"and",
"_base64",
".",
"match",
"(",
"s",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
")",
":",
"h",
"=",
"hash_string",
"(",
"s",
")",
"s",
"=",
"'%s...<snip b... | Trim and hash base64 strings | [
"Trim",
"and",
"hash",
"base64",
"strings"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L873-L878 |
20,944 | fastai/fastai | docs_src/nbval/plugin.py | _indent | 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 | python | 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",
"=",
"' '",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"string_types",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"(",
"'%s%s'",
"%",
"(",
"indent",
",",
"line",
")",
"for",
"line",
"i... | Intent each line with indent | [
"Intent",
"each",
"line",
"with",
"indent"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L881-L885 |
20,945 | fastai/fastai | docs_src/nbval/plugin.py | IPyNbFile.setup | 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... | python | 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",
")",
":",
"if",
"self",
".",
"parent",
".",
"config",
".",
"option",
".",
"current_env",
":",
"kernel_name",
"=",
"CURRENT_ENV_KERNEL_NAME",
"else",
":",
"kernel_name",
"=",
"self",
".",
"nb",
".",
"metadata",
".",
"get",
"("... | Called by pytest to setup the collector cells in .
Here we start a kernel and setup the sanitize patterns. | [
"Called",
"by",
"pytest",
"to",
"setup",
"the",
"collector",
"cells",
"in",
".",
"Here",
"we",
"start",
"a",
"kernel",
"and",
"setup",
"the",
"sanitize",
"patterns",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L221-L235 |
20,946 | fastai/fastai | docs_src/nbval/plugin.py | IPyNbFile.setup_sanitize_files | 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:
... | python | 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",
"fname",
"in",
"self",
".",
"get_sanitize_files",
"(",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'r'",
")",
"as",
"f",
":",
"self",
".",
"sanitize_patterns",
".",
"update",
"(",
"get_saniti... | 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",
"each",
"of",
"the",
"sanitize",
"files",
"that",
"were",
"specified",
"as",
"command",
"line",
"options",
"load",
"the",
"contents",
"of",
"the",
"file",
"into",
"the",
"sanitise",
"patterns",
"dictionary",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L238-L245 |
20,947 | fastai/fastai | docs_src/nbval/plugin.py | IPyNbFile.get_sanitize_files | 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... | python | 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",
")",
":",
"if",
"self",
".",
"parent",
".",
"config",
".",
"option",
".",
"sanitize_with",
"is",
"not",
"None",
":",
"return",
"[",
"self",
".",
"parent",
".",
"config",
".",
"option",
".",
"sanitize_with",
"]",
... | 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 | [
"Return",
"list",
"of",
"all",
"sanitize",
"files",
"provided",
"by",
"the",
"user",
"on",
"the",
"command",
"line",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L248-L259 |
20,948 | fastai/fastai | docs_src/nbval/plugin.py | IPyNbFile.get_kernel_message | 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) | python | 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'",
")",
":",
"return",
"self",
".",
"kernel",
".",
"get_message",
"(",
"stream",
",",
"timeout",
"=",
"timeout",
")"
] | Gets a message from the iopub channel of the notebook kernel. | [
"Gets",
"a",
"message",
"from",
"the",
"iopub",
"channel",
"of",
"the",
"notebook",
"kernel",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L261-L265 |
20,949 | fastai/fastai | docs_src/nbval/plugin.py | IPyNbFile.collect | 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
... | python | 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",
")",
":",
"self",
".",
"nb",
"=",
"nbformat",
".",
"read",
"(",
"str",
"(",
"self",
".",
"fspath",
")",
",",
"as_version",
"=",
"4",
")",
"# Start the cell count",
"cell_num",
"=",
"0",
"# Iterate over the cells in the notebook... | 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. | [
"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",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L269-L309 |
20,950 | fastai/fastai | docs_src/nbval/plugin.py | IPyNbCell.format_output_compare | 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... | python | 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",
")",
":",
"if",
"isinstance",
"(",
"left",
",",
"six",
".",
"string_types",
")",
":",
"left",
"=",
"_trim_base64",
"(",
"left",
")",
"if",
"isinstance",
"(",
"right",
"... | Format an output for printing | [
"Format",
"an",
"output",
"for",
"printing"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L480-L517 |
20,951 | fastai/fastai | docs_src/nbval/plugin.py | IPyNbCell.sanitize | 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... | python | 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",
")",
":",
"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 ... | sanitize a string for comparison. | [
"sanitize",
"a",
"string",
"for",
"comparison",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/docs_src/nbval/plugin.py#L775-L789 |
20,952 | fastai/fastai | fastai/vision/tta.py | _tta_only | 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
... | python | 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",
"]",
"]",
":",
"dl",
"=",
"learn",
"."... | Computes the outputs for several augmented inputs for TTA | [
"Computes",
"the",
"outputs",
"for",
"several",
"augmented",
"inputs",
"for",
"TTA"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/tta.py#L10-L28 |
20,953 | fastai/fastai | fastai/vision/tta.py | _TTA | 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_... | python | 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",
")",
"->",... | Applies TTA to predict on `ds_type` dataset. | [
"Applies",
"TTA",
"to",
"predict",
"on",
"ds_type",
"dataset",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/tta.py#L32-L43 |
20,954 | fastai/fastai | fastai/metrics.py | fbeta | 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... | python | 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",
")",
"->",
... | Computes the f_beta between `preds` and `targets` | [
"Computes",
"the",
"f_beta",
"between",
"preds",
"and",
"targets"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L12-L22 |
20,955 | fastai/fastai | fastai/metrics.py | accuracy_thresh | 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() | python | 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",
":",
"if",
"sigmoid",
":",
"y_pred",
"=",
"y_pred",
".",
... | Compute accuracy when `y_pred` and `y_true` are the same size. | [
"Compute",
"accuracy",
"when",
"y_pred",
"and",
"y_true",
"are",
"the",
"same",
"size",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L31-L34 |
20,956 | fastai/fastai | fastai/metrics.py | dice | 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... | python | 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",
":",
"n",
"=",
"targs",
".",
"shape",
"[",
"0",
"]",
"input",
"=",
"input",
".",
"argmax",
"(",
"dim",
"=",
... | Dice coefficient metric for binary target. If iou=True, returns iou metric, classic for segmentation problems. | [
"Dice",
"coefficient",
"metric",
"for",
"binary",
"target",
".",
"If",
"iou",
"=",
"True",
"returns",
"iou",
"metric",
"classic",
"for",
"segmentation",
"problems",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L46-L54 |
20,957 | fastai/fastai | fastai/metrics.py | exp_rmspe | 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()) | python | 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",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"pred",
",",
"targ",
"=",
"torch",
".",
"exp",
"(",
"pred",
")",
",... | Exp RMSE between `pred` and `targ`. | [
"Exp",
"RMSE",
"between",
"pred",
"and",
"targ",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L56-L61 |
20,958 | fastai/fastai | fastai/metrics.py | mean_absolute_error | 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() | python | 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",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"return",
"torch",
".",
"abs",
"(",
"targ",
"-",
"pred",
")",... | Mean absolute error between `pred` and `targ`. | [
"Mean",
"absolute",
"error",
"between",
"pred",
"and",
"targ",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L63-L66 |
20,959 | fastai/fastai | fastai/metrics.py | mean_squared_error | 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) | python | 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",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"return",
"F",
".",
"mse_loss",
"(",
"pred",
",",
"targ",
")"
... | Mean squared error between `pred` and `targ`. | [
"Mean",
"squared",
"error",
"between",
"pred",
"and",
"targ",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L68-L71 |
20,960 | fastai/fastai | fastai/metrics.py | root_mean_squared_error | 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)) | python | 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",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"return",
"torch",
".",
"sqrt",
"(",
"F",
".",
"mse_loss",
... | Root mean squared error between `pred` and `targ`. | [
"Root",
"mean",
"squared",
"error",
"between",
"pred",
"and",
"targ",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L73-L76 |
20,961 | fastai/fastai | fastai/metrics.py | mean_squared_logarithmic_error | 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)) | python | 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",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"return",
"F",
".",
"mse_loss",
"(",
"torch",
".",
"... | Mean squared logarithmic error between `pred` and `targ`. | [
"Mean",
"squared",
"logarithmic",
"error",
"between",
"pred",
"and",
"targ",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L78-L81 |
20,962 | fastai/fastai | fastai/metrics.py | explained_variance | 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 | python | 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",
":",
"pred",
",",
"targ",
"=",
"flatten_check",
"(",
"pred",
",",
"targ",
")",
"var_pct",
"=",
"torch",
".",
"var",
"(",
"targ",
"-",
"pred",... | Explained variance between `pred` and `targ`. | [
"Explained",
"variance",
"between",
"pred",
"and",
"targ",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L83-L87 |
20,963 | fastai/fastai | fastai/metrics.py | auc_roc_score | 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... | python | 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",
")",
":",
"fpr",
",",
"tpr",
"=",
"roc_curve",
"(",
"input",
",",
"targ",
")",
"d",
"=",
"fpr",
"[",
"1",
":",
"]",
"-",
"fpr",
"[",
":",
"-",
"1",
"]",
"sl1",
"... | Using trapezoid method to calculate the area under roc curve | [
"Using",
"trapezoid",
"method",
"to",
"calculate",
"the",
"area",
"under",
"roc",
"curve"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L266-L272 |
20,964 | fastai/fastai | fastai/metrics.py | roc_curve | 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... | python | 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",
")",
":",
"targ",
"=",
"(",
"targ",
"==",
"1",
")",
"desc_score_indices",
"=",
"torch",
".",
"flip",
"(",
"input",
".",
"argsort",
"(",
"-",
"1",
")",
",",
"[",
"-",
"1"... | Returns the false positive and true positive rates | [
"Returns",
"the",
"false",
"positive",
"and",
"true",
"positive",
"rates"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/metrics.py#L274-L289 |
20,965 | fastai/fastai | old/fastai/core.py | 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] | python | 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",
")",
":",
"return",
"np",
".",
"array",
"(",
"a",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"a",
")",
"==",
"1",
"else",
"[",
"np",
".",
"array",
"(",
"o",
")",
"for",
"o",
"in",
"a",
"]"
] | convert iterable object into numpy array | [
"convert",
"iterable",
"object",
"into",
"numpy",
"array"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L25-L27 |
20,966 | fastai/fastai | old/fastai/core.py | T | 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):
... | python | 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",
")",
":",
"if",
"not",
"torch",
".",
"is_tensor",
"(",
"a",
")",
":",
"a",
"=",
"np",
".",
"array",
"(",
"np",
".",
"ascontiguousarray",
"(",
"a",
")",
")",
"if",
"a",... | Convert numpy array into a pytorch tensor.
if Cuda is available and USE_GPU=True, store resulting tensor in GPU. | [
"Convert",
"numpy",
"array",
"into",
"a",
"pytorch",
"tensor",
".",
"if",
"Cuda",
"is",
"available",
"and",
"USE_GPU",
"=",
"True",
"store",
"resulting",
"tensor",
"in",
"GPU",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L29-L42 |
20,967 | fastai/fastai | old/fastai/core.py | V_ | 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) | python | 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",
")",
":",
"return",
"create_variable",
"(",
"x",
",",
"volatile",
"=",
"volatile",
",",
"requires_grad",
"=",
"requires_grad",
")"
] | equivalent to create_variable, which creates a pytorch tensor | [
"equivalent",
"to",
"create_variable",
"which",
"creates",
"a",
"pytorch",
"tensor"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L56-L58 |
20,968 | fastai/fastai | old/fastai/core.py | V | 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)) | python | 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",
")",
":",
"return",
"map_over",
"(",
"x",
",",
"lambda",
"o",
":",
"V_",
"(",
"o",
",",
"requires_grad",
",",
"volatile",
")",
")"
] | creates a single or a list of pytorch tensors, depending on input x. | [
"creates",
"a",
"single",
"or",
"a",
"list",
"of",
"pytorch",
"tensors",
"depending",
"on",
"input",
"x",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L59-L61 |
20,969 | fastai/fastai | old/fastai/core.py | to_np | 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): ... | python | 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",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"float",
")",
":",
"return",
"np",
".",
"array",
"(",
"v",
")",
"if",
"isinstance",
"(",
"v",
",",
"(",
"np",
".",
"ndarray",
",",
"np",
".",
"generic",
")",
")",
":",
"re... | returns an np.array object given an input of np.array, list, tuple, torch variable or tensor. | [
"returns",
"an",
"np",
".",
"array",
"object",
"given",
"an",
"input",
"of",
"np",
".",
"array",
"list",
"tuple",
"torch",
"variable",
"or",
"tensor",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L71-L80 |
20,970 | fastai/fastai | old/fastai/core.py | to_gpu | 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 | python | 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",
")",
":",
"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. | [
"puts",
"pytorch",
"variable",
"to",
"gpu",
"if",
"cuda",
"is",
"available",
"and",
"USE_GPU",
"is",
"set",
"to",
"true",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L88-L90 |
20,971 | fastai/fastai | old/fastai/core.py | split_by_idxs | def split_by_idxs(seq, idxs):
'''A generator that returns sequence pieces, seperated by indexes specified in idxs. '''
last = 0
for idx in idxs:
if not (-len(seq) <= idx < len(seq)):
raise KeyError(f'Idx {idx} is out-of-bounds')
yield seq[last:idx]
last = idx
yield seq[... | python | def split_by_idxs(seq, idxs):
'''A generator that returns sequence pieces, seperated by indexes specified in idxs. '''
last = 0
for idx in idxs:
if not (-len(seq) <= idx < len(seq)):
raise KeyError(f'Idx {idx} is out-of-bounds')
yield seq[last:idx]
last = idx
yield seq[... | [
"def",
"split_by_idxs",
"(",
"seq",
",",
"idxs",
")",
":",
"last",
"=",
"0",
"for",
"idx",
"in",
"idxs",
":",
"if",
"not",
"(",
"-",
"len",
"(",
"seq",
")",
"<=",
"idx",
"<",
"len",
"(",
"seq",
")",
")",
":",
"raise",
"KeyError",
"(",
"f'Idx {i... | A generator that returns sequence pieces, seperated by indexes specified in idxs. | [
"A",
"generator",
"that",
"returns",
"sequence",
"pieces",
"seperated",
"by",
"indexes",
"specified",
"in",
"idxs",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L94-L102 |
20,972 | fastai/fastai | old/fastai/core.py | partition | def partition(a, sz):
"""splits iterables a in equal parts of size sz"""
return [a[i:i+sz] for i in range(0, len(a), sz)] | python | def partition(a, sz):
"""splits iterables a in equal parts of size sz"""
return [a[i:i+sz] for i in range(0, len(a), sz)] | [
"def",
"partition",
"(",
"a",
",",
"sz",
")",
":",
"return",
"[",
"a",
"[",
"i",
":",
"i",
"+",
"sz",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"a",
")",
",",
"sz",
")",
"]"
] | splits iterables a in equal parts of size sz | [
"splits",
"iterables",
"a",
"in",
"equal",
"parts",
"of",
"size",
"sz"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L131-L133 |
20,973 | fastai/fastai | old/fastai/core.py | chunk_iter | def chunk_iter(iterable, chunk_size):
'''A generator that yields chunks of iterable, chunk_size at a time. '''
while True:
chunk = []
try:
for _ in range(chunk_size): chunk.append(next(iterable))
yield chunk
except StopIteration:
if chunk: yield chunk
... | python | def chunk_iter(iterable, chunk_size):
'''A generator that yields chunks of iterable, chunk_size at a time. '''
while True:
chunk = []
try:
for _ in range(chunk_size): chunk.append(next(iterable))
yield chunk
except StopIteration:
if chunk: yield chunk
... | [
"def",
"chunk_iter",
"(",
"iterable",
",",
"chunk_size",
")",
":",
"while",
"True",
":",
"chunk",
"=",
"[",
"]",
"try",
":",
"for",
"_",
"in",
"range",
"(",
"chunk_size",
")",
":",
"chunk",
".",
"append",
"(",
"next",
"(",
"iterable",
")",
")",
"yi... | A generator that yields chunks of iterable, chunk_size at a time. | [
"A",
"generator",
"that",
"yields",
"chunks",
"of",
"iterable",
"chunk_size",
"at",
"a",
"time",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/core.py#L184-L193 |
20,974 | fastai/fastai | fastai/vision/transform.py | _brightness | def _brightness(x, change:uniform):
"Apply `change` in brightness of image `x`."
return x.add_(scipy.special.logit(change)) | python | def _brightness(x, change:uniform):
"Apply `change` in brightness of image `x`."
return x.add_(scipy.special.logit(change)) | [
"def",
"_brightness",
"(",
"x",
",",
"change",
":",
"uniform",
")",
":",
"return",
"x",
".",
"add_",
"(",
"scipy",
".",
"special",
".",
"logit",
"(",
"change",
")",
")"
] | Apply `change` in brightness of image `x`. | [
"Apply",
"change",
"in",
"brightness",
"of",
"image",
"x",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L15-L17 |
20,975 | fastai/fastai | fastai/vision/transform.py | _rotate | def _rotate(degrees:uniform):
"Rotate image by `degrees`."
angle = degrees * math.pi / 180
return [[cos(angle), -sin(angle), 0.],
[sin(angle), cos(angle), 0.],
[0. , 0. , 1.]] | python | def _rotate(degrees:uniform):
"Rotate image by `degrees`."
angle = degrees * math.pi / 180
return [[cos(angle), -sin(angle), 0.],
[sin(angle), cos(angle), 0.],
[0. , 0. , 1.]] | [
"def",
"_rotate",
"(",
"degrees",
":",
"uniform",
")",
":",
"angle",
"=",
"degrees",
"*",
"math",
".",
"pi",
"/",
"180",
"return",
"[",
"[",
"cos",
"(",
"angle",
")",
",",
"-",
"sin",
"(",
"angle",
")",
",",
"0.",
"]",
",",
"[",
"sin",
"(",
"... | Rotate image by `degrees`. | [
"Rotate",
"image",
"by",
"degrees",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L25-L30 |
20,976 | fastai/fastai | fastai/vision/transform.py | _get_zoom_mat | def _get_zoom_mat(sw:float, sh:float, c:float, r:float)->AffineMatrix:
"`sw`,`sh` scale width,height - `c`,`r` focus col,row."
return [[sw, 0, c],
[0, sh, r],
[0, 0, 1.]] | python | def _get_zoom_mat(sw:float, sh:float, c:float, r:float)->AffineMatrix:
"`sw`,`sh` scale width,height - `c`,`r` focus col,row."
return [[sw, 0, c],
[0, sh, r],
[0, 0, 1.]] | [
"def",
"_get_zoom_mat",
"(",
"sw",
":",
"float",
",",
"sh",
":",
"float",
",",
"c",
":",
"float",
",",
"r",
":",
"float",
")",
"->",
"AffineMatrix",
":",
"return",
"[",
"[",
"sw",
",",
"0",
",",
"c",
"]",
",",
"[",
"0",
",",
"sh",
",",
"r",
... | `sw`,`sh` scale width,height - `c`,`r` focus col,row. | [
"sw",
"sh",
"scale",
"width",
"height",
"-",
"c",
"r",
"focus",
"col",
"row",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L33-L37 |
20,977 | fastai/fastai | fastai/vision/transform.py | _zoom | def _zoom(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5):
"Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom."
s = 1-1/scale
col_c = s * (2*col_pct - 1)
row_c = s * (2*row_pct - 1)
return _get_zoom_mat(1/scale, 1/scale, col_c, row_c) | python | def _zoom(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5):
"Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom."
s = 1-1/scale
col_c = s * (2*col_pct - 1)
row_c = s * (2*row_pct - 1)
return _get_zoom_mat(1/scale, 1/scale, col_c, row_c) | [
"def",
"_zoom",
"(",
"scale",
":",
"uniform",
"=",
"1.0",
",",
"row_pct",
":",
"uniform",
"=",
"0.5",
",",
"col_pct",
":",
"uniform",
"=",
"0.5",
")",
":",
"s",
"=",
"1",
"-",
"1",
"/",
"scale",
"col_c",
"=",
"s",
"*",
"(",
"2",
"*",
"col_pct",... | Zoom image by `scale`. `row_pct`,`col_pct` select focal point of zoom. | [
"Zoom",
"image",
"by",
"scale",
".",
"row_pct",
"col_pct",
"select",
"focal",
"point",
"of",
"zoom",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L39-L44 |
20,978 | fastai/fastai | fastai/vision/transform.py | _squish | def _squish(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5):
"Squish image by `scale`. `row_pct`,`col_pct` select focal point of zoom."
if scale <= 1:
col_c = (1-scale) * (2*col_pct - 1)
return _get_zoom_mat(scale, 1, col_c, 0.)
else:
row_c = (1-1/scale) * (2*row_pct - 1... | python | def _squish(scale:uniform=1.0, row_pct:uniform=0.5, col_pct:uniform=0.5):
"Squish image by `scale`. `row_pct`,`col_pct` select focal point of zoom."
if scale <= 1:
col_c = (1-scale) * (2*col_pct - 1)
return _get_zoom_mat(scale, 1, col_c, 0.)
else:
row_c = (1-1/scale) * (2*row_pct - 1... | [
"def",
"_squish",
"(",
"scale",
":",
"uniform",
"=",
"1.0",
",",
"row_pct",
":",
"uniform",
"=",
"0.5",
",",
"col_pct",
":",
"uniform",
"=",
"0.5",
")",
":",
"if",
"scale",
"<=",
"1",
":",
"col_c",
"=",
"(",
"1",
"-",
"scale",
")",
"*",
"(",
"2... | Squish image by `scale`. `row_pct`,`col_pct` select focal point of zoom. | [
"Squish",
"image",
"by",
"scale",
".",
"row_pct",
"col_pct",
"select",
"focal",
"point",
"of",
"zoom",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L47-L54 |
20,979 | fastai/fastai | fastai/vision/transform.py | _jitter | def _jitter(c, magnitude:uniform):
"Replace pixels by random neighbors at `magnitude`."
c.flow.add_((torch.rand_like(c.flow)-0.5)*magnitude*2)
return c | python | def _jitter(c, magnitude:uniform):
"Replace pixels by random neighbors at `magnitude`."
c.flow.add_((torch.rand_like(c.flow)-0.5)*magnitude*2)
return c | [
"def",
"_jitter",
"(",
"c",
",",
"magnitude",
":",
"uniform",
")",
":",
"c",
".",
"flow",
".",
"add_",
"(",
"(",
"torch",
".",
"rand_like",
"(",
"c",
".",
"flow",
")",
"-",
"0.5",
")",
"*",
"magnitude",
"*",
"2",
")",
"return",
"c"
] | Replace pixels by random neighbors at `magnitude`. | [
"Replace",
"pixels",
"by",
"random",
"neighbors",
"at",
"magnitude",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L57-L60 |
20,980 | fastai/fastai | fastai/vision/transform.py | _flip_lr | def _flip_lr(x):
"Flip `x` horizontally."
#return x.flip(2)
if isinstance(x, ImagePoints):
x.flow.flow[...,0] *= -1
return x
return tensor(np.ascontiguousarray(np.array(x)[...,::-1])) | python | def _flip_lr(x):
"Flip `x` horizontally."
#return x.flip(2)
if isinstance(x, ImagePoints):
x.flow.flow[...,0] *= -1
return x
return tensor(np.ascontiguousarray(np.array(x)[...,::-1])) | [
"def",
"_flip_lr",
"(",
"x",
")",
":",
"#return x.flip(2)",
"if",
"isinstance",
"(",
"x",
",",
"ImagePoints",
")",
":",
"x",
".",
"flow",
".",
"flow",
"[",
"...",
",",
"0",
"]",
"*=",
"-",
"1",
"return",
"x",
"return",
"tensor",
"(",
"np",
".",
"... | Flip `x` horizontally. | [
"Flip",
"x",
"horizontally",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L63-L69 |
20,981 | fastai/fastai | fastai/vision/transform.py | _cutout | def _cutout(x, n_holes:uniform_int=1, length:uniform_int=40):
"Cut out `n_holes` number of square holes of size `length` in image at random locations."
h,w = x.shape[1:]
for n in range(n_holes):
h_y = np.random.randint(0, h)
h_x = np.random.randint(0, w)
y1 = int(np.clip(h_y - length... | python | def _cutout(x, n_holes:uniform_int=1, length:uniform_int=40):
"Cut out `n_holes` number of square holes of size `length` in image at random locations."
h,w = x.shape[1:]
for n in range(n_holes):
h_y = np.random.randint(0, h)
h_x = np.random.randint(0, w)
y1 = int(np.clip(h_y - length... | [
"def",
"_cutout",
"(",
"x",
",",
"n_holes",
":",
"uniform_int",
"=",
"1",
",",
"length",
":",
"uniform_int",
"=",
"40",
")",
":",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"[",
"1",
":",
"]",
"for",
"n",
"in",
"range",
"(",
"n_holes",
")",
":",
... | Cut out `n_holes` number of square holes of size `length` in image at random locations. | [
"Cut",
"out",
"n_holes",
"number",
"of",
"square",
"holes",
"of",
"size",
"length",
"in",
"image",
"at",
"random",
"locations",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L122-L133 |
20,982 | fastai/fastai | fastai/vision/transform.py | _rgb_randomize | def _rgb_randomize(x, channel:int=None, thresh:float=0.3):
"Randomize one of the channels of the input image"
if channel is None: channel = np.random.randint(0, x.shape[0] - 1)
x[channel] = torch.rand(x.shape[1:]) * np.random.uniform(0, thresh)
return x | python | def _rgb_randomize(x, channel:int=None, thresh:float=0.3):
"Randomize one of the channels of the input image"
if channel is None: channel = np.random.randint(0, x.shape[0] - 1)
x[channel] = torch.rand(x.shape[1:]) * np.random.uniform(0, thresh)
return x | [
"def",
"_rgb_randomize",
"(",
"x",
",",
"channel",
":",
"int",
"=",
"None",
",",
"thresh",
":",
"float",
"=",
"0.3",
")",
":",
"if",
"channel",
"is",
"None",
":",
"channel",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"x",
".",
"shap... | Randomize one of the channels of the input image | [
"Randomize",
"one",
"of",
"the",
"channels",
"of",
"the",
"input",
"image"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L137-L141 |
20,983 | fastai/fastai | fastai/vision/transform.py | _crop_default | def _crop_default(x, size, row_pct:uniform=0.5, col_pct:uniform=0.5):
"Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop."
rows,cols = tis2hw(size)
row_pct,col_pct = _minus_epsilon(row_pct,col_pct)
row = int((x.size(1)-rows+1) * row_pct)
col = int((x.size(2)-cols+1) * col_pct... | python | def _crop_default(x, size, row_pct:uniform=0.5, col_pct:uniform=0.5):
"Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop."
rows,cols = tis2hw(size)
row_pct,col_pct = _minus_epsilon(row_pct,col_pct)
row = int((x.size(1)-rows+1) * row_pct)
col = int((x.size(2)-cols+1) * col_pct... | [
"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",
"... | Crop `x` to `size` pixels. `row_pct`,`col_pct` select focal point of crop. | [
"Crop",
"x",
"to",
"size",
"pixels",
".",
"row_pct",
"col_pct",
"select",
"focal",
"point",
"of",
"crop",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L150-L156 |
20,984 | fastai/fastai | fastai/vision/transform.py | _crop_pad_default | def _crop_pad_default(x, size, padding_mode='reflection', row_pct:uniform = 0.5, col_pct:uniform = 0.5):
"Crop and pad tfm - `row_pct`,`col_pct` sets focal point."
padding_mode = _pad_mode_convert[padding_mode]
size = tis2hw(size)
if x.shape[1:] == torch.Size(size): return x
rows,cols = size
row... | python | def _crop_pad_default(x, size, padding_mode='reflection', row_pct:uniform = 0.5, col_pct:uniform = 0.5):
"Crop and pad tfm - `row_pct`,`col_pct` sets focal point."
padding_mode = _pad_mode_convert[padding_mode]
size = tis2hw(size)
if x.shape[1:] == torch.Size(size): return x
rows,cols = size
row... | [
"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",
"]",... | Crop and pad tfm - `row_pct`,`col_pct` sets focal point. | [
"Crop",
"and",
"pad",
"tfm",
"-",
"row_pct",
"col_pct",
"sets",
"focal",
"point",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L175-L189 |
20,985 | fastai/fastai | fastai/vision/transform.py | rand_pad | def rand_pad(padding:int, size:int, mode:str='reflection'):
"Fixed `mode` `padding` and random crop of `size`"
return [pad(padding=padding,mode=mode),
crop(size=size, **rand_pos)] | python | def rand_pad(padding:int, size:int, mode:str='reflection'):
"Fixed `mode` `padding` and random crop of `size`"
return [pad(padding=padding,mode=mode),
crop(size=size, **rand_pos)] | [
"def",
"rand_pad",
"(",
"padding",
":",
"int",
",",
"size",
":",
"int",
",",
"mode",
":",
"str",
"=",
"'reflection'",
")",
":",
"return",
"[",
"pad",
"(",
"padding",
"=",
"padding",
",",
"mode",
"=",
"mode",
")",
",",
"crop",
"(",
"size",
"=",
"s... | Fixed `mode` `padding` and random crop of `size` | [
"Fixed",
"mode",
"padding",
"and",
"random",
"crop",
"of",
"size"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L213-L216 |
20,986 | fastai/fastai | fastai/vision/transform.py | rand_zoom | def rand_zoom(scale:uniform=1.0, p:float=1.):
"Randomized version of `zoom`."
return zoom(scale=scale, **rand_pos, p=p) | python | def rand_zoom(scale:uniform=1.0, p:float=1.):
"Randomized version of `zoom`."
return zoom(scale=scale, **rand_pos, p=p) | [
"def",
"rand_zoom",
"(",
"scale",
":",
"uniform",
"=",
"1.0",
",",
"p",
":",
"float",
"=",
"1.",
")",
":",
"return",
"zoom",
"(",
"scale",
"=",
"scale",
",",
"*",
"*",
"rand_pos",
",",
"p",
"=",
"p",
")"
] | Randomized version of `zoom`. | [
"Randomized",
"version",
"of",
"zoom",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L218-L220 |
20,987 | fastai/fastai | fastai/vision/transform.py | rand_crop | def rand_crop(*args, padding_mode='reflection', p:float=1.):
"Randomized version of `crop_pad`."
return crop_pad(*args, **rand_pos, padding_mode=padding_mode, p=p) | python | def rand_crop(*args, padding_mode='reflection', p:float=1.):
"Randomized version of `crop_pad`."
return crop_pad(*args, **rand_pos, padding_mode=padding_mode, p=p) | [
"def",
"rand_crop",
"(",
"*",
"args",
",",
"padding_mode",
"=",
"'reflection'",
",",
"p",
":",
"float",
"=",
"1.",
")",
":",
"return",
"crop_pad",
"(",
"*",
"args",
",",
"*",
"*",
"rand_pos",
",",
"padding_mode",
"=",
"padding_mode",
",",
"p",
"=",
"... | Randomized version of `crop_pad`. | [
"Randomized",
"version",
"of",
"crop_pad",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L222-L224 |
20,988 | fastai/fastai | fastai/vision/transform.py | _apply_perspective | def _apply_perspective(coords:FlowField, coeffs:Points)->FlowField:
"Transform `coords` with `coeffs`."
size = coords.flow.size()
#compress all the dims expect the last one ang adds ones, coords become N * 3
coords.flow = coords.flow.view(-1,2)
#Transform the coeffs in a 3*3 matrix with a 1 at the b... | python | def _apply_perspective(coords:FlowField, coeffs:Points)->FlowField:
"Transform `coords` with `coeffs`."
size = coords.flow.size()
#compress all the dims expect the last one ang adds ones, coords become N * 3
coords.flow = coords.flow.view(-1,2)
#Transform the coeffs in a 3*3 matrix with a 1 at the b... | [
"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... | Transform `coords` with `coeffs`. | [
"Transform",
"coords",
"with",
"coeffs",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L248-L258 |
20,989 | fastai/fastai | fastai/vision/transform.py | _do_perspective_warp | def _do_perspective_warp(c:FlowField, targ_pts:Points, invert=False):
"Apply warp to `targ_pts` from `_orig_pts` to `c` `FlowField`."
if invert: return _apply_perspective(c, _find_coeffs(targ_pts, _orig_pts))
return _apply_perspective(c, _find_coeffs(_orig_pts, targ_pts)) | python | def _do_perspective_warp(c:FlowField, targ_pts:Points, invert=False):
"Apply warp to `targ_pts` from `_orig_pts` to `c` `FlowField`."
if invert: return _apply_perspective(c, _find_coeffs(targ_pts, _orig_pts))
return _apply_perspective(c, _find_coeffs(_orig_pts, targ_pts)) | [
"def",
"_do_perspective_warp",
"(",
"c",
":",
"FlowField",
",",
"targ_pts",
":",
"Points",
",",
"invert",
"=",
"False",
")",
":",
"if",
"invert",
":",
"return",
"_apply_perspective",
"(",
"c",
",",
"_find_coeffs",
"(",
"targ_pts",
",",
"_orig_pts",
")",
")... | Apply warp to `targ_pts` from `_orig_pts` to `c` `FlowField`. | [
"Apply",
"warp",
"to",
"targ_pts",
"from",
"_orig_pts",
"to",
"c",
"FlowField",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L262-L265 |
20,990 | fastai/fastai | fastai/vision/transform.py | _perspective_warp | def _perspective_warp(c, magnitude:partial(uniform,size=8)=0, invert=False):
"Apply warp of `magnitude` to `c`."
magnitude = magnitude.view(4,2)
targ_pts = [[x+m for x,m in zip(xs, ms)] for xs, ms in zip(_orig_pts, magnitude)]
return _do_perspective_warp(c, targ_pts, invert) | python | def _perspective_warp(c, magnitude:partial(uniform,size=8)=0, invert=False):
"Apply warp of `magnitude` to `c`."
magnitude = magnitude.view(4,2)
targ_pts = [[x+m for x,m in zip(xs, ms)] for xs, ms in zip(_orig_pts, magnitude)]
return _do_perspective_warp(c, targ_pts, invert) | [
"def",
"_perspective_warp",
"(",
"c",
",",
"magnitude",
":",
"partial",
"(",
"uniform",
",",
"size",
"=",
"8",
")",
"=",
"0",
",",
"invert",
"=",
"False",
")",
":",
"magnitude",
"=",
"magnitude",
".",
"view",
"(",
"4",
",",
"2",
")",
"targ_pts",
"=... | Apply warp of `magnitude` to `c`. | [
"Apply",
"warp",
"of",
"magnitude",
"to",
"c",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L267-L271 |
20,991 | fastai/fastai | fastai/vision/transform.py | _symmetric_warp | def _symmetric_warp(c, magnitude:partial(uniform,size=4)=0, invert=False):
"Apply symmetric warp of `magnitude` to `c`."
m = listify(magnitude, 4)
targ_pts = [[-1-m[3],-1-m[1]], [-1-m[2],1+m[1]], [1+m[3],-1-m[0]], [1+m[2],1+m[0]]]
return _do_perspective_warp(c, targ_pts, invert) | python | def _symmetric_warp(c, magnitude:partial(uniform,size=4)=0, invert=False):
"Apply symmetric warp of `magnitude` to `c`."
m = listify(magnitude, 4)
targ_pts = [[-1-m[3],-1-m[1]], [-1-m[2],1+m[1]], [1+m[3],-1-m[0]], [1+m[2],1+m[0]]]
return _do_perspective_warp(c, targ_pts, invert) | [
"def",
"_symmetric_warp",
"(",
"c",
",",
"magnitude",
":",
"partial",
"(",
"uniform",
",",
"size",
"=",
"4",
")",
"=",
"0",
",",
"invert",
"=",
"False",
")",
":",
"m",
"=",
"listify",
"(",
"magnitude",
",",
"4",
")",
"targ_pts",
"=",
"[",
"[",
"-... | Apply symmetric warp of `magnitude` to `c`. | [
"Apply",
"symmetric",
"warp",
"of",
"magnitude",
"to",
"c",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L274-L278 |
20,992 | fastai/fastai | fastai/vision/transform.py | _tilt | def _tilt(c, direction:uniform_int, magnitude:uniform=0, invert=False):
"Tilt `c` field with random `direction` and `magnitude`."
orig_pts = [[-1,-1], [-1,1], [1,-1], [1,1]]
if direction == 0: targ_pts = [[-1,-1], [-1,1], [1,-1-magnitude], [1,1+magnitude]]
elif direction == 1: targ_pts = [[-1,-1-magni... | python | def _tilt(c, direction:uniform_int, magnitude:uniform=0, invert=False):
"Tilt `c` field with random `direction` and `magnitude`."
orig_pts = [[-1,-1], [-1,1], [1,-1], [1,1]]
if direction == 0: targ_pts = [[-1,-1], [-1,1], [1,-1-magnitude], [1,1+magnitude]]
elif direction == 1: targ_pts = [[-1,-1-magni... | [
"def",
"_tilt",
"(",
"c",
",",
"direction",
":",
"uniform_int",
",",
"magnitude",
":",
"uniform",
"=",
"0",
",",
"invert",
"=",
"False",
")",
":",
"orig_pts",
"=",
"[",
"[",
"-",
"1",
",",
"-",
"1",
"]",
",",
"[",
"-",
"1",
",",
"1",
"]",
","... | Tilt `c` field with random `direction` and `magnitude`. | [
"Tilt",
"c",
"field",
"with",
"random",
"direction",
"and",
"magnitude",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L281-L289 |
20,993 | fastai/fastai | fastai/vision/transform.py | get_transforms | def get_transforms(do_flip:bool=True, flip_vert:bool=False, max_rotate:float=10., max_zoom:float=1.1,
max_lighting:float=0.2, max_warp:float=0.2, p_affine:float=0.75,
p_lighting:float=0.75, xtra_tfms:Optional[Collection[Transform]]=None)->Collection[Transform]:
"Utility func to... | python | def get_transforms(do_flip:bool=True, flip_vert:bool=False, max_rotate:float=10., max_zoom:float=1.1,
max_lighting:float=0.2, max_warp:float=0.2, p_affine:float=0.75,
p_lighting:float=0.75, xtra_tfms:Optional[Collection[Transform]]=None)->Collection[Transform]:
"Utility func to... | [
"def",
"get_transforms",
"(",
"do_flip",
":",
"bool",
"=",
"True",
",",
"flip_vert",
":",
"bool",
"=",
"False",
",",
"max_rotate",
":",
"float",
"=",
"10.",
",",
"max_zoom",
":",
"float",
"=",
"1.1",
",",
"max_lighting",
":",
"float",
"=",
"0.2",
",",
... | Utility func to easily create a list of flip, rotate, `zoom`, warp, lighting transforms. | [
"Utility",
"func",
"to",
"easily",
"create",
"a",
"list",
"of",
"flip",
"rotate",
"zoom",
"warp",
"lighting",
"transforms",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L307-L320 |
20,994 | fastai/fastai | old/fastai/learner.py | Learner.get_layer_opt | def get_layer_opt(self, lrs, wds):
"""Method returns an instance of the LayerOptimizer class, which
allows for setting differential learning rates for different
parts of the model.
An example of how a model maybe differentiated into different parts
for application of differenti... | python | def get_layer_opt(self, lrs, wds):
"""Method returns an instance of the LayerOptimizer class, which
allows for setting differential learning rates for different
parts of the model.
An example of how a model maybe differentiated into different parts
for application of differenti... | [
"def",
"get_layer_opt",
"(",
"self",
",",
"lrs",
",",
"wds",
")",
":",
"return",
"LayerOptimizer",
"(",
"self",
".",
"opt_fn",
",",
"self",
".",
"get_layer_groups",
"(",
")",
",",
"lrs",
",",
"wds",
")"
] | Method returns an instance of the LayerOptimizer class, which
allows for setting differential learning rates for different
parts of the model.
An example of how a model maybe differentiated into different parts
for application of differential learning rates and weight decays is
... | [
"Method",
"returns",
"an",
"instance",
"of",
"the",
"LayerOptimizer",
"class",
"which",
"allows",
"for",
"setting",
"differential",
"learning",
"rates",
"for",
"different",
"parts",
"of",
"the",
"model",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L253-L273 |
20,995 | fastai/fastai | old/fastai/learner.py | Learner.lr_find | def lr_find(self, start_lr=1e-5, end_lr=10, wds=None, linear=False, **kwargs):
"""Helps you find an optimal learning rate for a model.
It uses the technique developed in the 2015 paper
`Cyclical Learning Rates for Training Neural Networks`, where
we simply keep increasing the learnin... | python | def lr_find(self, start_lr=1e-5, end_lr=10, wds=None, linear=False, **kwargs):
"""Helps you find an optimal learning rate for a model.
It uses the technique developed in the 2015 paper
`Cyclical Learning Rates for Training Neural Networks`, where
we simply keep increasing the learnin... | [
"def",
"lr_find",
"(",
"self",
",",
"start_lr",
"=",
"1e-5",
",",
"end_lr",
"=",
"10",
",",
"wds",
"=",
"None",
",",
"linear",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"save",
"(",
"'tmp'",
")",
"layer_opt",
"=",
"self",
".",... | Helps you find an optimal learning rate for a model.
It uses the technique developed in the 2015 paper
`Cyclical Learning Rates for Training Neural Networks`, where
we simply keep increasing the learning rate from a very small value,
until the loss starts decreasing.
Args:
... | [
"Helps",
"you",
"find",
"an",
"optimal",
"learning",
"rate",
"for",
"a",
"model",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/learner.py#L309-L346 |
20,996 | fastai/fastai | fastai/callbacks/rnn.py | RNNTrainer.on_loss_begin | def on_loss_begin(self, last_output:Tuple[Tensor,Tensor,Tensor], **kwargs):
"Save the extra outputs for later and only returns the true output."
self.raw_out,self.out = last_output[1],last_output[2]
return {'last_output': last_output[0]} | python | def on_loss_begin(self, last_output:Tuple[Tensor,Tensor,Tensor], **kwargs):
"Save the extra outputs for later and only returns the true output."
self.raw_out,self.out = last_output[1],last_output[2]
return {'last_output': last_output[0]} | [
"def",
"on_loss_begin",
"(",
"self",
",",
"last_output",
":",
"Tuple",
"[",
"Tensor",
",",
"Tensor",
",",
"Tensor",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"raw_out",
",",
"self",
".",
"out",
"=",
"last_output",
"[",
"1",
"]",
",",
"la... | Save the extra outputs for later and only returns the true output. | [
"Save",
"the",
"extra",
"outputs",
"for",
"later",
"and",
"only",
"returns",
"the",
"true",
"output",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/rnn.py#L19-L22 |
20,997 | fastai/fastai | fastai/callbacks/rnn.py | RNNTrainer.on_backward_begin | def on_backward_begin(self, last_loss:Rank0Tensor, last_input:Tensor, **kwargs):
"Apply AR and TAR to `last_loss`."
#AR and TAR
if self.alpha != 0.: last_loss += self.alpha * self.out[-1].float().pow(2).mean()
if self.beta != 0.:
h = self.raw_out[-1]
if len(h)>1:... | python | def on_backward_begin(self, last_loss:Rank0Tensor, last_input:Tensor, **kwargs):
"Apply AR and TAR to `last_loss`."
#AR and TAR
if self.alpha != 0.: last_loss += self.alpha * self.out[-1].float().pow(2).mean()
if self.beta != 0.:
h = self.raw_out[-1]
if len(h)>1:... | [
"def",
"on_backward_begin",
"(",
"self",
",",
"last_loss",
":",
"Rank0Tensor",
",",
"last_input",
":",
"Tensor",
",",
"*",
"*",
"kwargs",
")",
":",
"#AR and TAR",
"if",
"self",
".",
"alpha",
"!=",
"0.",
":",
"last_loss",
"+=",
"self",
".",
"alpha",
"*",
... | Apply AR and TAR to `last_loss`. | [
"Apply",
"AR",
"and",
"TAR",
"to",
"last_loss",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/rnn.py#L24-L31 |
20,998 | fastai/fastai | fastai/text/learner.py | convert_weights | def convert_weights(wgts:Weights, stoi_wgts:Dict[str,int], itos_new:Collection[str]) -> Weights:
"Convert the model `wgts` to go with a new vocabulary."
dec_bias, enc_wgts = wgts.get('1.decoder.bias', None), wgts['0.encoder.weight']
wgts_m = enc_wgts.mean(0)
if dec_bias is not None: bias_m = dec_bias.me... | python | def convert_weights(wgts:Weights, stoi_wgts:Dict[str,int], itos_new:Collection[str]) -> Weights:
"Convert the model `wgts` to go with a new vocabulary."
dec_bias, enc_wgts = wgts.get('1.decoder.bias', None), wgts['0.encoder.weight']
wgts_m = enc_wgts.mean(0)
if dec_bias is not None: bias_m = dec_bias.me... | [
"def",
"convert_weights",
"(",
"wgts",
":",
"Weights",
",",
"stoi_wgts",
":",
"Dict",
"[",
"str",
",",
"int",
"]",
",",
"itos_new",
":",
"Collection",
"[",
"str",
"]",
")",
"->",
"Weights",
":",
"dec_bias",
",",
"enc_wgts",
"=",
"wgts",
".",
"get",
"... | Convert the model `wgts` to go with a new vocabulary. | [
"Convert",
"the",
"model",
"wgts",
"to",
"go",
"with",
"a",
"new",
"vocabulary",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L28-L43 |
20,999 | fastai/fastai | fastai/text/learner.py | get_language_model | def get_language_model(arch:Callable, vocab_sz:int, config:dict=None, drop_mult:float=1.):
"Create a language model from `arch` and its `config`, maybe `pretrained`."
meta = _model_meta[arch]
config = ifnone(config, meta['config_lm'].copy())
for k in config.keys():
if k.endswith('_p'): config[k... | python | def get_language_model(arch:Callable, vocab_sz:int, config:dict=None, drop_mult:float=1.):
"Create a language model from `arch` and its `config`, maybe `pretrained`."
meta = _model_meta[arch]
config = ifnone(config, meta['config_lm'].copy())
for k in config.keys():
if k.endswith('_p'): config[k... | [
"def",
"get_language_model",
"(",
"arch",
":",
"Callable",
",",
"vocab_sz",
":",
"int",
",",
"config",
":",
"dict",
"=",
"None",
",",
"drop_mult",
":",
"float",
"=",
"1.",
")",
":",
"meta",
"=",
"_model_meta",
"[",
"arch",
"]",
"config",
"=",
"ifnone",... | Create a language model from `arch` and its `config`, maybe `pretrained`. | [
"Create",
"a",
"language",
"model",
"from",
"arch",
"and",
"its",
"config",
"maybe",
"pretrained",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L187-L199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.