id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
21,000 | fastai/fastai | fastai/text/learner.py | language_model_learner | def language_model_learner(data:DataBunch, arch, config:dict=None, drop_mult:float=1., pretrained:bool=True,
pretrained_fnames:OptStrTuple=None, **learn_kwargs) -> 'LanguageLearner':
"Create a `Learner` with a language model from `data` and `arch`."
model = get_language_model(arch, le... | python | def language_model_learner(data:DataBunch, arch, config:dict=None, drop_mult:float=1., pretrained:bool=True,
pretrained_fnames:OptStrTuple=None, **learn_kwargs) -> 'LanguageLearner':
"Create a `Learner` with a language model from `data` and `arch`."
model = get_language_model(arch, le... | [
"def",
"language_model_learner",
"(",
"data",
":",
"DataBunch",
",",
"arch",
",",
"config",
":",
"dict",
"=",
"None",
",",
"drop_mult",
":",
"float",
"=",
"1.",
",",
"pretrained",
":",
"bool",
"=",
"True",
",",
"pretrained_fnames",
":",
"OptStrTuple",
"=",... | Create a `Learner` with a language model from `data` and `arch`. | [
"Create",
"a",
"Learner",
"with",
"a",
"language",
"model",
"from",
"data",
"and",
"arch",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L201-L219 |
21,001 | fastai/fastai | fastai/text/learner.py | get_text_classifier | def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None,
drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None,
pad_idx:int=1) -> nn.Module:
"Create a text classifier from `arch` and it... | python | def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None,
drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None,
pad_idx:int=1) -> nn.Module:
"Create a text classifier from `arch` and it... | [
"def",
"get_text_classifier",
"(",
"arch",
":",
"Callable",
",",
"vocab_sz",
":",
"int",
",",
"n_class",
":",
"int",
",",
"bptt",
":",
"int",
"=",
"70",
",",
"max_len",
":",
"int",
"=",
"20",
"*",
"70",
",",
"config",
":",
"dict",
"=",
"None",
",",... | Create a text classifier from `arch` and its `config`, maybe `pretrained`. | [
"Create",
"a",
"text",
"classifier",
"from",
"arch",
"and",
"its",
"config",
"maybe",
"pretrained",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L269-L284 |
21,002 | fastai/fastai | fastai/text/learner.py | text_classifier_learner | def text_classifier_learner(data:DataBunch, arch:Callable, bptt:int=70, max_len:int=70*20, config:dict=None,
pretrained:bool=True, drop_mult:float=1., lin_ftrs:Collection[int]=None,
ps:Collection[float]=None, **learn_kwargs) -> 'TextClassifierLearner':
"Crea... | python | def text_classifier_learner(data:DataBunch, arch:Callable, bptt:int=70, max_len:int=70*20, config:dict=None,
pretrained:bool=True, drop_mult:float=1., lin_ftrs:Collection[int]=None,
ps:Collection[float]=None, **learn_kwargs) -> 'TextClassifierLearner':
"Crea... | [
"def",
"text_classifier_learner",
"(",
"data",
":",
"DataBunch",
",",
"arch",
":",
"Callable",
",",
"bptt",
":",
"int",
"=",
"70",
",",
"max_len",
":",
"int",
"=",
"70",
"*",
"20",
",",
"config",
":",
"dict",
"=",
"None",
",",
"pretrained",
":",
"boo... | Create a `Learner` with a text classifier from `data` and `arch`. | [
"Create",
"a",
"Learner",
"with",
"a",
"text",
"classifier",
"from",
"data",
"and",
"arch",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L286-L302 |
21,003 | fastai/fastai | fastai/text/learner.py | RNNLearner.save_encoder | def save_encoder(self, name:str):
"Save the encoder to `name` inside the model directory."
encoder = get_model(self.model)[0]
if hasattr(encoder, 'module'): encoder = encoder.module
torch.save(encoder.state_dict(), self.path/self.model_dir/f'{name}.pth') | python | def save_encoder(self, name:str):
"Save the encoder to `name` inside the model directory."
encoder = get_model(self.model)[0]
if hasattr(encoder, 'module'): encoder = encoder.module
torch.save(encoder.state_dict(), self.path/self.model_dir/f'{name}.pth') | [
"def",
"save_encoder",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"encoder",
"=",
"get_model",
"(",
"self",
".",
"model",
")",
"[",
"0",
"]",
"if",
"hasattr",
"(",
"encoder",
",",
"'module'",
")",
":",
"encoder",
"=",
"encoder",
".",
"module",
... | Save the encoder to `name` inside the model directory. | [
"Save",
"the",
"encoder",
"to",
"name",
"inside",
"the",
"model",
"directory",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L57-L61 |
21,004 | fastai/fastai | fastai/text/learner.py | RNNLearner.load_encoder | def load_encoder(self, name:str, device:torch.device=None):
"Load the encoder `name` from the model directory."
encoder = get_model(self.model)[0]
if device is None: device = self.data.device
if hasattr(encoder, 'module'): encoder = encoder.module
encoder.load_state_dict(torch.lo... | python | def load_encoder(self, name:str, device:torch.device=None):
"Load the encoder `name` from the model directory."
encoder = get_model(self.model)[0]
if device is None: device = self.data.device
if hasattr(encoder, 'module'): encoder = encoder.module
encoder.load_state_dict(torch.lo... | [
"def",
"load_encoder",
"(",
"self",
",",
"name",
":",
"str",
",",
"device",
":",
"torch",
".",
"device",
"=",
"None",
")",
":",
"encoder",
"=",
"get_model",
"(",
"self",
".",
"model",
")",
"[",
"0",
"]",
"if",
"device",
"is",
"None",
":",
"device",... | Load the encoder `name` from the model directory. | [
"Load",
"the",
"encoder",
"name",
"from",
"the",
"model",
"directory",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L63-L70 |
21,005 | fastai/fastai | fastai/text/learner.py | RNNLearner.load_pretrained | def load_pretrained(self, wgts_fname:str, itos_fname:str, strict:bool=True):
"Load a pretrained model and adapts it to the data vocabulary."
old_itos = pickle.load(open(itos_fname, 'rb'))
old_stoi = {v:k for k,v in enumerate(old_itos)}
wgts = torch.load(wgts_fname, map_location=lambda st... | python | def load_pretrained(self, wgts_fname:str, itos_fname:str, strict:bool=True):
"Load a pretrained model and adapts it to the data vocabulary."
old_itos = pickle.load(open(itos_fname, 'rb'))
old_stoi = {v:k for k,v in enumerate(old_itos)}
wgts = torch.load(wgts_fname, map_location=lambda st... | [
"def",
"load_pretrained",
"(",
"self",
",",
"wgts_fname",
":",
"str",
",",
"itos_fname",
":",
"str",
",",
"strict",
":",
"bool",
"=",
"True",
")",
":",
"old_itos",
"=",
"pickle",
".",
"load",
"(",
"open",
"(",
"itos_fname",
",",
"'rb'",
")",
")",
"ol... | Load a pretrained model and adapts it to the data vocabulary. | [
"Load",
"a",
"pretrained",
"model",
"and",
"adapts",
"it",
"to",
"the",
"data",
"vocabulary",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L72-L79 |
21,006 | fastai/fastai | fastai/text/learner.py | RNNLearner.get_preds | def get_preds(self, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False, n_batch:Optional[int]=None, pbar:Optional[PBar]=None,
ordered:bool=False) -> List[Tensor]:
"Return predictions and targets on the valid, train, or test set, depending on `ds_type`."
self.model.reset()
... | python | def get_preds(self, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False, n_batch:Optional[int]=None, pbar:Optional[PBar]=None,
ordered:bool=False) -> List[Tensor]:
"Return predictions and targets on the valid, train, or test set, depending on `ds_type`."
self.model.reset()
... | [
"def",
"get_preds",
"(",
"self",
",",
"ds_type",
":",
"DatasetType",
"=",
"DatasetType",
".",
"Valid",
",",
"with_loss",
":",
"bool",
"=",
"False",
",",
"n_batch",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"pbar",
":",
"Optional",
"[",
"PBar"... | Return predictions and targets on the valid, train, or test set, depending on `ds_type`. | [
"Return",
"predictions",
"and",
"targets",
"on",
"the",
"valid",
"train",
"or",
"test",
"set",
"depending",
"on",
"ds_type",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L81-L92 |
21,007 | fastai/fastai | fastai/text/learner.py | LanguageLearner.predict | def predict(self, text:str, n_words:int=1, no_unk:bool=True, temperature:float=1., min_p:float=None, sep:str=' ',
decoder=decode_spec_tokens):
"Return the `n_words` that come after `text`."
ds = self.data.single_dl.dataset
self.model.reset()
xb,yb = self.data.one_item(tex... | python | def predict(self, text:str, n_words:int=1, no_unk:bool=True, temperature:float=1., min_p:float=None, sep:str=' ',
decoder=decode_spec_tokens):
"Return the `n_words` that come after `text`."
ds = self.data.single_dl.dataset
self.model.reset()
xb,yb = self.data.one_item(tex... | [
"def",
"predict",
"(",
"self",
",",
"text",
":",
"str",
",",
"n_words",
":",
"int",
"=",
"1",
",",
"no_unk",
":",
"bool",
"=",
"True",
",",
"temperature",
":",
"float",
"=",
"1.",
",",
"min_p",
":",
"float",
"=",
"None",
",",
"sep",
":",
"str",
... | Return the `n_words` that come after `text`. | [
"Return",
"the",
"n_words",
"that",
"come",
"after",
"text",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L116-L135 |
21,008 | fastai/fastai | fastai/text/learner.py | LanguageLearner.beam_search | def beam_search(self, text:str, n_words:int, no_unk:bool=True, top_k:int=10, beam_sz:int=1000, temperature:float=1.,
sep:str=' ', decoder=decode_spec_tokens):
"Return the `n_words` that come after `text` using beam search."
ds = self.data.single_dl.dataset
self.model.reset()
... | python | def beam_search(self, text:str, n_words:int, no_unk:bool=True, top_k:int=10, beam_sz:int=1000, temperature:float=1.,
sep:str=' ', decoder=decode_spec_tokens):
"Return the `n_words` that come after `text` using beam search."
ds = self.data.single_dl.dataset
self.model.reset()
... | [
"def",
"beam_search",
"(",
"self",
",",
"text",
":",
"str",
",",
"n_words",
":",
"int",
",",
"no_unk",
":",
"bool",
"=",
"True",
",",
"top_k",
":",
"int",
"=",
"10",
",",
"beam_sz",
":",
"int",
"=",
"1000",
",",
"temperature",
":",
"float",
"=",
... | Return the `n_words` that come after `text` using beam search. | [
"Return",
"the",
"n_words",
"that",
"come",
"after",
"text",
"using",
"beam",
"search",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L137-L163 |
21,009 | fastai/fastai | fastai/text/learner.py | LanguageLearner.show_results | def show_results(self, ds_type=DatasetType.Valid, rows:int=5, max_len:int=20):
from IPython.display import display, HTML
"Show `rows` result of predictions on `ds_type` dataset."
ds = self.dl(ds_type).dataset
x,y = self.data.one_batch(ds_type, detach=False, denorm=False)
preds = ... | python | def show_results(self, ds_type=DatasetType.Valid, rows:int=5, max_len:int=20):
from IPython.display import display, HTML
"Show `rows` result of predictions on `ds_type` dataset."
ds = self.dl(ds_type).dataset
x,y = self.data.one_batch(ds_type, detach=False, denorm=False)
preds = ... | [
"def",
"show_results",
"(",
"self",
",",
"ds_type",
"=",
"DatasetType",
".",
"Valid",
",",
"rows",
":",
"int",
"=",
"5",
",",
"max_len",
":",
"int",
"=",
"20",
")",
":",
"from",
"IPython",
".",
"display",
"import",
"display",
",",
"HTML",
"ds",
"=",
... | Show `rows` result of predictions on `ds_type` dataset. | [
"Show",
"rows",
"result",
"of",
"predictions",
"on",
"ds_type",
"dataset",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L165-L185 |
21,010 | fastai/fastai | fastai/text/learner.py | MultiBatchEncoder.concat | def concat(self, arrs:Collection[Tensor])->Tensor:
"Concatenate the `arrs` along the batch dimension."
return [torch.cat([l[si] for l in arrs], dim=1) for si in range_of(arrs[0])] | python | def concat(self, arrs:Collection[Tensor])->Tensor:
"Concatenate the `arrs` along the batch dimension."
return [torch.cat([l[si] for l in arrs], dim=1) for si in range_of(arrs[0])] | [
"def",
"concat",
"(",
"self",
",",
"arrs",
":",
"Collection",
"[",
"Tensor",
"]",
")",
"->",
"Tensor",
":",
"return",
"[",
"torch",
".",
"cat",
"(",
"[",
"l",
"[",
"si",
"]",
"for",
"l",
"in",
"arrs",
"]",
",",
"dim",
"=",
"1",
")",
"for",
"s... | Concatenate the `arrs` along the batch dimension. | [
"Concatenate",
"the",
"arrs",
"along",
"the",
"batch",
"dimension",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L250-L252 |
21,011 | fastai/fastai | fastai/layers.py | batchnorm_2d | def batchnorm_2d(nf:int, norm_type:NormType=NormType.Batch):
"A batchnorm2d layer with `nf` features initialized depending on `norm_type`."
bn = nn.BatchNorm2d(nf)
with torch.no_grad():
bn.bias.fill_(1e-3)
bn.weight.fill_(0. if norm_type==NormType.BatchZero else 1.)
return bn | python | def batchnorm_2d(nf:int, norm_type:NormType=NormType.Batch):
"A batchnorm2d layer with `nf` features initialized depending on `norm_type`."
bn = nn.BatchNorm2d(nf)
with torch.no_grad():
bn.bias.fill_(1e-3)
bn.weight.fill_(0. if norm_type==NormType.BatchZero else 1.)
return bn | [
"def",
"batchnorm_2d",
"(",
"nf",
":",
"int",
",",
"norm_type",
":",
"NormType",
"=",
"NormType",
".",
"Batch",
")",
":",
"bn",
"=",
"nn",
".",
"BatchNorm2d",
"(",
"nf",
")",
"with",
"torch",
".",
"no_grad",
"(",
")",
":",
"bn",
".",
"bias",
".",
... | A batchnorm2d layer with `nf` features initialized depending on `norm_type`. | [
"A",
"batchnorm2d",
"layer",
"with",
"nf",
"features",
"initialized",
"depending",
"on",
"norm_type",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L52-L58 |
21,012 | fastai/fastai | fastai/layers.py | conv1d | def conv1d(ni:int, no:int, ks:int=1, stride:int=1, padding:int=0, bias:bool=False):
"Create and initialize a `nn.Conv1d` layer with spectral normalization."
conv = nn.Conv1d(ni, no, ks, stride=stride, padding=padding, bias=bias)
nn.init.kaiming_normal_(conv.weight)
if bias: conv.bias.data.zero_()
re... | python | def conv1d(ni:int, no:int, ks:int=1, stride:int=1, padding:int=0, bias:bool=False):
"Create and initialize a `nn.Conv1d` layer with spectral normalization."
conv = nn.Conv1d(ni, no, ks, stride=stride, padding=padding, bias=bias)
nn.init.kaiming_normal_(conv.weight)
if bias: conv.bias.data.zero_()
re... | [
"def",
"conv1d",
"(",
"ni",
":",
"int",
",",
"no",
":",
"int",
",",
"ks",
":",
"int",
"=",
"1",
",",
"stride",
":",
"int",
"=",
"1",
",",
"padding",
":",
"int",
"=",
"0",
",",
"bias",
":",
"bool",
"=",
"False",
")",
":",
"conv",
"=",
"nn",
... | Create and initialize a `nn.Conv1d` layer with spectral normalization. | [
"Create",
"and",
"initialize",
"a",
"nn",
".",
"Conv1d",
"layer",
"with",
"spectral",
"normalization",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L68-L73 |
21,013 | fastai/fastai | fastai/layers.py | conv2d_trans | def conv2d_trans(ni:int, nf:int, ks:int=2, stride:int=2, padding:int=0, bias=False) -> nn.ConvTranspose2d:
"Create `nn.ConvTranspose2d` layer."
return nn.ConvTranspose2d(ni, nf, kernel_size=ks, stride=stride, padding=padding, bias=bias) | python | def conv2d_trans(ni:int, nf:int, ks:int=2, stride:int=2, padding:int=0, bias=False) -> nn.ConvTranspose2d:
"Create `nn.ConvTranspose2d` layer."
return nn.ConvTranspose2d(ni, nf, kernel_size=ks, stride=stride, padding=padding, bias=bias) | [
"def",
"conv2d_trans",
"(",
"ni",
":",
"int",
",",
"nf",
":",
"int",
",",
"ks",
":",
"int",
"=",
"2",
",",
"stride",
":",
"int",
"=",
"2",
",",
"padding",
":",
"int",
"=",
"0",
",",
"bias",
"=",
"False",
")",
"->",
"nn",
".",
"ConvTranspose2d",... | Create `nn.ConvTranspose2d` layer. | [
"Create",
"nn",
".",
"ConvTranspose2d",
"layer",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L120-L122 |
21,014 | fastai/fastai | fastai/layers.py | relu | def relu(inplace:bool=False, leaky:float=None):
"Return a relu activation, maybe `leaky` and `inplace`."
return nn.LeakyReLU(inplace=inplace, negative_slope=leaky) if leaky is not None else nn.ReLU(inplace=inplace) | python | def relu(inplace:bool=False, leaky:float=None):
"Return a relu activation, maybe `leaky` and `inplace`."
return nn.LeakyReLU(inplace=inplace, negative_slope=leaky) if leaky is not None else nn.ReLU(inplace=inplace) | [
"def",
"relu",
"(",
"inplace",
":",
"bool",
"=",
"False",
",",
"leaky",
":",
"float",
"=",
"None",
")",
":",
"return",
"nn",
".",
"LeakyReLU",
"(",
"inplace",
"=",
"inplace",
",",
"negative_slope",
"=",
"leaky",
")",
"if",
"leaky",
"is",
"not",
"None... | Return a relu activation, maybe `leaky` and `inplace`. | [
"Return",
"a",
"relu",
"activation",
"maybe",
"leaky",
"and",
"inplace",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L124-L126 |
21,015 | fastai/fastai | fastai/layers.py | res_block | def res_block(nf, dense:bool=False, norm_type:Optional[NormType]=NormType.Batch, bottle:bool=False, **conv_kwargs):
"Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`."
norm2 = norm_type
if not dense and (norm_type==NormType.Batch): norm2 = NormType.BatchZero
nf_inner = nf//2 if bo... | python | def res_block(nf, dense:bool=False, norm_type:Optional[NormType]=NormType.Batch, bottle:bool=False, **conv_kwargs):
"Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`."
norm2 = norm_type
if not dense and (norm_type==NormType.Batch): norm2 = NormType.BatchZero
nf_inner = nf//2 if bo... | [
"def",
"res_block",
"(",
"nf",
",",
"dense",
":",
"bool",
"=",
"False",
",",
"norm_type",
":",
"Optional",
"[",
"NormType",
"]",
"=",
"NormType",
".",
"Batch",
",",
"bottle",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"conv_kwargs",
")",
":",
"norm2",... | Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`. | [
"Resnet",
"block",
"of",
"nf",
"features",
".",
"conv_kwargs",
"are",
"passed",
"to",
"conv_layer",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L174-L181 |
21,016 | fastai/fastai | fastai/layers.py | icnr | def icnr(x, scale=2, init=nn.init.kaiming_normal_):
"ICNR init of `x`, with `scale` and `init` function."
ni,nf,h,w = x.shape
ni2 = int(ni/(scale**2))
k = init(torch.zeros([ni2,nf,h,w])).transpose(0, 1)
k = k.contiguous().view(ni2, nf, -1)
k = k.repeat(1, 1, scale**2)
k = k.contiguous().view... | python | def icnr(x, scale=2, init=nn.init.kaiming_normal_):
"ICNR init of `x`, with `scale` and `init` function."
ni,nf,h,w = x.shape
ni2 = int(ni/(scale**2))
k = init(torch.zeros([ni2,nf,h,w])).transpose(0, 1)
k = k.contiguous().view(ni2, nf, -1)
k = k.repeat(1, 1, scale**2)
k = k.contiguous().view... | [
"def",
"icnr",
"(",
"x",
",",
"scale",
"=",
"2",
",",
"init",
"=",
"nn",
".",
"init",
".",
"kaiming_normal_",
")",
":",
"ni",
",",
"nf",
",",
"h",
",",
"w",
"=",
"x",
".",
"shape",
"ni2",
"=",
"int",
"(",
"ni",
"/",
"(",
"scale",
"**",
"2",... | ICNR init of `x`, with `scale` and `init` function. | [
"ICNR",
"init",
"of",
"x",
"with",
"scale",
"and",
"init",
"function",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L221-L229 |
21,017 | fastai/fastai | fastai/layers.py | CrossEntropyFlat | def CrossEntropyFlat(*args, axis:int=-1, **kwargs):
"Same as `nn.CrossEntropyLoss`, but flattens input and target."
return FlattenedLoss(nn.CrossEntropyLoss, *args, axis=axis, **kwargs) | python | def CrossEntropyFlat(*args, axis:int=-1, **kwargs):
"Same as `nn.CrossEntropyLoss`, but flattens input and target."
return FlattenedLoss(nn.CrossEntropyLoss, *args, axis=axis, **kwargs) | [
"def",
"CrossEntropyFlat",
"(",
"*",
"args",
",",
"axis",
":",
"int",
"=",
"-",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"FlattenedLoss",
"(",
"nn",
".",
"CrossEntropyLoss",
",",
"*",
"args",
",",
"axis",
"=",
"axis",
",",
"*",
"*",
"kwarg... | Same as `nn.CrossEntropyLoss`, but flattens input and target. | [
"Same",
"as",
"nn",
".",
"CrossEntropyLoss",
"but",
"flattens",
"input",
"and",
"target",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L269-L271 |
21,018 | fastai/fastai | fastai/layers.py | BCEWithLogitsFlat | def BCEWithLogitsFlat(*args, axis:int=-1, floatify:bool=True, **kwargs):
"Same as `nn.BCEWithLogitsLoss`, but flattens input and target."
return FlattenedLoss(nn.BCEWithLogitsLoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs) | python | def BCEWithLogitsFlat(*args, axis:int=-1, floatify:bool=True, **kwargs):
"Same as `nn.BCEWithLogitsLoss`, but flattens input and target."
return FlattenedLoss(nn.BCEWithLogitsLoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs) | [
"def",
"BCEWithLogitsFlat",
"(",
"*",
"args",
",",
"axis",
":",
"int",
"=",
"-",
"1",
",",
"floatify",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"FlattenedLoss",
"(",
"nn",
".",
"BCEWithLogitsLoss",
",",
"*",
"args",
",",... | Same as `nn.BCEWithLogitsLoss`, but flattens input and target. | [
"Same",
"as",
"nn",
".",
"BCEWithLogitsLoss",
"but",
"flattens",
"input",
"and",
"target",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L273-L275 |
21,019 | fastai/fastai | fastai/layers.py | BCEFlat | def BCEFlat(*args, axis:int=-1, floatify:bool=True, **kwargs):
"Same as `nn.BCELoss`, but flattens input and target."
return FlattenedLoss(nn.BCELoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs) | python | def BCEFlat(*args, axis:int=-1, floatify:bool=True, **kwargs):
"Same as `nn.BCELoss`, but flattens input and target."
return FlattenedLoss(nn.BCELoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs) | [
"def",
"BCEFlat",
"(",
"*",
"args",
",",
"axis",
":",
"int",
"=",
"-",
"1",
",",
"floatify",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"FlattenedLoss",
"(",
"nn",
".",
"BCELoss",
",",
"*",
"args",
",",
"axis",
"=",
... | Same as `nn.BCELoss`, but flattens input and target. | [
"Same",
"as",
"nn",
".",
"BCELoss",
"but",
"flattens",
"input",
"and",
"target",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L277-L279 |
21,020 | fastai/fastai | fastai/layers.py | MSELossFlat | def MSELossFlat(*args, axis:int=-1, floatify:bool=True, **kwargs):
"Same as `nn.MSELoss`, but flattens input and target."
return FlattenedLoss(nn.MSELoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs) | python | def MSELossFlat(*args, axis:int=-1, floatify:bool=True, **kwargs):
"Same as `nn.MSELoss`, but flattens input and target."
return FlattenedLoss(nn.MSELoss, *args, axis=axis, floatify=floatify, is_2d=False, **kwargs) | [
"def",
"MSELossFlat",
"(",
"*",
"args",
",",
"axis",
":",
"int",
"=",
"-",
"1",
",",
"floatify",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"FlattenedLoss",
"(",
"nn",
".",
"MSELoss",
",",
"*",
"args",
",",
"axis",
"="... | Same as `nn.MSELoss`, but flattens input and target. | [
"Same",
"as",
"nn",
".",
"MSELoss",
"but",
"flattens",
"input",
"and",
"target",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L281-L283 |
21,021 | fastai/fastai | fastai/layers.py | simple_cnn | def simple_cnn(actns:Collection[int], kernel_szs:Collection[int]=None,
strides:Collection[int]=None, bn=False) -> nn.Sequential:
"CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`."
nl = len(actns)-1
kernel_szs = ifnone(kernel_szs, [3]*nl)
stride... | python | def simple_cnn(actns:Collection[int], kernel_szs:Collection[int]=None,
strides:Collection[int]=None, bn=False) -> nn.Sequential:
"CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`."
nl = len(actns)-1
kernel_szs = ifnone(kernel_szs, [3]*nl)
stride... | [
"def",
"simple_cnn",
"(",
"actns",
":",
"Collection",
"[",
"int",
"]",
",",
"kernel_szs",
":",
"Collection",
"[",
"int",
"]",
"=",
"None",
",",
"strides",
":",
"Collection",
"[",
"int",
"]",
"=",
"None",
",",
"bn",
"=",
"False",
")",
"->",
"nn",
".... | CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`. | [
"CNN",
"with",
"conv_layer",
"defined",
"by",
"actns",
"kernel_szs",
"and",
"strides",
"plus",
"batchnorm",
"if",
"bn",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L293-L302 |
21,022 | fastai/fastai | fastai/layers.py | trunc_normal_ | def trunc_normal_(x:Tensor, mean:float=0., std:float=1.) -> Tensor:
"Truncated normal initialization."
# From https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/12
return x.normal_().fmod_(2).mul_(std).add_(mean) | python | def trunc_normal_(x:Tensor, mean:float=0., std:float=1.) -> Tensor:
"Truncated normal initialization."
# From https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/12
return x.normal_().fmod_(2).mul_(std).add_(mean) | [
"def",
"trunc_normal_",
"(",
"x",
":",
"Tensor",
",",
"mean",
":",
"float",
"=",
"0.",
",",
"std",
":",
"float",
"=",
"1.",
")",
"->",
"Tensor",
":",
"# From https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/12",
"return",
"x",
".",
"nor... | Truncated normal initialization. | [
"Truncated",
"normal",
"initialization",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L304-L307 |
21,023 | fastai/fastai | fastai/layers.py | embedding | def embedding(ni:int,nf:int) -> nn.Module:
"Create an embedding layer."
emb = nn.Embedding(ni, nf)
# See https://arxiv.org/abs/1711.09160
with torch.no_grad(): trunc_normal_(emb.weight, std=0.01)
return emb | python | def embedding(ni:int,nf:int) -> nn.Module:
"Create an embedding layer."
emb = nn.Embedding(ni, nf)
# See https://arxiv.org/abs/1711.09160
with torch.no_grad(): trunc_normal_(emb.weight, std=0.01)
return emb | [
"def",
"embedding",
"(",
"ni",
":",
"int",
",",
"nf",
":",
"int",
")",
"->",
"nn",
".",
"Module",
":",
"emb",
"=",
"nn",
".",
"Embedding",
"(",
"ni",
",",
"nf",
")",
"# See https://arxiv.org/abs/1711.09160",
"with",
"torch",
".",
"no_grad",
"(",
")",
... | Create an embedding layer. | [
"Create",
"an",
"embedding",
"layer",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L309-L314 |
21,024 | fastai/fastai | fastai/callbacks/mlflow.py | MLFlowTracker.on_train_begin | def on_train_begin(self, **kwargs: Any) -> None:
"Prepare MLflow experiment and log params"
self.client = mlflow.tracking.MlflowClient(self.uri)
exp = self.client.get_experiment_by_name(self.exp_name)
self.exp_id = self.client.create_experiment(self.exp_name) if exp is None else exp.expe... | python | def on_train_begin(self, **kwargs: Any) -> None:
"Prepare MLflow experiment and log params"
self.client = mlflow.tracking.MlflowClient(self.uri)
exp = self.client.get_experiment_by_name(self.exp_name)
self.exp_id = self.client.create_experiment(self.exp_name) if exp is None else exp.expe... | [
"def",
"on_train_begin",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"client",
"=",
"mlflow",
".",
"tracking",
".",
"MlflowClient",
"(",
"self",
".",
"uri",
")",
"exp",
"=",
"self",
".",
"client",
".",
"ge... | Prepare MLflow experiment and log params | [
"Prepare",
"MLflow",
"experiment",
"and",
"log",
"params"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L16-L24 |
21,025 | fastai/fastai | fastai/callbacks/mlflow.py | MLFlowTracker.on_epoch_end | def on_epoch_end(self, epoch, **kwargs:Any)->None:
"Send loss and metrics values to MLFlow after each epoch"
if kwargs['smooth_loss'] is None or kwargs["last_metrics"] is None: return
metrics = [kwargs['smooth_loss']] + kwargs["last_metrics"]
for name, val in zip(self.metrics_names, metr... | python | def on_epoch_end(self, epoch, **kwargs:Any)->None:
"Send loss and metrics values to MLFlow after each epoch"
if kwargs['smooth_loss'] is None or kwargs["last_metrics"] is None: return
metrics = [kwargs['smooth_loss']] + kwargs["last_metrics"]
for name, val in zip(self.metrics_names, metr... | [
"def",
"on_epoch_end",
"(",
"self",
",",
"epoch",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"if",
"kwargs",
"[",
"'smooth_loss'",
"]",
"is",
"None",
"or",
"kwargs",
"[",
"\"last_metrics\"",
"]",
"is",
"None",
":",
"return",
"metrics"... | Send loss and metrics values to MLFlow after each epoch | [
"Send",
"loss",
"and",
"metrics",
"values",
"to",
"MLFlow",
"after",
"each",
"epoch"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L26-L31 |
21,026 | fastai/fastai | fastai/callbacks/mlflow.py | MLFlowTracker.on_train_end | def on_train_end(self, **kwargs: Any) -> None:
"Store the notebook and stop run"
self.client.log_artifact(run_id=self.run, local_path=self.nb_path)
self.client.set_terminated(run_id=self.run) | python | def on_train_end(self, **kwargs: Any) -> None:
"Store the notebook and stop run"
self.client.log_artifact(run_id=self.run, local_path=self.nb_path)
self.client.set_terminated(run_id=self.run) | [
"def",
"on_train_end",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"client",
".",
"log_artifact",
"(",
"run_id",
"=",
"self",
".",
"run",
",",
"local_path",
"=",
"self",
".",
"nb_path",
")",
"self",
".",
"... | Store the notebook and stop run | [
"Store",
"the",
"notebook",
"and",
"stop",
"run"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L33-L36 |
21,027 | fastai/fastai | fastai/vision/image.py | pil2tensor | def pil2tensor(image:Union[NPImage,NPArray],dtype:np.dtype)->TensorImage:
"Convert PIL style `image` array to torch style image tensor."
a = np.asarray(image)
if a.ndim==2 : a = np.expand_dims(a,2)
a = np.transpose(a, (1, 0, 2))
a = np.transpose(a, (2, 1, 0))
return torch.from_numpy(a.astype(dty... | python | def pil2tensor(image:Union[NPImage,NPArray],dtype:np.dtype)->TensorImage:
"Convert PIL style `image` array to torch style image tensor."
a = np.asarray(image)
if a.ndim==2 : a = np.expand_dims(a,2)
a = np.transpose(a, (1, 0, 2))
a = np.transpose(a, (2, 1, 0))
return torch.from_numpy(a.astype(dty... | [
"def",
"pil2tensor",
"(",
"image",
":",
"Union",
"[",
"NPImage",
",",
"NPArray",
"]",
",",
"dtype",
":",
"np",
".",
"dtype",
")",
"->",
"TensorImage",
":",
"a",
"=",
"np",
".",
"asarray",
"(",
"image",
")",
"if",
"a",
".",
"ndim",
"==",
"2",
":",... | Convert PIL style `image` array to torch style image tensor. | [
"Convert",
"PIL",
"style",
"image",
"array",
"to",
"torch",
"style",
"image",
"tensor",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L14-L20 |
21,028 | fastai/fastai | fastai/vision/image.py | _draw_outline | def _draw_outline(o:Patch, lw:int):
"Outline bounding box onto image `Patch`."
o.set_path_effects([patheffects.Stroke(
linewidth=lw, foreground='black'), patheffects.Normal()]) | python | def _draw_outline(o:Patch, lw:int):
"Outline bounding box onto image `Patch`."
o.set_path_effects([patheffects.Stroke(
linewidth=lw, foreground='black'), patheffects.Normal()]) | [
"def",
"_draw_outline",
"(",
"o",
":",
"Patch",
",",
"lw",
":",
"int",
")",
":",
"o",
".",
"set_path_effects",
"(",
"[",
"patheffects",
".",
"Stroke",
"(",
"linewidth",
"=",
"lw",
",",
"foreground",
"=",
"'black'",
")",
",",
"patheffects",
".",
"Normal... | Outline bounding box onto image `Patch`. | [
"Outline",
"bounding",
"box",
"onto",
"image",
"Patch",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L36-L39 |
21,029 | fastai/fastai | fastai/vision/image.py | _draw_rect | def _draw_rect(ax:plt.Axes, b:Collection[int], color:str='white', text=None, text_size=14):
"Draw bounding box on `ax`."
patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor=color, lw=2))
_draw_outline(patch, 4)
if text is not None:
patch = ax.text(*b[:2], text, verticala... | python | def _draw_rect(ax:plt.Axes, b:Collection[int], color:str='white', text=None, text_size=14):
"Draw bounding box on `ax`."
patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor=color, lw=2))
_draw_outline(patch, 4)
if text is not None:
patch = ax.text(*b[:2], text, verticala... | [
"def",
"_draw_rect",
"(",
"ax",
":",
"plt",
".",
"Axes",
",",
"b",
":",
"Collection",
"[",
"int",
"]",
",",
"color",
":",
"str",
"=",
"'white'",
",",
"text",
"=",
"None",
",",
"text_size",
"=",
"14",
")",
":",
"patch",
"=",
"ax",
".",
"add_patch"... | Draw bounding box on `ax`. | [
"Draw",
"bounding",
"box",
"on",
"ax",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L41-L47 |
21,030 | fastai/fastai | fastai/vision/image.py | open_image | def open_image(fn:PathOrStr, div:bool=True, convert_mode:str='RGB', cls:type=Image,
after_open:Callable=None)->Image:
"Return `Image` object created from image in file `fn`."
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning) # EXIF warning from TiffPlugin
x = P... | python | def open_image(fn:PathOrStr, div:bool=True, convert_mode:str='RGB', cls:type=Image,
after_open:Callable=None)->Image:
"Return `Image` object created from image in file `fn`."
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning) # EXIF warning from TiffPlugin
x = P... | [
"def",
"open_image",
"(",
"fn",
":",
"PathOrStr",
",",
"div",
":",
"bool",
"=",
"True",
",",
"convert_mode",
":",
"str",
"=",
"'RGB'",
",",
"cls",
":",
"type",
"=",
"Image",
",",
"after_open",
":",
"Callable",
"=",
"None",
")",
"->",
"Image",
":",
... | Return `Image` object created from image in file `fn`. | [
"Return",
"Image",
"object",
"created",
"from",
"image",
"in",
"file",
"fn",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L388-L397 |
21,031 | fastai/fastai | fastai/vision/image.py | open_mask | def open_mask(fn:PathOrStr, div=False, convert_mode='L', after_open:Callable=None)->ImageSegment:
"Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255."
return open_image(fn, div=div, convert_mode=convert_mode, cls=ImageSegment, after_open=after_open) | python | def open_mask(fn:PathOrStr, div=False, convert_mode='L', after_open:Callable=None)->ImageSegment:
"Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255."
return open_image(fn, div=div, convert_mode=convert_mode, cls=ImageSegment, after_open=after_open) | [
"def",
"open_mask",
"(",
"fn",
":",
"PathOrStr",
",",
"div",
"=",
"False",
",",
"convert_mode",
"=",
"'L'",
",",
"after_open",
":",
"Callable",
"=",
"None",
")",
"->",
"ImageSegment",
":",
"return",
"open_image",
"(",
"fn",
",",
"div",
"=",
"div",
",",... | Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255. | [
"Return",
"ImageSegment",
"object",
"create",
"from",
"mask",
"in",
"file",
"fn",
".",
"If",
"div",
"divides",
"pixel",
"values",
"by",
"255",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L399-L401 |
21,032 | fastai/fastai | fastai/vision/image.py | open_mask_rle | def open_mask_rle(mask_rle:str, shape:Tuple[int, int])->ImageSegment:
"Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`."
x = FloatTensor(rle_decode(str(mask_rle), shape).astype(np.uint8))
x = x.view(shape[1], shape[0], -1)
return ImageSegment(x.permu... | python | def open_mask_rle(mask_rle:str, shape:Tuple[int, int])->ImageSegment:
"Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`."
x = FloatTensor(rle_decode(str(mask_rle), shape).astype(np.uint8))
x = x.view(shape[1], shape[0], -1)
return ImageSegment(x.permu... | [
"def",
"open_mask_rle",
"(",
"mask_rle",
":",
"str",
",",
"shape",
":",
"Tuple",
"[",
"int",
",",
"int",
"]",
")",
"->",
"ImageSegment",
":",
"x",
"=",
"FloatTensor",
"(",
"rle_decode",
"(",
"str",
"(",
"mask_rle",
")",
",",
"shape",
")",
".",
"astyp... | Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`. | [
"Return",
"ImageSegment",
"object",
"create",
"from",
"run",
"-",
"length",
"encoded",
"string",
"in",
"mask_lre",
"with",
"size",
"in",
"shape",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L403-L407 |
21,033 | fastai/fastai | fastai/vision/image.py | rle_encode | def rle_encode(img:NPArrayMask)->str:
"Return run-length encoding string from `img`."
pixels = np.concatenate([[0], img.flatten() , [0]])
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
runs[1::2] -= runs[::2]
return ' '.join(str(x) for x in runs) | python | def rle_encode(img:NPArrayMask)->str:
"Return run-length encoding string from `img`."
pixels = np.concatenate([[0], img.flatten() , [0]])
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
runs[1::2] -= runs[::2]
return ' '.join(str(x) for x in runs) | [
"def",
"rle_encode",
"(",
"img",
":",
"NPArrayMask",
")",
"->",
"str",
":",
"pixels",
"=",
"np",
".",
"concatenate",
"(",
"[",
"[",
"0",
"]",
",",
"img",
".",
"flatten",
"(",
")",
",",
"[",
"0",
"]",
"]",
")",
"runs",
"=",
"np",
".",
"where",
... | Return run-length encoding string from `img`. | [
"Return",
"run",
"-",
"length",
"encoding",
"string",
"from",
"img",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L409-L414 |
21,034 | fastai/fastai | fastai/vision/image.py | rle_decode | def rle_decode(mask_rle:str, shape:Tuple[int,int])->NPArrayMask:
"Return an image array from run-length encoded string `mask_rle` with `shape`."
s = mask_rle.split()
starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
starts -= 1
ends = starts + lengths
img = np.zeros(... | python | def rle_decode(mask_rle:str, shape:Tuple[int,int])->NPArrayMask:
"Return an image array from run-length encoded string `mask_rle` with `shape`."
s = mask_rle.split()
starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
starts -= 1
ends = starts + lengths
img = np.zeros(... | [
"def",
"rle_decode",
"(",
"mask_rle",
":",
"str",
",",
"shape",
":",
"Tuple",
"[",
"int",
",",
"int",
"]",
")",
"->",
"NPArrayMask",
":",
"s",
"=",
"mask_rle",
".",
"split",
"(",
")",
"starts",
",",
"lengths",
"=",
"[",
"np",
".",
"asarray",
"(",
... | Return an image array from run-length encoded string `mask_rle` with `shape`. | [
"Return",
"an",
"image",
"array",
"from",
"run",
"-",
"length",
"encoded",
"string",
"mask_rle",
"with",
"shape",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L416-L424 |
21,035 | fastai/fastai | fastai/vision/image.py | show_image | def show_image(img:Image, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True, cmap:str='binary',
alpha:float=None, **kwargs)->plt.Axes:
"Display `Image` in notebook."
if ax is None: fig,ax = plt.subplots(figsize=figsize)
ax.imshow(image2np(img.data), cmap=cmap, alpha=alpha, **kwargs)... | python | def show_image(img:Image, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True, cmap:str='binary',
alpha:float=None, **kwargs)->plt.Axes:
"Display `Image` in notebook."
if ax is None: fig,ax = plt.subplots(figsize=figsize)
ax.imshow(image2np(img.data), cmap=cmap, alpha=alpha, **kwargs)... | [
"def",
"show_image",
"(",
"img",
":",
"Image",
",",
"ax",
":",
"plt",
".",
"Axes",
"=",
"None",
",",
"figsize",
":",
"tuple",
"=",
"(",
"3",
",",
"3",
")",
",",
"hide_axis",
":",
"bool",
"=",
"True",
",",
"cmap",
":",
"str",
"=",
"'binary'",
",... | Display `Image` in notebook. | [
"Display",
"Image",
"in",
"notebook",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L426-L432 |
21,036 | fastai/fastai | fastai/vision/image.py | _affine_mult | def _affine_mult(c:FlowField,m:AffineMatrix)->FlowField:
"Multiply `c` by `m` - can adjust for rectangular shaped `c`."
if m is None: return c
size = c.flow.size()
h,w = c.size
m[0,1] *= h/w
m[1,0] *= w/h
c.flow = c.flow.view(-1,2)
c.flow = torch.addmm(m[:2,2], c.flow, m[:2,:2].t()).vie... | python | def _affine_mult(c:FlowField,m:AffineMatrix)->FlowField:
"Multiply `c` by `m` - can adjust for rectangular shaped `c`."
if m is None: return c
size = c.flow.size()
h,w = c.size
m[0,1] *= h/w
m[1,0] *= w/h
c.flow = c.flow.view(-1,2)
c.flow = torch.addmm(m[:2,2], c.flow, m[:2,:2].t()).vie... | [
"def",
"_affine_mult",
"(",
"c",
":",
"FlowField",
",",
"m",
":",
"AffineMatrix",
")",
"->",
"FlowField",
":",
"if",
"m",
"is",
"None",
":",
"return",
"c",
"size",
"=",
"c",
".",
"flow",
".",
"size",
"(",
")",
"h",
",",
"w",
"=",
"c",
".",
"siz... | Multiply `c` by `m` - can adjust for rectangular shaped `c`. | [
"Multiply",
"c",
"by",
"m",
"-",
"can",
"adjust",
"for",
"rectangular",
"shaped",
"c",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L547-L556 |
21,037 | fastai/fastai | fastai/vision/image.py | _affine_inv_mult | def _affine_inv_mult(c, m):
"Applies the inverse affine transform described in `m` to `c`."
size = c.flow.size()
h,w = c.size
m[0,1] *= h/w
m[1,0] *= w/h
c.flow = c.flow.view(-1,2)
a = torch.inverse(m[:2,:2].t())
c.flow = torch.mm(c.flow - m[:2,2], a).view(size)
return c | python | def _affine_inv_mult(c, m):
"Applies the inverse affine transform described in `m` to `c`."
size = c.flow.size()
h,w = c.size
m[0,1] *= h/w
m[1,0] *= w/h
c.flow = c.flow.view(-1,2)
a = torch.inverse(m[:2,:2].t())
c.flow = torch.mm(c.flow - m[:2,2], a).view(size)
return c | [
"def",
"_affine_inv_mult",
"(",
"c",
",",
"m",
")",
":",
"size",
"=",
"c",
".",
"flow",
".",
"size",
"(",
")",
"h",
",",
"w",
"=",
"c",
".",
"size",
"m",
"[",
"0",
",",
"1",
"]",
"*=",
"h",
"/",
"w",
"m",
"[",
"1",
",",
"0",
"]",
"*=",
... | Applies the inverse affine transform described in `m` to `c`. | [
"Applies",
"the",
"inverse",
"affine",
"transform",
"described",
"in",
"m",
"to",
"c",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L558-L567 |
21,038 | fastai/fastai | fastai/vision/image.py | _round_multiple | def _round_multiple(x:int, mult:int=None)->int:
"Calc `x` to nearest multiple of `mult`."
return (int(x/mult+0.5)*mult) if mult is not None else x | python | def _round_multiple(x:int, mult:int=None)->int:
"Calc `x` to nearest multiple of `mult`."
return (int(x/mult+0.5)*mult) if mult is not None else x | [
"def",
"_round_multiple",
"(",
"x",
":",
"int",
",",
"mult",
":",
"int",
"=",
"None",
")",
"->",
"int",
":",
"return",
"(",
"int",
"(",
"x",
"/",
"mult",
"+",
"0.5",
")",
"*",
"mult",
")",
"if",
"mult",
"is",
"not",
"None",
"else",
"x"
] | Calc `x` to nearest multiple of `mult`. | [
"Calc",
"x",
"to",
"nearest",
"multiple",
"of",
"mult",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L585-L587 |
21,039 | fastai/fastai | fastai/vision/image.py | _get_crop_target | def _get_crop_target(target_px:Union[int,TensorImageSize], mult:int=None)->Tuple[int,int]:
"Calc crop shape of `target_px` to nearest multiple of `mult`."
target_r,target_c = tis2hw(target_px)
return _round_multiple(target_r,mult),_round_multiple(target_c,mult) | python | def _get_crop_target(target_px:Union[int,TensorImageSize], mult:int=None)->Tuple[int,int]:
"Calc crop shape of `target_px` to nearest multiple of `mult`."
target_r,target_c = tis2hw(target_px)
return _round_multiple(target_r,mult),_round_multiple(target_c,mult) | [
"def",
"_get_crop_target",
"(",
"target_px",
":",
"Union",
"[",
"int",
",",
"TensorImageSize",
"]",
",",
"mult",
":",
"int",
"=",
"None",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"target_r",
",",
"target_c",
"=",
"tis2hw",
"(",
"target_px"... | Calc crop shape of `target_px` to nearest multiple of `mult`. | [
"Calc",
"crop",
"shape",
"of",
"target_px",
"to",
"nearest",
"multiple",
"of",
"mult",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L589-L592 |
21,040 | fastai/fastai | fastai/vision/image.py | _get_resize_target | def _get_resize_target(img, crop_target, do_crop=False)->TensorImageSize:
"Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`."
if crop_target is None: return None
ch,r,c = img.shape
target_r,target_c = crop_target
ratio = (min if do_crop else max)(r/target_r, c/target_c)
ret... | python | def _get_resize_target(img, crop_target, do_crop=False)->TensorImageSize:
"Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`."
if crop_target is None: return None
ch,r,c = img.shape
target_r,target_c = crop_target
ratio = (min if do_crop else max)(r/target_r, c/target_c)
ret... | [
"def",
"_get_resize_target",
"(",
"img",
",",
"crop_target",
",",
"do_crop",
"=",
"False",
")",
"->",
"TensorImageSize",
":",
"if",
"crop_target",
"is",
"None",
":",
"return",
"None",
"ch",
",",
"r",
",",
"c",
"=",
"img",
".",
"shape",
"target_r",
",",
... | Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`. | [
"Calc",
"size",
"of",
"img",
"to",
"fit",
"in",
"crop_target",
"-",
"adjust",
"based",
"on",
"do_crop",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L594-L600 |
21,041 | fastai/fastai | fastai/vision/image.py | plot_multi | def plot_multi(func:Callable[[int,int,plt.Axes],None], r:int=1, c:int=1, figsize:Tuple=(12,6)):
"Call `func` for every combination of `r,c` on a subplot"
axes = plt.subplots(r, c, figsize=figsize)[1]
for i in range(r):
for j in range(c): func(i,j,axes[i,j]) | python | def plot_multi(func:Callable[[int,int,plt.Axes],None], r:int=1, c:int=1, figsize:Tuple=(12,6)):
"Call `func` for every combination of `r,c` on a subplot"
axes = plt.subplots(r, c, figsize=figsize)[1]
for i in range(r):
for j in range(c): func(i,j,axes[i,j]) | [
"def",
"plot_multi",
"(",
"func",
":",
"Callable",
"[",
"[",
"int",
",",
"int",
",",
"plt",
".",
"Axes",
"]",
",",
"None",
"]",
",",
"r",
":",
"int",
"=",
"1",
",",
"c",
":",
"int",
"=",
"1",
",",
"figsize",
":",
"Tuple",
"=",
"(",
"12",
",... | Call `func` for every combination of `r,c` on a subplot | [
"Call",
"func",
"for",
"every",
"combination",
"of",
"r",
"c",
"on",
"a",
"subplot"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L606-L610 |
21,042 | fastai/fastai | fastai/vision/image.py | show_all | def show_all(imgs:Collection[Image], r:int=1, c:Optional[int]=None, figsize=(12,6)):
"Show all `imgs` using `r` rows"
imgs = listify(imgs)
if c is None: c = len(imgs)//r
for i,ax in plot_flat(r,c,figsize): imgs[i].show(ax) | python | def show_all(imgs:Collection[Image], r:int=1, c:Optional[int]=None, figsize=(12,6)):
"Show all `imgs` using `r` rows"
imgs = listify(imgs)
if c is None: c = len(imgs)//r
for i,ax in plot_flat(r,c,figsize): imgs[i].show(ax) | [
"def",
"show_all",
"(",
"imgs",
":",
"Collection",
"[",
"Image",
"]",
",",
"r",
":",
"int",
"=",
"1",
",",
"c",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"figsize",
"=",
"(",
"12",
",",
"6",
")",
")",
":",
"imgs",
"=",
"listify",
"(... | Show all `imgs` using `r` rows | [
"Show",
"all",
"imgs",
"using",
"r",
"rows"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L616-L620 |
21,043 | fastai/fastai | fastai/vision/image.py | Image.apply_tfms | def apply_tfms(self, tfms:TfmList, do_resolve:bool=True, xtra:Optional[Dict[Callable,dict]]=None,
size:Optional[Union[int,TensorImageSize]]=None, resize_method:ResizeMethod=None,
mult:int=None, padding_mode:str='reflection', mode:str='bilinear', remove_out:bool=True)->TensorImage:
... | python | def apply_tfms(self, tfms:TfmList, do_resolve:bool=True, xtra:Optional[Dict[Callable,dict]]=None,
size:Optional[Union[int,TensorImageSize]]=None, resize_method:ResizeMethod=None,
mult:int=None, padding_mode:str='reflection', mode:str='bilinear', remove_out:bool=True)->TensorImage:
... | [
"def",
"apply_tfms",
"(",
"self",
",",
"tfms",
":",
"TfmList",
",",
"do_resolve",
":",
"bool",
"=",
"True",
",",
"xtra",
":",
"Optional",
"[",
"Dict",
"[",
"Callable",
",",
"dict",
"]",
"]",
"=",
"None",
",",
"size",
":",
"Optional",
"[",
"Union",
... | Apply all `tfms` to the `Image`, if `do_resolve` picks value for random args. | [
"Apply",
"all",
"tfms",
"to",
"the",
"Image",
"if",
"do_resolve",
"picks",
"value",
"for",
"random",
"args",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L96-L124 |
21,044 | fastai/fastai | fastai/vision/image.py | Image.refresh | def refresh(self)->None:
"Apply any logit, flow, or affine transfers that have been sent to the `Image`."
if self._logit_px is not None:
self._px = self._logit_px.sigmoid_()
self._logit_px = None
if self._affine_mat is not None or self._flow is not None:
self.... | python | def refresh(self)->None:
"Apply any logit, flow, or affine transfers that have been sent to the `Image`."
if self._logit_px is not None:
self._px = self._logit_px.sigmoid_()
self._logit_px = None
if self._affine_mat is not None or self._flow is not None:
self.... | [
"def",
"refresh",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_logit_px",
"is",
"not",
"None",
":",
"self",
".",
"_px",
"=",
"self",
".",
"_logit_px",
".",
"sigmoid_",
"(",
")",
"self",
".",
"_logit_px",
"=",
"None",
"if",
"self",
".",... | Apply any logit, flow, or affine transfers that have been sent to the `Image`. | [
"Apply",
"any",
"logit",
"flow",
"or",
"affine",
"transfers",
"that",
"have",
"been",
"sent",
"to",
"the",
"Image",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L126-L135 |
21,045 | fastai/fastai | fastai/vision/image.py | Image.save | def save(self, fn:PathOrStr):
"Save the image to `fn`."
x = image2np(self.data*255).astype(np.uint8)
PIL.Image.fromarray(x).save(fn) | python | def save(self, fn:PathOrStr):
"Save the image to `fn`."
x = image2np(self.data*255).astype(np.uint8)
PIL.Image.fromarray(x).save(fn) | [
"def",
"save",
"(",
"self",
",",
"fn",
":",
"PathOrStr",
")",
":",
"x",
"=",
"image2np",
"(",
"self",
".",
"data",
"*",
"255",
")",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"PIL",
".",
"Image",
".",
"fromarray",
"(",
"x",
")",
".",
"save",
... | Save the image to `fn`. | [
"Save",
"the",
"image",
"to",
"fn",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L137-L140 |
21,046 | fastai/fastai | fastai/vision/image.py | Image.flow | def flow(self)->FlowField:
"Access the flow-field grid after applying queued affine transforms."
if self._flow is None:
self._flow = _affine_grid(self.shape)
if self._affine_mat is not None:
self._flow = _affine_mult(self._flow,self._affine_mat)
self._affine_m... | python | def flow(self)->FlowField:
"Access the flow-field grid after applying queued affine transforms."
if self._flow is None:
self._flow = _affine_grid(self.shape)
if self._affine_mat is not None:
self._flow = _affine_mult(self._flow,self._affine_mat)
self._affine_m... | [
"def",
"flow",
"(",
"self",
")",
"->",
"FlowField",
":",
"if",
"self",
".",
"_flow",
"is",
"None",
":",
"self",
".",
"_flow",
"=",
"_affine_grid",
"(",
"self",
".",
"shape",
")",
"if",
"self",
".",
"_affine_mat",
"is",
"not",
"None",
":",
"self",
"... | Access the flow-field grid after applying queued affine transforms. | [
"Access",
"the",
"flow",
"-",
"field",
"grid",
"after",
"applying",
"queued",
"affine",
"transforms",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L153-L160 |
21,047 | fastai/fastai | fastai/vision/image.py | Image.affine | def affine(self, func:AffineFunc, *args, **kwargs)->'Image':
"Equivalent to `image.affine_mat = image.affine_mat @ func()`."
m = tensor(func(*args, **kwargs)).to(self.device)
self.affine_mat = self.affine_mat @ m
return self | python | def affine(self, func:AffineFunc, *args, **kwargs)->'Image':
"Equivalent to `image.affine_mat = image.affine_mat @ func()`."
m = tensor(func(*args, **kwargs)).to(self.device)
self.affine_mat = self.affine_mat @ m
return self | [
"def",
"affine",
"(",
"self",
",",
"func",
":",
"AffineFunc",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"'Image'",
":",
"m",
"=",
"tensor",
"(",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
".",
"to",
"(",
"self",
... | Equivalent to `image.affine_mat = image.affine_mat @ func()`. | [
"Equivalent",
"to",
"image",
".",
"affine_mat",
"=",
"image",
".",
"affine_mat"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L180-L184 |
21,048 | fastai/fastai | fastai/vision/image.py | Image.affine_mat | def affine_mat(self)->AffineMatrix:
"Get the affine matrix that will be applied by `refresh`."
if self._affine_mat is None:
self._affine_mat = torch.eye(3).to(self.device)
return self._affine_mat | python | def affine_mat(self)->AffineMatrix:
"Get the affine matrix that will be applied by `refresh`."
if self._affine_mat is None:
self._affine_mat = torch.eye(3).to(self.device)
return self._affine_mat | [
"def",
"affine_mat",
"(",
"self",
")",
"->",
"AffineMatrix",
":",
"if",
"self",
".",
"_affine_mat",
"is",
"None",
":",
"self",
".",
"_affine_mat",
"=",
"torch",
".",
"eye",
"(",
"3",
")",
".",
"to",
"(",
"self",
".",
"device",
")",
"return",
"self",
... | Get the affine matrix that will be applied by `refresh`. | [
"Get",
"the",
"affine",
"matrix",
"that",
"will",
"be",
"applied",
"by",
"refresh",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L195-L199 |
21,049 | fastai/fastai | fastai/vision/image.py | Image.show | def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True,
cmap:str=None, y:Any=None, **kwargs):
"Show image on `ax` with `title`, using `cmap` if single-channel, overlaid with optional `y`"
cmap = ifnone(cmap, defaults.cmap)
ax = show_imag... | python | def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True,
cmap:str=None, y:Any=None, **kwargs):
"Show image on `ax` with `title`, using `cmap` if single-channel, overlaid with optional `y`"
cmap = ifnone(cmap, defaults.cmap)
ax = show_imag... | [
"def",
"show",
"(",
"self",
",",
"ax",
":",
"plt",
".",
"Axes",
"=",
"None",
",",
"figsize",
":",
"tuple",
"=",
"(",
"3",
",",
"3",
")",
",",
"title",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"hide_axis",
":",
"bool",
"=",
"True",
... | Show image on `ax` with `title`, using `cmap` if single-channel, overlaid with optional `y` | [
"Show",
"image",
"on",
"ax",
"with",
"title",
"using",
"cmap",
"if",
"single",
"-",
"channel",
"overlaid",
"with",
"optional",
"y"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L216-L222 |
21,050 | fastai/fastai | fastai/vision/image.py | ImageSegment.show | def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True,
cmap:str='tab20', alpha:float=0.5, **kwargs):
"Show the `ImageSegment` on `ax`."
ax = show_image(self, ax=ax, hide_axis=hide_axis, cmap=cmap, figsize=figsize,
interpolatio... | python | def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True,
cmap:str='tab20', alpha:float=0.5, **kwargs):
"Show the `ImageSegment` on `ax`."
ax = show_image(self, ax=ax, hide_axis=hide_axis, cmap=cmap, figsize=figsize,
interpolatio... | [
"def",
"show",
"(",
"self",
",",
"ax",
":",
"plt",
".",
"Axes",
"=",
"None",
",",
"figsize",
":",
"tuple",
"=",
"(",
"3",
",",
"3",
")",
",",
"title",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"hide_axis",
":",
"bool",
"=",
"True",
... | Show the `ImageSegment` on `ax`. | [
"Show",
"the",
"ImageSegment",
"on",
"ax",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L237-L242 |
21,051 | fastai/fastai | fastai/vision/image.py | ImagePoints.clone | def clone(self):
"Mimic the behavior of torch.clone for `ImagePoints` objects."
return self.__class__(FlowField(self.size, self.flow.flow.clone()), scale=False, y_first=False) | python | def clone(self):
"Mimic the behavior of torch.clone for `ImagePoints` objects."
return self.__class__(FlowField(self.size, self.flow.flow.clone()), scale=False, y_first=False) | [
"def",
"clone",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"FlowField",
"(",
"self",
".",
"size",
",",
"self",
".",
"flow",
".",
"flow",
".",
"clone",
"(",
")",
")",
",",
"scale",
"=",
"False",
",",
"y_first",
"=",
"False",
"... | Mimic the behavior of torch.clone for `ImagePoints` objects. | [
"Mimic",
"the",
"behavior",
"of",
"torch",
".",
"clone",
"for",
"ImagePoints",
"objects",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L258-L260 |
21,052 | fastai/fastai | fastai/vision/image.py | ImagePoints.flow | def flow(self)->FlowField:
"Access the flow-field grid after applying queued affine and coord transforms."
if self._affine_mat is not None:
self._flow = _affine_inv_mult(self._flow, self._affine_mat)
self._affine_mat = None
self.transformed = True
if len(self.... | python | def flow(self)->FlowField:
"Access the flow-field grid after applying queued affine and coord transforms."
if self._affine_mat is not None:
self._flow = _affine_inv_mult(self._flow, self._affine_mat)
self._affine_mat = None
self.transformed = True
if len(self.... | [
"def",
"flow",
"(",
"self",
")",
"->",
"FlowField",
":",
"if",
"self",
".",
"_affine_mat",
"is",
"not",
"None",
":",
"self",
".",
"_flow",
"=",
"_affine_inv_mult",
"(",
"self",
".",
"_flow",
",",
"self",
".",
"_affine_mat",
")",
"self",
".",
"_affine_m... | Access the flow-field grid after applying queued affine and coord transforms. | [
"Access",
"the",
"flow",
"-",
"field",
"grid",
"after",
"applying",
"queued",
"affine",
"and",
"coord",
"transforms",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L275-L285 |
21,053 | fastai/fastai | fastai/vision/image.py | ImagePoints.coord | def coord(self, func:CoordFunc, *args, **kwargs)->'ImagePoints':
"Put `func` with `args` and `kwargs` in `self.flow_func` for later."
if 'invert' in kwargs: kwargs['invert'] = True
else: warn(f"{func.__name__} isn't implemented for {self.__class__}.")
self.flow_func.append(partial(func, ... | python | def coord(self, func:CoordFunc, *args, **kwargs)->'ImagePoints':
"Put `func` with `args` and `kwargs` in `self.flow_func` for later."
if 'invert' in kwargs: kwargs['invert'] = True
else: warn(f"{func.__name__} isn't implemented for {self.__class__}.")
self.flow_func.append(partial(func, ... | [
"def",
"coord",
"(",
"self",
",",
"func",
":",
"CoordFunc",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"'ImagePoints'",
":",
"if",
"'invert'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'invert'",
"]",
"=",
"True",
"else",
":",
"warn",
"(",
"f... | Put `func` with `args` and `kwargs` in `self.flow_func` for later. | [
"Put",
"func",
"with",
"args",
"and",
"kwargs",
"in",
"self",
".",
"flow_func",
"for",
"later",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L290-L295 |
21,054 | fastai/fastai | fastai/vision/image.py | ImagePoints.data | def data(self)->Tensor:
"Return the points associated to this object."
flow = self.flow #This updates flow before we test if some transforms happened
if self.transformed:
if 'remove_out' not in self.sample_kwargs or self.sample_kwargs['remove_out']:
flow = _remove_poi... | python | def data(self)->Tensor:
"Return the points associated to this object."
flow = self.flow #This updates flow before we test if some transforms happened
if self.transformed:
if 'remove_out' not in self.sample_kwargs or self.sample_kwargs['remove_out']:
flow = _remove_poi... | [
"def",
"data",
"(",
"self",
")",
"->",
"Tensor",
":",
"flow",
"=",
"self",
".",
"flow",
"#This updates flow before we test if some transforms happened",
"if",
"self",
".",
"transformed",
":",
"if",
"'remove_out'",
"not",
"in",
"self",
".",
"sample_kwargs",
"or",
... | Return the points associated to this object. | [
"Return",
"the",
"points",
"associated",
"to",
"this",
"object",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L315-L322 |
21,055 | fastai/fastai | fastai/vision/image.py | ImagePoints.show | def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, **kwargs):
"Show the `ImagePoints` on `ax`."
if ax is None: _,ax = plt.subplots(figsize=figsize)
pnt = scale_flow(FlowField(self.size, self.data), to_unit=False).flow.flip(1)
params = {'s... | python | def show(self, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True, **kwargs):
"Show the `ImagePoints` on `ax`."
if ax is None: _,ax = plt.subplots(figsize=figsize)
pnt = scale_flow(FlowField(self.size, self.data), to_unit=False).flow.flip(1)
params = {'s... | [
"def",
"show",
"(",
"self",
",",
"ax",
":",
"plt",
".",
"Axes",
"=",
"None",
",",
"figsize",
":",
"tuple",
"=",
"(",
"3",
",",
"3",
")",
",",
"title",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"hide_axis",
":",
"bool",
"=",
"True",
... | Show the `ImagePoints` on `ax`. | [
"Show",
"the",
"ImagePoints",
"on",
"ax",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L324-L331 |
21,056 | fastai/fastai | fastai/vision/image.py | ImageBBox.clone | def clone(self) -> 'ImageBBox':
"Mimic the behavior of torch.clone for `Image` objects."
flow = FlowField(self.size, self.flow.flow.clone())
return self.__class__(flow, scale=False, y_first=False, labels=self.labels, pad_idx=self.pad_idx) | python | def clone(self) -> 'ImageBBox':
"Mimic the behavior of torch.clone for `Image` objects."
flow = FlowField(self.size, self.flow.flow.clone())
return self.__class__(flow, scale=False, y_first=False, labels=self.labels, pad_idx=self.pad_idx) | [
"def",
"clone",
"(",
"self",
")",
"->",
"'ImageBBox'",
":",
"flow",
"=",
"FlowField",
"(",
"self",
".",
"size",
",",
"self",
".",
"flow",
".",
"flow",
".",
"clone",
"(",
")",
")",
"return",
"self",
".",
"__class__",
"(",
"flow",
",",
"scale",
"=",
... | Mimic the behavior of torch.clone for `Image` objects. | [
"Mimic",
"the",
"behavior",
"of",
"torch",
".",
"clone",
"for",
"Image",
"objects",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L343-L346 |
21,057 | fastai/fastai | fastai/vision/image.py | ImageBBox.create | def create(cls, h:int, w:int, bboxes:Collection[Collection[int]], labels:Collection=None, classes:dict=None,
pad_idx:int=0, scale:bool=True)->'ImageBBox':
"Create an ImageBBox object from `bboxes`."
if isinstance(bboxes, np.ndarray) and bboxes.dtype == np.object: bboxes = np.array([bb for... | python | def create(cls, h:int, w:int, bboxes:Collection[Collection[int]], labels:Collection=None, classes:dict=None,
pad_idx:int=0, scale:bool=True)->'ImageBBox':
"Create an ImageBBox object from `bboxes`."
if isinstance(bboxes, np.ndarray) and bboxes.dtype == np.object: bboxes = np.array([bb for... | [
"def",
"create",
"(",
"cls",
",",
"h",
":",
"int",
",",
"w",
":",
"int",
",",
"bboxes",
":",
"Collection",
"[",
"Collection",
"[",
"int",
"]",
"]",
",",
"labels",
":",
"Collection",
"=",
"None",
",",
"classes",
":",
"dict",
"=",
"None",
",",
"pad... | Create an ImageBBox object from `bboxes`. | [
"Create",
"an",
"ImageBBox",
"object",
"from",
"bboxes",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L349-L358 |
21,058 | fastai/fastai | fastai/vision/image.py | ImageBBox.show | def show(self, y:Image=None, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True,
color:str='white', **kwargs):
"Show the `ImageBBox` on `ax`."
if ax is None: _,ax = plt.subplots(figsize=figsize)
bboxes, lbls = self._compute_boxes()
h,w = self.flo... | python | def show(self, y:Image=None, ax:plt.Axes=None, figsize:tuple=(3,3), title:Optional[str]=None, hide_axis:bool=True,
color:str='white', **kwargs):
"Show the `ImageBBox` on `ax`."
if ax is None: _,ax = plt.subplots(figsize=figsize)
bboxes, lbls = self._compute_boxes()
h,w = self.flo... | [
"def",
"show",
"(",
"self",
",",
"y",
":",
"Image",
"=",
"None",
",",
"ax",
":",
"plt",
".",
"Axes",
"=",
"None",
",",
"figsize",
":",
"tuple",
"=",
"(",
"3",
",",
"3",
")",
",",
"title",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
... | Show the `ImageBBox` on `ax`. | [
"Show",
"the",
"ImageBBox",
"on",
"ax",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L376-L386 |
21,059 | fastai/fastai | fastai/vision/image.py | Transform.calc | def calc(self, x:Image, *args:Any, **kwargs:Any)->Image:
"Apply to image `x`, wrapping it if necessary."
if self._wrap: return getattr(x, self._wrap)(self.func, *args, **kwargs)
else: return self.func(x, *args, **kwargs) | python | def calc(self, x:Image, *args:Any, **kwargs:Any)->Image:
"Apply to image `x`, wrapping it if necessary."
if self._wrap: return getattr(x, self._wrap)(self.func, *args, **kwargs)
else: return self.func(x, *args, **kwargs) | [
"def",
"calc",
"(",
"self",
",",
"x",
":",
"Image",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Image",
":",
"if",
"self",
".",
"_wrap",
":",
"return",
"getattr",
"(",
"x",
",",
"self",
".",
"_wrap",
")",
"(... | Apply to image `x`, wrapping it if necessary. | [
"Apply",
"to",
"image",
"x",
"wrapping",
"it",
"if",
"necessary",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L467-L470 |
21,060 | fastai/fastai | fastai/datasets.py | url2path | def url2path(url, data=True, ext:str='.tgz'):
"Change `url` to a path."
name = url2name(url)
return datapath4file(name, ext=ext, archive=False) if data else modelpath4file(name, ext=ext) | python | def url2path(url, data=True, ext:str='.tgz'):
"Change `url` to a path."
name = url2name(url)
return datapath4file(name, ext=ext, archive=False) if data else modelpath4file(name, ext=ext) | [
"def",
"url2path",
"(",
"url",
",",
"data",
"=",
"True",
",",
"ext",
":",
"str",
"=",
"'.tgz'",
")",
":",
"name",
"=",
"url2name",
"(",
"url",
")",
"return",
"datapath4file",
"(",
"name",
",",
"ext",
"=",
"ext",
",",
"archive",
"=",
"False",
")",
... | Change `url` to a path. | [
"Change",
"url",
"to",
"a",
"path",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L186-L189 |
21,061 | fastai/fastai | fastai/datasets.py | modelpath4file | def modelpath4file(filename, ext:str='.tgz'):
"Return model path to `filename`, checking locally first then in the config file."
local_path = URLs.LOCAL_PATH/'models'/filename
if local_path.exists() or local_path.with_suffix(ext).exists(): return local_path
else: return Config.model_path()/filename | python | def modelpath4file(filename, ext:str='.tgz'):
"Return model path to `filename`, checking locally first then in the config file."
local_path = URLs.LOCAL_PATH/'models'/filename
if local_path.exists() or local_path.with_suffix(ext).exists(): return local_path
else: return Config.model_path()/filename | [
"def",
"modelpath4file",
"(",
"filename",
",",
"ext",
":",
"str",
"=",
"'.tgz'",
")",
":",
"local_path",
"=",
"URLs",
".",
"LOCAL_PATH",
"/",
"'models'",
"/",
"filename",
"if",
"local_path",
".",
"exists",
"(",
")",
"or",
"local_path",
".",
"with_suffix",
... | Return model path to `filename`, checking locally first then in the config file. | [
"Return",
"model",
"path",
"to",
"filename",
"checking",
"locally",
"first",
"then",
"in",
"the",
"config",
"file",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L193-L197 |
21,062 | fastai/fastai | fastai/datasets.py | datapath4file | def datapath4file(filename, ext:str='.tgz', archive=True):
"Return data path to `filename`, checking locally first then in the config file."
local_path = URLs.LOCAL_PATH/'data'/filename
if local_path.exists() or local_path.with_suffix(ext).exists(): return local_path
elif archive: return Config.data_arc... | python | def datapath4file(filename, ext:str='.tgz', archive=True):
"Return data path to `filename`, checking locally first then in the config file."
local_path = URLs.LOCAL_PATH/'data'/filename
if local_path.exists() or local_path.with_suffix(ext).exists(): return local_path
elif archive: return Config.data_arc... | [
"def",
"datapath4file",
"(",
"filename",
",",
"ext",
":",
"str",
"=",
"'.tgz'",
",",
"archive",
"=",
"True",
")",
":",
"local_path",
"=",
"URLs",
".",
"LOCAL_PATH",
"/",
"'data'",
"/",
"filename",
"if",
"local_path",
".",
"exists",
"(",
")",
"or",
"loc... | Return data path to `filename`, checking locally first then in the config file. | [
"Return",
"data",
"path",
"to",
"filename",
"checking",
"locally",
"first",
"then",
"in",
"the",
"config",
"file",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L199-L204 |
21,063 | fastai/fastai | fastai/datasets.py | download_data | def download_data(url:str, fname:PathOrStr=None, data:bool=True, ext:str='.tgz') -> Path:
"Download `url` to destination `fname`."
fname = Path(ifnone(fname, _url2tgz(url, data, ext=ext)))
os.makedirs(fname.parent, exist_ok=True)
if not fname.exists():
print(f'Downloading {url}')
downloa... | python | def download_data(url:str, fname:PathOrStr=None, data:bool=True, ext:str='.tgz') -> Path:
"Download `url` to destination `fname`."
fname = Path(ifnone(fname, _url2tgz(url, data, ext=ext)))
os.makedirs(fname.parent, exist_ok=True)
if not fname.exists():
print(f'Downloading {url}')
downloa... | [
"def",
"download_data",
"(",
"url",
":",
"str",
",",
"fname",
":",
"PathOrStr",
"=",
"None",
",",
"data",
":",
"bool",
"=",
"True",
",",
"ext",
":",
"str",
"=",
"'.tgz'",
")",
"->",
"Path",
":",
"fname",
"=",
"Path",
"(",
"ifnone",
"(",
"fname",
... | Download `url` to destination `fname`. | [
"Download",
"url",
"to",
"destination",
"fname",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L206-L213 |
21,064 | fastai/fastai | fastai/datasets.py | untar_data | def untar_data(url:str, fname:PathOrStr=None, dest:PathOrStr=None, data=True, force_download=False) -> Path:
"Download `url` to `fname` if `dest` doesn't exist, and un-tgz to folder `dest`."
dest = url2path(url, data) if dest is None else Path(dest)/url2name(url)
fname = Path(ifnone(fname, _url2tgz(url, dat... | python | def untar_data(url:str, fname:PathOrStr=None, dest:PathOrStr=None, data=True, force_download=False) -> Path:
"Download `url` to `fname` if `dest` doesn't exist, and un-tgz to folder `dest`."
dest = url2path(url, data) if dest is None else Path(dest)/url2name(url)
fname = Path(ifnone(fname, _url2tgz(url, dat... | [
"def",
"untar_data",
"(",
"url",
":",
"str",
",",
"fname",
":",
"PathOrStr",
"=",
"None",
",",
"dest",
":",
"PathOrStr",
"=",
"None",
",",
"data",
"=",
"True",
",",
"force_download",
"=",
"False",
")",
"->",
"Path",
":",
"dest",
"=",
"url2path",
"(",... | Download `url` to `fname` if `dest` doesn't exist, and un-tgz to folder `dest`. | [
"Download",
"url",
"to",
"fname",
"if",
"dest",
"doesn",
"t",
"exist",
"and",
"un",
"-",
"tgz",
"to",
"folder",
"dest",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L221-L234 |
21,065 | fastai/fastai | fastai/datasets.py | Config.get_key | def get_key(cls, key):
"Get the path to `key` in the config file."
return cls.get().get(key, cls.DEFAULT_CONFIG.get(key,None)) | python | def get_key(cls, key):
"Get the path to `key` in the config file."
return cls.get().get(key, cls.DEFAULT_CONFIG.get(key,None)) | [
"def",
"get_key",
"(",
"cls",
",",
"key",
")",
":",
"return",
"cls",
".",
"get",
"(",
")",
".",
"get",
"(",
"key",
",",
"cls",
".",
"DEFAULT_CONFIG",
".",
"get",
"(",
"key",
",",
"None",
")",
")"
] | Get the path to `key` in the config file. | [
"Get",
"the",
"path",
"to",
"key",
"in",
"the",
"config",
"file",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L140-L142 |
21,066 | fastai/fastai | fastai/datasets.py | Config.get | def get(cls, fpath=None, create_missing=True):
"Retrieve the `Config` in `fpath`."
fpath = _expand_path(fpath or cls.DEFAULT_CONFIG_PATH)
if not fpath.exists() and create_missing: cls.create(fpath)
assert fpath.exists(), f'Could not find config at: {fpath}. Please create'
with op... | python | def get(cls, fpath=None, create_missing=True):
"Retrieve the `Config` in `fpath`."
fpath = _expand_path(fpath or cls.DEFAULT_CONFIG_PATH)
if not fpath.exists() and create_missing: cls.create(fpath)
assert fpath.exists(), f'Could not find config at: {fpath}. Please create'
with op... | [
"def",
"get",
"(",
"cls",
",",
"fpath",
"=",
"None",
",",
"create_missing",
"=",
"True",
")",
":",
"fpath",
"=",
"_expand_path",
"(",
"fpath",
"or",
"cls",
".",
"DEFAULT_CONFIG_PATH",
")",
"if",
"not",
"fpath",
".",
"exists",
"(",
")",
"and",
"create_m... | Retrieve the `Config` in `fpath`. | [
"Retrieve",
"the",
"Config",
"in",
"fpath",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L165-L170 |
21,067 | fastai/fastai | fastai/datasets.py | Config.create | def create(cls, fpath):
"Creates a `Config` from `fpath`."
fpath = _expand_path(fpath)
assert(fpath.suffix == '.yml')
if fpath.exists(): return
fpath.parent.mkdir(parents=True, exist_ok=True)
with open(fpath, 'w') as yaml_file:
yaml.dump(cls.DEFAULT_CONFIG, ya... | python | def create(cls, fpath):
"Creates a `Config` from `fpath`."
fpath = _expand_path(fpath)
assert(fpath.suffix == '.yml')
if fpath.exists(): return
fpath.parent.mkdir(parents=True, exist_ok=True)
with open(fpath, 'w') as yaml_file:
yaml.dump(cls.DEFAULT_CONFIG, ya... | [
"def",
"create",
"(",
"cls",
",",
"fpath",
")",
":",
"fpath",
"=",
"_expand_path",
"(",
"fpath",
")",
"assert",
"(",
"fpath",
".",
"suffix",
"==",
"'.yml'",
")",
"if",
"fpath",
".",
"exists",
"(",
")",
":",
"return",
"fpath",
".",
"parent",
".",
"m... | Creates a `Config` from `fpath`. | [
"Creates",
"a",
"Config",
"from",
"fpath",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/datasets.py#L173-L180 |
21,068 | fastai/fastai | fastai/callbacks/mixup.py | MixUpCallback.on_batch_begin | def on_batch_begin(self, last_input, last_target, train, **kwargs):
"Applies mixup to `last_input` and `last_target` if `train`."
if not train: return
lambd = np.random.beta(self.alpha, self.alpha, last_target.size(0))
lambd = np.concatenate([lambd[:,None], 1-lambd[:,None]], 1).max(1)
... | python | def on_batch_begin(self, last_input, last_target, train, **kwargs):
"Applies mixup to `last_input` and `last_target` if `train`."
if not train: return
lambd = np.random.beta(self.alpha, self.alpha, last_target.size(0))
lambd = np.concatenate([lambd[:,None], 1-lambd[:,None]], 1).max(1)
... | [
"def",
"on_batch_begin",
"(",
"self",
",",
"last_input",
",",
"last_target",
",",
"train",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"train",
":",
"return",
"lambd",
"=",
"np",
".",
"random",
".",
"beta",
"(",
"self",
".",
"alpha",
",",
"self",... | Applies mixup to `last_input` and `last_target` if `train`. | [
"Applies",
"mixup",
"to",
"last_input",
"and",
"last_target",
"if",
"train",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mixup.py#L15-L33 |
21,069 | fastai/fastai | fastai/tabular/transform.py | add_datepart | def add_datepart(df:DataFrame, field_name:str, prefix:str=None, drop:bool=True, time:bool=False):
"Helper function that adds columns relevant to a date in the column `field_name` of `df`."
make_date(df, field_name)
field = df[field_name]
prefix = ifnone(prefix, re.sub('[Dd]ate$', '', field_name))
at... | python | def add_datepart(df:DataFrame, field_name:str, prefix:str=None, drop:bool=True, time:bool=False):
"Helper function that adds columns relevant to a date in the column `field_name` of `df`."
make_date(df, field_name)
field = df[field_name]
prefix = ifnone(prefix, re.sub('[Dd]ate$', '', field_name))
at... | [
"def",
"add_datepart",
"(",
"df",
":",
"DataFrame",
",",
"field_name",
":",
"str",
",",
"prefix",
":",
"str",
"=",
"None",
",",
"drop",
":",
"bool",
"=",
"True",
",",
"time",
":",
"bool",
"=",
"False",
")",
":",
"make_date",
"(",
"df",
",",
"field_... | Helper function that adds columns relevant to a date in the column `field_name` of `df`. | [
"Helper",
"function",
"that",
"adds",
"columns",
"relevant",
"to",
"a",
"date",
"in",
"the",
"column",
"field_name",
"of",
"df",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L55-L66 |
21,070 | fastai/fastai | fastai/tabular/transform.py | cont_cat_split | def cont_cat_split(df, max_card=20, dep_var=None)->Tuple[List,List]:
"Helper function that returns column names of cont and cat variables from given df."
cont_names, cat_names = [], []
for label in df:
if label == dep_var: continue
if df[label].dtype == int and df[label].unique().shape[0] > ... | python | def cont_cat_split(df, max_card=20, dep_var=None)->Tuple[List,List]:
"Helper function that returns column names of cont and cat variables from given df."
cont_names, cat_names = [], []
for label in df:
if label == dep_var: continue
if df[label].dtype == int and df[label].unique().shape[0] > ... | [
"def",
"cont_cat_split",
"(",
"df",
",",
"max_card",
"=",
"20",
",",
"dep_var",
"=",
"None",
")",
"->",
"Tuple",
"[",
"List",
",",
"List",
"]",
":",
"cont_names",
",",
"cat_names",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"label",
"in",
"df",
":",
"i... | Helper function that returns column names of cont and cat variables from given df. | [
"Helper",
"function",
"that",
"returns",
"column",
"names",
"of",
"cont",
"and",
"cat",
"variables",
"from",
"given",
"df",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L106-L113 |
21,071 | fastai/fastai | fastai/tabular/transform.py | Categorify.apply_train | def apply_train(self, df:DataFrame):
"Transform `self.cat_names` columns in categorical."
self.categories = {}
for n in self.cat_names:
df.loc[:,n] = df.loc[:,n].astype('category').cat.as_ordered()
self.categories[n] = df[n].cat.categories | python | def apply_train(self, df:DataFrame):
"Transform `self.cat_names` columns in categorical."
self.categories = {}
for n in self.cat_names:
df.loc[:,n] = df.loc[:,n].astype('category').cat.as_ordered()
self.categories[n] = df[n].cat.categories | [
"def",
"apply_train",
"(",
"self",
",",
"df",
":",
"DataFrame",
")",
":",
"self",
".",
"categories",
"=",
"{",
"}",
"for",
"n",
"in",
"self",
".",
"cat_names",
":",
"df",
".",
"loc",
"[",
":",
",",
"n",
"]",
"=",
"df",
".",
"loc",
"[",
":",
"... | Transform `self.cat_names` columns in categorical. | [
"Transform",
"self",
".",
"cat_names",
"columns",
"in",
"categorical",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L135-L140 |
21,072 | fastai/fastai | fastai/tabular/transform.py | Normalize.apply_train | def apply_train(self, df:DataFrame):
"Compute the means and stds of `self.cont_names` columns to normalize them."
self.means,self.stds = {},{}
for n in self.cont_names:
assert is_numeric_dtype(df[n]), (f"""Cannot normalize '{n}' column as it isn't numerical.
Are you s... | python | def apply_train(self, df:DataFrame):
"Compute the means and stds of `self.cont_names` columns to normalize them."
self.means,self.stds = {},{}
for n in self.cont_names:
assert is_numeric_dtype(df[n]), (f"""Cannot normalize '{n}' column as it isn't numerical.
Are you s... | [
"def",
"apply_train",
"(",
"self",
",",
"df",
":",
"DataFrame",
")",
":",
"self",
".",
"means",
",",
"self",
".",
"stds",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"n",
"in",
"self",
".",
"cont_names",
":",
"assert",
"is_numeric_dtype",
"(",
"df",
"[",
... | Compute the means and stds of `self.cont_names` columns to normalize them. | [
"Compute",
"the",
"means",
"and",
"stds",
"of",
"self",
".",
"cont_names",
"columns",
"to",
"normalize",
"them",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/transform.py#L183-L190 |
21,073 | fastai/fastai | fastai/tabular/data.py | def_emb_sz | def def_emb_sz(classes, n, sz_dict=None):
"Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`."
sz_dict = ifnone(sz_dict, {})
n_cat = len(classes[n])
sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb
return n_cat,sz | python | def def_emb_sz(classes, n, sz_dict=None):
"Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`."
sz_dict = ifnone(sz_dict, {})
n_cat = len(classes[n])
sz = sz_dict.get(n, int(emb_sz_rule(n_cat))) # rule of thumb
return n_cat,sz | [
"def",
"def_emb_sz",
"(",
"classes",
",",
"n",
",",
"sz_dict",
"=",
"None",
")",
":",
"sz_dict",
"=",
"ifnone",
"(",
"sz_dict",
",",
"{",
"}",
")",
"n_cat",
"=",
"len",
"(",
"classes",
"[",
"n",
"]",
")",
"sz",
"=",
"sz_dict",
".",
"get",
"(",
... | Pick an embedding size for `n` depending on `classes` if not given in `sz_dict`. | [
"Pick",
"an",
"embedding",
"size",
"for",
"n",
"depending",
"on",
"classes",
"if",
"not",
"given",
"in",
"sz_dict",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/data.py#L17-L22 |
21,074 | fastai/fastai | fastai/tabular/data.py | tabular_learner | def tabular_learner(data:DataBunch, layers:Collection[int], emb_szs:Dict[str,int]=None, metrics=None,
ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True, **learn_kwargs):
"Get a `Learner` using `data`, with `metrics`, including a `TabularModel` created using the remaining ... | python | def tabular_learner(data:DataBunch, layers:Collection[int], emb_szs:Dict[str,int]=None, metrics=None,
ps:Collection[float]=None, emb_drop:float=0., y_range:OptRange=None, use_bn:bool=True, **learn_kwargs):
"Get a `Learner` using `data`, with `metrics`, including a `TabularModel` created using the remaining ... | [
"def",
"tabular_learner",
"(",
"data",
":",
"DataBunch",
",",
"layers",
":",
"Collection",
"[",
"int",
"]",
",",
"emb_szs",
":",
"Dict",
"[",
"str",
",",
"int",
"]",
"=",
"None",
",",
"metrics",
"=",
"None",
",",
"ps",
":",
"Collection",
"[",
"float"... | Get a `Learner` using `data`, with `metrics`, including a `TabularModel` created using the remaining params. | [
"Get",
"a",
"Learner",
"using",
"data",
"with",
"metrics",
"including",
"a",
"TabularModel",
"created",
"using",
"the",
"remaining",
"params",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/data.py#L170-L176 |
21,075 | fastai/fastai | fastai/tabular/data.py | TabularDataBunch.from_df | def from_df(cls, path, df:DataFrame, dep_var:str, valid_idx:Collection[int], procs:OptTabTfms=None,
cat_names:OptStrList=None, cont_names:OptStrList=None, classes:Collection=None,
test_df=None, bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callab... | python | def from_df(cls, path, df:DataFrame, dep_var:str, valid_idx:Collection[int], procs:OptTabTfms=None,
cat_names:OptStrList=None, cont_names:OptStrList=None, classes:Collection=None,
test_df=None, bs:int=64, val_bs:int=None, num_workers:int=defaults.cpus, dl_tfms:Optional[Collection[Callab... | [
"def",
"from_df",
"(",
"cls",
",",
"path",
",",
"df",
":",
"DataFrame",
",",
"dep_var",
":",
"str",
",",
"valid_idx",
":",
"Collection",
"[",
"int",
"]",
",",
"procs",
":",
"OptTabTfms",
"=",
"None",
",",
"cat_names",
":",
"OptStrList",
"=",
"None",
... | Create a `DataBunch` from `df` and `valid_idx` with `dep_var`. `kwargs` are passed to `DataBunch.create`. | [
"Create",
"a",
"DataBunch",
"from",
"df",
"and",
"valid_idx",
"with",
"dep_var",
".",
"kwargs",
"are",
"passed",
"to",
"DataBunch",
".",
"create",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/data.py#L87-L101 |
21,076 | fastai/fastai | fastai/tabular/data.py | TabularList.get_emb_szs | def get_emb_szs(self, sz_dict=None):
"Return the default embedding sizes suitable for this data or takes the ones in `sz_dict`."
return [def_emb_sz(self.classes, n, sz_dict) for n in self.cat_names] | python | def get_emb_szs(self, sz_dict=None):
"Return the default embedding sizes suitable for this data or takes the ones in `sz_dict`."
return [def_emb_sz(self.classes, n, sz_dict) for n in self.cat_names] | [
"def",
"get_emb_szs",
"(",
"self",
",",
"sz_dict",
"=",
"None",
")",
":",
"return",
"[",
"def_emb_sz",
"(",
"self",
".",
"classes",
",",
"n",
",",
"sz_dict",
")",
"for",
"n",
"in",
"self",
".",
"cat_names",
"]"
] | Return the default embedding sizes suitable for this data or takes the ones in `sz_dict`. | [
"Return",
"the",
"default",
"embedding",
"sizes",
"suitable",
"for",
"this",
"data",
"or",
"takes",
"the",
"ones",
"in",
"sz_dict",
"."
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/tabular/data.py#L129-L131 |
21,077 | fastai/fastai | courses/dl2/imdb_scripts/predict_with_classifier.py | load_model | def load_model(itos_filename, classifier_filename, num_classes):
"""Load the classifier and int to string mapping
Args:
itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
classifier_filename (str): The filename of the trained classifier
Returns:
... | python | def load_model(itos_filename, classifier_filename, num_classes):
"""Load the classifier and int to string mapping
Args:
itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
classifier_filename (str): The filename of the trained classifier
Returns:
... | [
"def",
"load_model",
"(",
"itos_filename",
",",
"classifier_filename",
",",
"num_classes",
")",
":",
"# load the int to string mapping file",
"itos",
"=",
"pickle",
".",
"load",
"(",
"Path",
"(",
"itos_filename",
")",
".",
"open",
"(",
"'rb'",
")",
")",
"# turn ... | Load the classifier and int to string mapping
Args:
itos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)
classifier_filename (str): The filename of the trained classifier
Returns:
string to int mapping, trained classifer model | [
"Load",
"the",
"classifier",
"and",
"int",
"to",
"string",
"mapping"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/courses/dl2/imdb_scripts/predict_with_classifier.py#L6-L38 |
21,078 | fastai/fastai | courses/dl2/imdb_scripts/predict_with_classifier.py | predict_text | def predict_text(stoi, model, text):
"""Do the actual prediction on the text using the
model and mapping files passed
"""
# prefix text with tokens:
# xbos: beginning of sentence
# xfld 1: we are using a single field here
input_str = 'xbos xfld 1 ' + text
# predictions are done... | python | def predict_text(stoi, model, text):
"""Do the actual prediction on the text using the
model and mapping files passed
"""
# prefix text with tokens:
# xbos: beginning of sentence
# xfld 1: we are using a single field here
input_str = 'xbos xfld 1 ' + text
# predictions are done... | [
"def",
"predict_text",
"(",
"stoi",
",",
"model",
",",
"text",
")",
":",
"# prefix text with tokens:",
"# xbos: beginning of sentence",
"# xfld 1: we are using a single field here",
"input_str",
"=",
"'xbos xfld 1 '",
"+",
"text",
"# predictions are done on arrays of input.",... | Do the actual prediction on the text using the
model and mapping files passed | [
"Do",
"the",
"actual",
"prediction",
"on",
"the",
"text",
"using",
"the",
"model",
"and",
"mapping",
"files",
"passed"
] | 9fb84a5cdefe5a766cdb792b8f5d8971737b7e67 | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/courses/dl2/imdb_scripts/predict_with_classifier.py#L64-L100 |
21,079 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | _make_w3c_caps | def _make_w3c_caps(caps):
"""Makes a W3C alwaysMatch capabilities object.
Filters out capability names that are not in the W3C spec. Spec-compliant
drivers will reject requests containing unknown capability names.
Moves the Firefox profile, if present, from the old location to the new Firefox
opti... | python | def _make_w3c_caps(caps):
"""Makes a W3C alwaysMatch capabilities object.
Filters out capability names that are not in the W3C spec. Spec-compliant
drivers will reject requests containing unknown capability names.
Moves the Firefox profile, if present, from the old location to the new Firefox
opti... | [
"def",
"_make_w3c_caps",
"(",
"caps",
")",
":",
"caps",
"=",
"copy",
".",
"deepcopy",
"(",
"caps",
")",
"profile",
"=",
"caps",
".",
"get",
"(",
"'firefox_profile'",
")",
"always_match",
"=",
"{",
"}",
"if",
"caps",
".",
"get",
"(",
"'proxy'",
")",
"... | Makes a W3C alwaysMatch capabilities object.
Filters out capability names that are not in the W3C spec. Spec-compliant
drivers will reject requests containing unknown capability names.
Moves the Firefox profile, if present, from the old location to the new Firefox
options object.
:Args:
- ca... | [
"Makes",
"a",
"W3C",
"alwaysMatch",
"capabilities",
"object",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L65-L95 |
21,080 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.start_session | def start_session(self, capabilities, browser_profile=None):
"""
Creates a new session with the desired capabilities.
:Args:
- browser_name - The name of the browser to request.
- version - Which browser version to request.
- platform - Which platform to request the b... | python | def start_session(self, capabilities, browser_profile=None):
"""
Creates a new session with the desired capabilities.
:Args:
- browser_name - The name of the browser to request.
- version - Which browser version to request.
- platform - Which platform to request the b... | [
"def",
"start_session",
"(",
"self",
",",
"capabilities",
",",
"browser_profile",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"capabilities",
",",
"dict",
")",
":",
"raise",
"InvalidArgumentException",
"(",
"\"Capabilities must be a dictionary\"",
")",
... | Creates a new session with the desired capabilities.
:Args:
- browser_name - The name of the browser to request.
- version - Which browser version to request.
- platform - Which platform to request the browser on.
- javascript_enabled - Whether the new session should support... | [
"Creates",
"a",
"new",
"session",
"with",
"the",
"desired",
"capabilities",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L228-L262 |
21,081 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.create_web_element | def create_web_element(self, element_id):
"""Creates a web element with the specified `element_id`."""
return self._web_element_cls(self, element_id, w3c=self.w3c) | python | def create_web_element(self, element_id):
"""Creates a web element with the specified `element_id`."""
return self._web_element_cls(self, element_id, w3c=self.w3c) | [
"def",
"create_web_element",
"(",
"self",
",",
"element_id",
")",
":",
"return",
"self",
".",
"_web_element_cls",
"(",
"self",
",",
"element_id",
",",
"w3c",
"=",
"self",
".",
"w3c",
")"
] | Creates a web element with the specified `element_id`. | [
"Creates",
"a",
"web",
"element",
"with",
"the",
"specified",
"element_id",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L277-L279 |
21,082 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.execute | def execute(self, driver_command, params=None):
"""
Sends a command to be executed by a command.CommandExecutor.
:Args:
- driver_command: The name of the command to execute as a string.
- params: A dictionary of named parameters to send with the command.
:Returns:
... | python | def execute(self, driver_command, params=None):
"""
Sends a command to be executed by a command.CommandExecutor.
:Args:
- driver_command: The name of the command to execute as a string.
- params: A dictionary of named parameters to send with the command.
:Returns:
... | [
"def",
"execute",
"(",
"self",
",",
"driver_command",
",",
"params",
"=",
"None",
")",
":",
"if",
"self",
".",
"session_id",
"is",
"not",
"None",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"'sessionId'",
":",
"self",
".",
"session_id",
"}",
... | Sends a command to be executed by a command.CommandExecutor.
:Args:
- driver_command: The name of the command to execute as a string.
- params: A dictionary of named parameters to send with the command.
:Returns:
The command's JSON response loaded into a dictionary object. | [
"Sends",
"a",
"command",
"to",
"be",
"executed",
"by",
"a",
"command",
".",
"CommandExecutor",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L298-L324 |
21,083 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.find_element_by_link_text | def find_element_by_link_text(self, link_text):
"""
Finds an element by link text.
:Args:
- link_text: The text of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't... | python | def find_element_by_link_text(self, link_text):
"""
Finds an element by link text.
:Args:
- link_text: The text of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't... | [
"def",
"find_element_by_link_text",
"(",
"self",
",",
"link_text",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"LINK_TEXT",
",",
"value",
"=",
"link_text",
")"
] | Finds an element by link text.
:Args:
- link_text: The text of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = dr... | [
"Finds",
"an",
"element",
"by",
"link",
"text",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L419-L437 |
21,084 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.find_elements_by_link_text | def find_elements_by_link_text(self, text):
"""
Finds elements by link text.
:Args:
- link_text: The text of the elements to be found.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
... | python | def find_elements_by_link_text(self, text):
"""
Finds elements by link text.
:Args:
- link_text: The text of the elements to be found.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
... | [
"def",
"find_elements_by_link_text",
"(",
"self",
",",
"text",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"LINK_TEXT",
",",
"value",
"=",
"text",
")"
] | Finds elements by link text.
:Args:
- link_text: The text of the elements to be found.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = driver.find_elements_by_link_tex... | [
"Finds",
"elements",
"by",
"link",
"text",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L439-L455 |
21,085 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.find_element_by_partial_link_text | def find_element_by_partial_link_text(self, link_text):
"""
Finds an element by a partial match of its link text.
:Args:
- link_text: The text of the element to partially match on.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuc... | python | def find_element_by_partial_link_text(self, link_text):
"""
Finds an element by a partial match of its link text.
:Args:
- link_text: The text of the element to partially match on.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuc... | [
"def",
"find_element_by_partial_link_text",
"(",
"self",
",",
"link_text",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"PARTIAL_LINK_TEXT",
",",
"value",
"=",
"link_text",
")"
] | Finds an element by a partial match of its link text.
:Args:
- link_text: The text of the element to partially match on.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
... | [
"Finds",
"an",
"element",
"by",
"a",
"partial",
"match",
"of",
"its",
"link",
"text",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L457-L475 |
21,086 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.find_elements_by_partial_link_text | def find_elements_by_partial_link_text(self, link_text):
"""
Finds elements by a partial match of their link text.
:Args:
- link_text: The text of the element to partial match on.
:Returns:
- list of webelement - a list with elements if any was found. an
e... | python | def find_elements_by_partial_link_text(self, link_text):
"""
Finds elements by a partial match of their link text.
:Args:
- link_text: The text of the element to partial match on.
:Returns:
- list of webelement - a list with elements if any was found. an
e... | [
"def",
"find_elements_by_partial_link_text",
"(",
"self",
",",
"link_text",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"PARTIAL_LINK_TEXT",
",",
"value",
"=",
"link_text",
")"
] | Finds elements by a partial match of their link text.
:Args:
- link_text: The text of the element to partial match on.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = ... | [
"Finds",
"elements",
"by",
"a",
"partial",
"match",
"of",
"their",
"link",
"text",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L477-L493 |
21,087 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.find_elements_by_name | def find_elements_by_name(self, name):
"""
Finds elements by name.
:Args:
- name: The name of the elements to find.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
... | python | def find_elements_by_name(self, name):
"""
Finds elements by name.
:Args:
- name: The name of the elements to find.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
... | [
"def",
"find_elements_by_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"NAME",
",",
"value",
"=",
"name",
")"
] | Finds elements by name.
:Args:
- name: The name of the elements to find.
:Returns:
- list of webelement - a list with elements if any was found. an
empty list if not
:Usage:
::
elements = driver.find_elements_by_name('foo') | [
"Finds",
"elements",
"by",
"name",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L515-L531 |
21,088 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.find_element_by_tag_name | def find_element_by_tag_name(self, name):
"""
Finds an element by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
... | python | def find_element_by_tag_name(self, name):
"""
Finds an element by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
... | [
"def",
"find_element_by_tag_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"TAG_NAME",
",",
"value",
"=",
"name",
")"
] | Finds an element by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driver.fi... | [
"Finds",
"an",
"element",
"by",
"tag",
"name",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L533-L551 |
21,089 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.find_elements_by_tag_name | def find_elements_by_tag_name(self, name):
"""
Finds elements by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
... | python | def find_elements_by_tag_name(self, name):
"""
Finds elements by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
... | [
"def",
"find_elements_by_tag_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"TAG_NAME",
",",
"value",
"=",
"name",
")"
] | Finds elements by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_tag_name('h1') | [
"Finds",
"elements",
"by",
"tag",
"name",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L553-L569 |
21,090 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.find_element_by_class_name | def find_element_by_class_name(self, name):
"""
Finds an element by class name.
:Args:
- name: The class name of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found... | python | def find_element_by_class_name(self, name):
"""
Finds an element by class name.
:Args:
- name: The class name of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found... | [
"def",
"find_element_by_class_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"CLASS_NAME",
",",
"value",
"=",
"name",
")"
] | Finds an element by class name.
:Args:
- name: The class name of the element to find.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
element = driv... | [
"Finds",
"an",
"element",
"by",
"class",
"name",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L571-L589 |
21,091 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.find_elements_by_class_name | def find_elements_by_class_name(self, name):
"""
Finds elements by class name.
:Args:
- name: The class name of the elements to find.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
... | python | def find_elements_by_class_name(self, name):
"""
Finds elements by class name.
:Args:
- name: The class name of the elements to find.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
... | [
"def",
"find_elements_by_class_name",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"CLASS_NAME",
",",
"value",
"=",
"name",
")"
] | Finds elements by class name.
:Args:
- name: The class name of the elements to find.
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_class_name... | [
"Finds",
"elements",
"by",
"class",
"name",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L591-L607 |
21,092 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.find_element_by_css_selector | def find_element_by_css_selector(self, css_selector):
"""
Finds an element by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the ... | python | def find_element_by_css_selector(self, css_selector):
"""
Finds an element by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the ... | [
"def",
"find_element_by_css_selector",
"(",
"self",
",",
"css_selector",
")",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"value",
"=",
"css_selector",
")"
] | Finds an element by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
::
elem... | [
"Finds",
"an",
"element",
"by",
"css",
"selector",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L609-L627 |
21,093 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.find_elements_by_css_selector | def find_elements_by_css_selector(self, css_selector):
"""
Finds elements by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:... | python | def find_elements_by_css_selector(self, css_selector):
"""
Finds elements by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:... | [
"def",
"find_elements_by_css_selector",
"(",
"self",
",",
"css_selector",
")",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"value",
"=",
"css_selector",
")"
] | Finds elements by css selector.
:Args:
- css_selector - CSS selector string, ex: 'a.nav#home'
:Returns:
- list of WebElement - a list with elements if any was found. An
empty list if not
:Usage:
::
elements = driver.find_elements_by_c... | [
"Finds",
"elements",
"by",
"css",
"selector",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L629-L645 |
21,094 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.quit | def quit(self):
"""
Quits the driver and closes every associated window.
:Usage:
::
driver.quit()
"""
try:
self.execute(Command.QUIT)
finally:
self.stop_client()
self.command_executor.close() | python | def quit(self):
"""
Quits the driver and closes every associated window.
:Usage:
::
driver.quit()
"""
try:
self.execute(Command.QUIT)
finally:
self.stop_client()
self.command_executor.close() | [
"def",
"quit",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"QUIT",
")",
"finally",
":",
"self",
".",
"stop_client",
"(",
")",
"self",
".",
"command_executor",
".",
"close",
"(",
")"
] | Quits the driver and closes every associated window.
:Usage:
::
driver.quit() | [
"Quits",
"the",
"driver",
"and",
"closes",
"every",
"associated",
"window",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L731-L744 |
21,095 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.current_window_handle | def current_window_handle(self):
"""
Returns the handle of the current window.
:Usage:
::
driver.current_window_handle
"""
if self.w3c:
return self.execute(Command.W3C_GET_CURRENT_WINDOW_HANDLE)['value']
else:
return s... | python | def current_window_handle(self):
"""
Returns the handle of the current window.
:Usage:
::
driver.current_window_handle
"""
if self.w3c:
return self.execute(Command.W3C_GET_CURRENT_WINDOW_HANDLE)['value']
else:
return s... | [
"def",
"current_window_handle",
"(",
"self",
")",
":",
"if",
"self",
".",
"w3c",
":",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"W3C_GET_CURRENT_WINDOW_HANDLE",
")",
"[",
"'value'",
"]",
"else",
":",
"return",
"self",
".",
"execute",
"(",
"Com... | Returns the handle of the current window.
:Usage:
::
driver.current_window_handle | [
"Returns",
"the",
"handle",
"of",
"the",
"current",
"window",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L747-L759 |
21,096 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.window_handles | def window_handles(self):
"""
Returns the handles of all windows within the current session.
:Usage:
::
driver.window_handles
"""
if self.w3c:
return self.execute(Command.W3C_GET_WINDOW_HANDLES)['value']
else:
return s... | python | def window_handles(self):
"""
Returns the handles of all windows within the current session.
:Usage:
::
driver.window_handles
"""
if self.w3c:
return self.execute(Command.W3C_GET_WINDOW_HANDLES)['value']
else:
return s... | [
"def",
"window_handles",
"(",
"self",
")",
":",
"if",
"self",
".",
"w3c",
":",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"W3C_GET_WINDOW_HANDLES",
")",
"[",
"'value'",
"]",
"else",
":",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
... | Returns the handles of all windows within the current session.
:Usage:
::
driver.window_handles | [
"Returns",
"the",
"handles",
"of",
"all",
"windows",
"within",
"the",
"current",
"session",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L762-L774 |
21,097 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.maximize_window | def maximize_window(self):
"""
Maximizes the current window that webdriver is using
"""
params = None
command = Command.W3C_MAXIMIZE_WINDOW
if not self.w3c:
command = Command.MAXIMIZE_WINDOW
params = {'windowHandle': 'current'}
self.execute... | python | def maximize_window(self):
"""
Maximizes the current window that webdriver is using
"""
params = None
command = Command.W3C_MAXIMIZE_WINDOW
if not self.w3c:
command = Command.MAXIMIZE_WINDOW
params = {'windowHandle': 'current'}
self.execute... | [
"def",
"maximize_window",
"(",
"self",
")",
":",
"params",
"=",
"None",
"command",
"=",
"Command",
".",
"W3C_MAXIMIZE_WINDOW",
"if",
"not",
"self",
".",
"w3c",
":",
"command",
"=",
"Command",
".",
"MAXIMIZE_WINDOW",
"params",
"=",
"{",
"'windowHandle'",
":",... | Maximizes the current window that webdriver is using | [
"Maximizes",
"the",
"current",
"window",
"that",
"webdriver",
"is",
"using"
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L776-L785 |
21,098 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.get_cookie | def get_cookie(self, name):
"""
Get a single cookie by name. Returns the cookie if found, None if not.
:Usage:
::
driver.get_cookie('my_cookie')
"""
if self.w3c:
try:
return self.execute(Command.GET_COOKIE, {'name': name})... | python | def get_cookie(self, name):
"""
Get a single cookie by name. Returns the cookie if found, None if not.
:Usage:
::
driver.get_cookie('my_cookie')
"""
if self.w3c:
try:
return self.execute(Command.GET_COOKIE, {'name': name})... | [
"def",
"get_cookie",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"w3c",
":",
"try",
":",
"return",
"self",
".",
"execute",
"(",
"Command",
".",
"GET_COOKIE",
",",
"{",
"'name'",
":",
"name",
"}",
")",
"[",
"'value'",
"]",
"except",
"NoSu... | Get a single cookie by name. Returns the cookie if found, None if not.
:Usage:
::
driver.get_cookie('my_cookie') | [
"Get",
"a",
"single",
"cookie",
"by",
"name",
".",
"Returns",
"the",
"cookie",
"if",
"found",
"None",
"if",
"not",
"."
] | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L865-L884 |
21,099 | SeleniumHQ/selenium | py/selenium/webdriver/remote/webdriver.py | WebDriver.implicitly_wait | def implicitly_wait(self, time_to_wait):
"""
Sets a sticky timeout to implicitly wait for an element to be found,
or a command to complete. This method only needs to be called one
time per session. To set the timeout for calls to
execute_async_script, see set_script_time... | python | def implicitly_wait(self, time_to_wait):
"""
Sets a sticky timeout to implicitly wait for an element to be found,
or a command to complete. This method only needs to be called one
time per session. To set the timeout for calls to
execute_async_script, see set_script_time... | [
"def",
"implicitly_wait",
"(",
"self",
",",
"time_to_wait",
")",
":",
"if",
"self",
".",
"w3c",
":",
"self",
".",
"execute",
"(",
"Command",
".",
"SET_TIMEOUTS",
",",
"{",
"'implicit'",
":",
"int",
"(",
"float",
"(",
"time_to_wait",
")",
"*",
"1000",
"... | Sets a sticky timeout to implicitly wait for an element to be found,
or a command to complete. This method only needs to be called one
time per session. To set the timeout for calls to
execute_async_script, see set_script_timeout.
:Args:
- time_to_wait: Amount of time ... | [
"Sets",
"a",
"sticky",
"timeout",
"to",
"implicitly",
"wait",
"for",
"an",
"element",
"to",
"be",
"found",
"or",
"a",
"command",
"to",
"complete",
".",
"This",
"method",
"only",
"needs",
"to",
"be",
"called",
"one",
"time",
"per",
"session",
".",
"To",
... | df40c28b41d4b3953f90eaff84838a9ac052b84a | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L925-L945 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.