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