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, len(data.vocab.itos), config=config, drop_mult=drop_mult) meta = _model_meta[arch] learn = LanguageLearner(data, model, split_func=meta['split_lm'], **learn_kwargs) if pretrained: if 'url' not in meta: warn("There are no pretrained weights for that architecture yet!") return learn model_path = untar_data(meta['url'], data=False) fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']] learn.load_pretrained(*fnames) learn.freeze() if pretrained_fnames is not None: fnames = [learn.path/learn.model_dir/f'{fn}.{ext}' for fn,ext in zip(pretrained_fnames, ['pth', 'pkl'])] learn.load_pretrained(*fnames) learn.freeze() return learn
python
def language_model_learner(data:DataBunch, arch, config:dict=None, drop_mult:float=1., pretrained:bool=True, pretrained_fnames:OptStrTuple=None, **learn_kwargs) -> 'LanguageLearner': "Create a `Learner` with a language model from `data` and `arch`." model = get_language_model(arch, len(data.vocab.itos), config=config, drop_mult=drop_mult) meta = _model_meta[arch] learn = LanguageLearner(data, model, split_func=meta['split_lm'], **learn_kwargs) if pretrained: if 'url' not in meta: warn("There are no pretrained weights for that architecture yet!") return learn model_path = untar_data(meta['url'], data=False) fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']] learn.load_pretrained(*fnames) learn.freeze() if pretrained_fnames is not None: fnames = [learn.path/learn.model_dir/f'{fn}.{ext}' for fn,ext in zip(pretrained_fnames, ['pth', 'pkl'])] learn.load_pretrained(*fnames) learn.freeze() return learn
[ "def", "language_model_learner", "(", "data", ":", "DataBunch", ",", "arch", ",", "config", ":", "dict", "=", "None", ",", "drop_mult", ":", "float", "=", "1.", ",", "pretrained", ":", "bool", "=", "True", ",", "pretrained_fnames", ":", "OptStrTuple", "=", "None", ",", "*", "*", "learn_kwargs", ")", "->", "'LanguageLearner'", ":", "model", "=", "get_language_model", "(", "arch", ",", "len", "(", "data", ".", "vocab", ".", "itos", ")", ",", "config", "=", "config", ",", "drop_mult", "=", "drop_mult", ")", "meta", "=", "_model_meta", "[", "arch", "]", "learn", "=", "LanguageLearner", "(", "data", ",", "model", ",", "split_func", "=", "meta", "[", "'split_lm'", "]", ",", "*", "*", "learn_kwargs", ")", "if", "pretrained", ":", "if", "'url'", "not", "in", "meta", ":", "warn", "(", "\"There are no pretrained weights for that architecture yet!\"", ")", "return", "learn", "model_path", "=", "untar_data", "(", "meta", "[", "'url'", "]", ",", "data", "=", "False", ")", "fnames", "=", "[", "list", "(", "model_path", ".", "glob", "(", "f'*.{ext}'", ")", ")", "[", "0", "]", "for", "ext", "in", "[", "'pth'", ",", "'pkl'", "]", "]", "learn", ".", "load_pretrained", "(", "*", "fnames", ")", "learn", ".", "freeze", "(", ")", "if", "pretrained_fnames", "is", "not", "None", ":", "fnames", "=", "[", "learn", ".", "path", "/", "learn", ".", "model_dir", "/", "f'{fn}.{ext}'", "for", "fn", ",", "ext", "in", "zip", "(", "pretrained_fnames", ",", "[", "'pth'", ",", "'pkl'", "]", ")", "]", "learn", ".", "load_pretrained", "(", "*", "fnames", ")", "learn", ".", "freeze", "(", ")", "return", "learn" ]
Create a `Learner` with a language model from `data` and `arch`.
[ "Create", "a", "Learner", "with", "a", "language", "model", "from", "data", "and", "arch", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L201-L219
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 its `config`, maybe `pretrained`." meta = _model_meta[arch] config = ifnone(config, meta['config_clas'].copy()) for k in config.keys(): if k.endswith('_p'): config[k] *= drop_mult if lin_ftrs is None: lin_ftrs = [50] if ps is None: ps = [0.1]*len(lin_ftrs) layers = [config[meta['hid_name']] * 3] + lin_ftrs + [n_class] ps = [config.pop('output_p')] + ps init = config.pop('init') if 'init' in config else None encoder = MultiBatchEncoder(bptt, max_len, arch(vocab_sz, **config), pad_idx=pad_idx) model = SequentialRNN(encoder, PoolingLinearClassifier(layers, ps)) return model if init is None else model.apply(init)
python
def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None, drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None, pad_idx:int=1) -> nn.Module: "Create a text classifier from `arch` and its `config`, maybe `pretrained`." meta = _model_meta[arch] config = ifnone(config, meta['config_clas'].copy()) for k in config.keys(): if k.endswith('_p'): config[k] *= drop_mult if lin_ftrs is None: lin_ftrs = [50] if ps is None: ps = [0.1]*len(lin_ftrs) layers = [config[meta['hid_name']] * 3] + lin_ftrs + [n_class] ps = [config.pop('output_p')] + ps init = config.pop('init') if 'init' in config else None encoder = MultiBatchEncoder(bptt, max_len, arch(vocab_sz, **config), pad_idx=pad_idx) model = SequentialRNN(encoder, PoolingLinearClassifier(layers, ps)) return model if init is None else model.apply(init)
[ "def", "get_text_classifier", "(", "arch", ":", "Callable", ",", "vocab_sz", ":", "int", ",", "n_class", ":", "int", ",", "bptt", ":", "int", "=", "70", ",", "max_len", ":", "int", "=", "20", "*", "70", ",", "config", ":", "dict", "=", "None", ",", "drop_mult", ":", "float", "=", "1.", ",", "lin_ftrs", ":", "Collection", "[", "int", "]", "=", "None", ",", "ps", ":", "Collection", "[", "float", "]", "=", "None", ",", "pad_idx", ":", "int", "=", "1", ")", "->", "nn", ".", "Module", ":", "meta", "=", "_model_meta", "[", "arch", "]", "config", "=", "ifnone", "(", "config", ",", "meta", "[", "'config_clas'", "]", ".", "copy", "(", ")", ")", "for", "k", "in", "config", ".", "keys", "(", ")", ":", "if", "k", ".", "endswith", "(", "'_p'", ")", ":", "config", "[", "k", "]", "*=", "drop_mult", "if", "lin_ftrs", "is", "None", ":", "lin_ftrs", "=", "[", "50", "]", "if", "ps", "is", "None", ":", "ps", "=", "[", "0.1", "]", "*", "len", "(", "lin_ftrs", ")", "layers", "=", "[", "config", "[", "meta", "[", "'hid_name'", "]", "]", "*", "3", "]", "+", "lin_ftrs", "+", "[", "n_class", "]", "ps", "=", "[", "config", ".", "pop", "(", "'output_p'", ")", "]", "+", "ps", "init", "=", "config", ".", "pop", "(", "'init'", ")", "if", "'init'", "in", "config", "else", "None", "encoder", "=", "MultiBatchEncoder", "(", "bptt", ",", "max_len", ",", "arch", "(", "vocab_sz", ",", "*", "*", "config", ")", ",", "pad_idx", "=", "pad_idx", ")", "model", "=", "SequentialRNN", "(", "encoder", ",", "PoolingLinearClassifier", "(", "layers", ",", "ps", ")", ")", "return", "model", "if", "init", "is", "None", "else", "model", ".", "apply", "(", "init", ")" ]
Create a text classifier from `arch` and its `config`, maybe `pretrained`.
[ "Create", "a", "text", "classifier", "from", "arch", "and", "its", "config", "maybe", "pretrained", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L269-L284
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': "Create a `Learner` with a text classifier from `data` and `arch`." model = get_text_classifier(arch, len(data.vocab.itos), data.c, bptt=bptt, max_len=max_len, config=config, drop_mult=drop_mult, lin_ftrs=lin_ftrs, ps=ps) meta = _model_meta[arch] learn = RNNLearner(data, model, split_func=meta['split_clas'], **learn_kwargs) if pretrained: if 'url' not in meta: warn("There are no pretrained weights for that architecture yet!") return learn model_path = untar_data(meta['url'], data=False) fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']] learn.load_pretrained(*fnames, strict=False) learn.freeze() return learn
python
def text_classifier_learner(data:DataBunch, arch:Callable, bptt:int=70, max_len:int=70*20, config:dict=None, pretrained:bool=True, drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None, **learn_kwargs) -> 'TextClassifierLearner': "Create a `Learner` with a text classifier from `data` and `arch`." model = get_text_classifier(arch, len(data.vocab.itos), data.c, bptt=bptt, max_len=max_len, config=config, drop_mult=drop_mult, lin_ftrs=lin_ftrs, ps=ps) meta = _model_meta[arch] learn = RNNLearner(data, model, split_func=meta['split_clas'], **learn_kwargs) if pretrained: if 'url' not in meta: warn("There are no pretrained weights for that architecture yet!") return learn model_path = untar_data(meta['url'], data=False) fnames = [list(model_path.glob(f'*.{ext}'))[0] for ext in ['pth', 'pkl']] learn.load_pretrained(*fnames, strict=False) learn.freeze() return learn
[ "def", "text_classifier_learner", "(", "data", ":", "DataBunch", ",", "arch", ":", "Callable", ",", "bptt", ":", "int", "=", "70", ",", "max_len", ":", "int", "=", "70", "*", "20", ",", "config", ":", "dict", "=", "None", ",", "pretrained", ":", "bool", "=", "True", ",", "drop_mult", ":", "float", "=", "1.", ",", "lin_ftrs", ":", "Collection", "[", "int", "]", "=", "None", ",", "ps", ":", "Collection", "[", "float", "]", "=", "None", ",", "*", "*", "learn_kwargs", ")", "->", "'TextClassifierLearner'", ":", "model", "=", "get_text_classifier", "(", "arch", ",", "len", "(", "data", ".", "vocab", ".", "itos", ")", ",", "data", ".", "c", ",", "bptt", "=", "bptt", ",", "max_len", "=", "max_len", ",", "config", "=", "config", ",", "drop_mult", "=", "drop_mult", ",", "lin_ftrs", "=", "lin_ftrs", ",", "ps", "=", "ps", ")", "meta", "=", "_model_meta", "[", "arch", "]", "learn", "=", "RNNLearner", "(", "data", ",", "model", ",", "split_func", "=", "meta", "[", "'split_clas'", "]", ",", "*", "*", "learn_kwargs", ")", "if", "pretrained", ":", "if", "'url'", "not", "in", "meta", ":", "warn", "(", "\"There are no pretrained weights for that architecture yet!\"", ")", "return", "learn", "model_path", "=", "untar_data", "(", "meta", "[", "'url'", "]", ",", "data", "=", "False", ")", "fnames", "=", "[", "list", "(", "model_path", ".", "glob", "(", "f'*.{ext}'", ")", ")", "[", "0", "]", "for", "ext", "in", "[", "'pth'", ",", "'pkl'", "]", "]", "learn", ".", "load_pretrained", "(", "*", "fnames", ",", "strict", "=", "False", ")", "learn", ".", "freeze", "(", ")", "return", "learn" ]
Create a `Learner` with a text classifier from `data` and `arch`.
[ "Create", "a", "Learner", "with", "a", "text", "classifier", "from", "data", "and", "arch", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L286-L302
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", "torch", ".", "save", "(", "encoder", ".", "state_dict", "(", ")", ",", "self", ".", "path", "/", "self", ".", "model_dir", "/", "f'{name}.pth'", ")" ]
Save the encoder to `name` inside the model directory.
[ "Save", "the", "encoder", "to", "name", "inside", "the", "model", "directory", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L57-L61
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.load(self.path/self.model_dir/f'{name}.pth')) encoder.load_state_dict(torch.load(self.path/self.model_dir/f'{name}.pth', map_location=device)) self.freeze()
python
def load_encoder(self, name:str, device:torch.device=None): "Load the encoder `name` from the model directory." encoder = get_model(self.model)[0] if device is None: device = self.data.device if hasattr(encoder, 'module'): encoder = encoder.module encoder.load_state_dict(torch.load(self.path/self.model_dir/f'{name}.pth')) encoder.load_state_dict(torch.load(self.path/self.model_dir/f'{name}.pth', map_location=device)) self.freeze()
[ "def", "load_encoder", "(", "self", ",", "name", ":", "str", ",", "device", ":", "torch", ".", "device", "=", "None", ")", ":", "encoder", "=", "get_model", "(", "self", ".", "model", ")", "[", "0", "]", "if", "device", "is", "None", ":", "device", "=", "self", ".", "data", ".", "device", "if", "hasattr", "(", "encoder", ",", "'module'", ")", ":", "encoder", "=", "encoder", ".", "module", "encoder", ".", "load_state_dict", "(", "torch", ".", "load", "(", "self", ".", "path", "/", "self", ".", "model_dir", "/", "f'{name}.pth'", ")", ")", "encoder", ".", "load_state_dict", "(", "torch", ".", "load", "(", "self", ".", "path", "/", "self", ".", "model_dir", "/", "f'{name}.pth'", ",", "map_location", "=", "device", ")", ")", "self", ".", "freeze", "(", ")" ]
Load the encoder `name` from the model directory.
[ "Load", "the", "encoder", "name", "from", "the", "model", "directory", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L63-L70
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 storage, loc: storage) if 'model' in wgts: wgts = wgts['model'] wgts = convert_weights(wgts, old_stoi, self.data.train_ds.vocab.itos) self.model.load_state_dict(wgts, strict=strict)
python
def load_pretrained(self, wgts_fname:str, itos_fname:str, strict:bool=True): "Load a pretrained model and adapts it to the data vocabulary." old_itos = pickle.load(open(itos_fname, 'rb')) old_stoi = {v:k for k,v in enumerate(old_itos)} wgts = torch.load(wgts_fname, map_location=lambda storage, loc: storage) if 'model' in wgts: wgts = wgts['model'] wgts = convert_weights(wgts, old_stoi, self.data.train_ds.vocab.itos) self.model.load_state_dict(wgts, strict=strict)
[ "def", "load_pretrained", "(", "self", ",", "wgts_fname", ":", "str", ",", "itos_fname", ":", "str", ",", "strict", ":", "bool", "=", "True", ")", ":", "old_itos", "=", "pickle", ".", "load", "(", "open", "(", "itos_fname", ",", "'rb'", ")", ")", "old_stoi", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "enumerate", "(", "old_itos", ")", "}", "wgts", "=", "torch", ".", "load", "(", "wgts_fname", ",", "map_location", "=", "lambda", "storage", ",", "loc", ":", "storage", ")", "if", "'model'", "in", "wgts", ":", "wgts", "=", "wgts", "[", "'model'", "]", "wgts", "=", "convert_weights", "(", "wgts", ",", "old_stoi", ",", "self", ".", "data", ".", "train_ds", ".", "vocab", ".", "itos", ")", "self", ".", "model", ".", "load_state_dict", "(", "wgts", ",", "strict", "=", "strict", ")" ]
Load a pretrained model and adapts it to the data vocabulary.
[ "Load", "a", "pretrained", "model", "and", "adapts", "it", "to", "the", "data", "vocabulary", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L72-L79
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() if ordered: np.random.seed(42) preds = super().get_preds(ds_type=ds_type, with_loss=with_loss, n_batch=n_batch, pbar=pbar) if ordered and hasattr(self.dl(ds_type), 'sampler'): np.random.seed(42) sampler = [i for i in self.dl(ds_type).sampler] reverse_sampler = np.argsort(sampler) preds = [p[reverse_sampler] for p in preds] return(preds)
python
def get_preds(self, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False, n_batch:Optional[int]=None, pbar:Optional[PBar]=None, ordered:bool=False) -> List[Tensor]: "Return predictions and targets on the valid, train, or test set, depending on `ds_type`." self.model.reset() if ordered: np.random.seed(42) preds = super().get_preds(ds_type=ds_type, with_loss=with_loss, n_batch=n_batch, pbar=pbar) if ordered and hasattr(self.dl(ds_type), 'sampler'): np.random.seed(42) sampler = [i for i in self.dl(ds_type).sampler] reverse_sampler = np.argsort(sampler) preds = [p[reverse_sampler] for p in preds] return(preds)
[ "def", "get_preds", "(", "self", ",", "ds_type", ":", "DatasetType", "=", "DatasetType", ".", "Valid", ",", "with_loss", ":", "bool", "=", "False", ",", "n_batch", ":", "Optional", "[", "int", "]", "=", "None", ",", "pbar", ":", "Optional", "[", "PBar", "]", "=", "None", ",", "ordered", ":", "bool", "=", "False", ")", "->", "List", "[", "Tensor", "]", ":", "self", ".", "model", ".", "reset", "(", ")", "if", "ordered", ":", "np", ".", "random", ".", "seed", "(", "42", ")", "preds", "=", "super", "(", ")", ".", "get_preds", "(", "ds_type", "=", "ds_type", ",", "with_loss", "=", "with_loss", ",", "n_batch", "=", "n_batch", ",", "pbar", "=", "pbar", ")", "if", "ordered", "and", "hasattr", "(", "self", ".", "dl", "(", "ds_type", ")", ",", "'sampler'", ")", ":", "np", ".", "random", ".", "seed", "(", "42", ")", "sampler", "=", "[", "i", "for", "i", "in", "self", ".", "dl", "(", "ds_type", ")", ".", "sampler", "]", "reverse_sampler", "=", "np", ".", "argsort", "(", "sampler", ")", "preds", "=", "[", "p", "[", "reverse_sampler", "]", "for", "p", "in", "preds", "]", "return", "(", "preds", ")" ]
Return predictions and targets on the valid, train, or test set, depending on `ds_type`.
[ "Return", "predictions", "and", "targets", "on", "the", "valid", "train", "or", "test", "set", "depending", "on", "ds_type", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L81-L92
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(text) new_idx = [] for _ in range(n_words): #progress_bar(range(n_words), leave=False): res = self.pred_batch(batch=(xb,yb))[0][-1] #if len(new_idx) == 0: self.model[0].select_hidden([0]) if no_unk: res[self.data.vocab.stoi[UNK]] = 0. if min_p is not None: if (res >= min_p).float().sum() == 0: warn(f"There is no item with probability >= {min_p}, try a lower value.") else: res[res < min_p] = 0. if temperature != 1.: res.pow_(1 / temperature) idx = torch.multinomial(res, 1).item() new_idx.append(idx) xb = xb.new_tensor([idx])[None] return text + sep + sep.join(decoder(self.data.vocab.textify(new_idx, sep=None)))
python
def predict(self, text:str, n_words:int=1, no_unk:bool=True, temperature:float=1., min_p:float=None, sep:str=' ', decoder=decode_spec_tokens): "Return the `n_words` that come after `text`." ds = self.data.single_dl.dataset self.model.reset() xb,yb = self.data.one_item(text) new_idx = [] for _ in range(n_words): #progress_bar(range(n_words), leave=False): res = self.pred_batch(batch=(xb,yb))[0][-1] #if len(new_idx) == 0: self.model[0].select_hidden([0]) if no_unk: res[self.data.vocab.stoi[UNK]] = 0. if min_p is not None: if (res >= min_p).float().sum() == 0: warn(f"There is no item with probability >= {min_p}, try a lower value.") else: res[res < min_p] = 0. if temperature != 1.: res.pow_(1 / temperature) idx = torch.multinomial(res, 1).item() new_idx.append(idx) xb = xb.new_tensor([idx])[None] return text + sep + sep.join(decoder(self.data.vocab.textify(new_idx, sep=None)))
[ "def", "predict", "(", "self", ",", "text", ":", "str", ",", "n_words", ":", "int", "=", "1", ",", "no_unk", ":", "bool", "=", "True", ",", "temperature", ":", "float", "=", "1.", ",", "min_p", ":", "float", "=", "None", ",", "sep", ":", "str", "=", "' '", ",", "decoder", "=", "decode_spec_tokens", ")", ":", "ds", "=", "self", ".", "data", ".", "single_dl", ".", "dataset", "self", ".", "model", ".", "reset", "(", ")", "xb", ",", "yb", "=", "self", ".", "data", ".", "one_item", "(", "text", ")", "new_idx", "=", "[", "]", "for", "_", "in", "range", "(", "n_words", ")", ":", "#progress_bar(range(n_words), leave=False):", "res", "=", "self", ".", "pred_batch", "(", "batch", "=", "(", "xb", ",", "yb", ")", ")", "[", "0", "]", "[", "-", "1", "]", "#if len(new_idx) == 0: self.model[0].select_hidden([0])", "if", "no_unk", ":", "res", "[", "self", ".", "data", ".", "vocab", ".", "stoi", "[", "UNK", "]", "]", "=", "0.", "if", "min_p", "is", "not", "None", ":", "if", "(", "res", ">=", "min_p", ")", ".", "float", "(", ")", ".", "sum", "(", ")", "==", "0", ":", "warn", "(", "f\"There is no item with probability >= {min_p}, try a lower value.\"", ")", "else", ":", "res", "[", "res", "<", "min_p", "]", "=", "0.", "if", "temperature", "!=", "1.", ":", "res", ".", "pow_", "(", "1", "/", "temperature", ")", "idx", "=", "torch", ".", "multinomial", "(", "res", ",", "1", ")", ".", "item", "(", ")", "new_idx", ".", "append", "(", "idx", ")", "xb", "=", "xb", ".", "new_tensor", "(", "[", "idx", "]", ")", "[", "None", "]", "return", "text", "+", "sep", "+", "sep", ".", "join", "(", "decoder", "(", "self", ".", "data", ".", "vocab", ".", "textify", "(", "new_idx", ",", "sep", "=", "None", ")", ")", ")" ]
Return the `n_words` that come after `text`.
[ "Return", "the", "n_words", "that", "come", "after", "text", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L116-L135
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() xb, yb = self.data.one_item(text) nodes = None xb = xb.repeat(top_k, 1) nodes = xb.clone() scores = xb.new_zeros(1).float() with torch.no_grad(): for k in progress_bar(range(n_words), leave=False): out = F.log_softmax(self.model(xb)[0][:,-1], dim=-1) if no_unk: out[:,self.data.vocab.stoi[UNK]] = -float('Inf') values, indices = out.topk(top_k, dim=-1) scores = (-values + scores[:,None]).view(-1) indices_idx = torch.arange(0,nodes.size(0))[:,None].expand(nodes.size(0), top_k).contiguous().view(-1) sort_idx = scores.argsort()[:beam_sz] scores = scores[sort_idx] nodes = torch.cat([nodes[:,None].expand(nodes.size(0),top_k,nodes.size(1)), indices[:,:,None].expand(nodes.size(0),top_k,1),], dim=2) nodes = nodes.view(-1, nodes.size(2))[sort_idx] self.model[0].select_hidden(indices_idx[sort_idx]) xb = nodes[:,-1][:,None] if temperature != 1.: scores.div_(temperature) node_idx = torch.multinomial(torch.exp(-scores), 1).item() return text + sep + sep.join(decoder(self.data.vocab.textify([i.item() for i in nodes[node_idx][1:] ], sep=None)))
python
def beam_search(self, text:str, n_words:int, no_unk:bool=True, top_k:int=10, beam_sz:int=1000, temperature:float=1., sep:str=' ', decoder=decode_spec_tokens): "Return the `n_words` that come after `text` using beam search." ds = self.data.single_dl.dataset self.model.reset() xb, yb = self.data.one_item(text) nodes = None xb = xb.repeat(top_k, 1) nodes = xb.clone() scores = xb.new_zeros(1).float() with torch.no_grad(): for k in progress_bar(range(n_words), leave=False): out = F.log_softmax(self.model(xb)[0][:,-1], dim=-1) if no_unk: out[:,self.data.vocab.stoi[UNK]] = -float('Inf') values, indices = out.topk(top_k, dim=-1) scores = (-values + scores[:,None]).view(-1) indices_idx = torch.arange(0,nodes.size(0))[:,None].expand(nodes.size(0), top_k).contiguous().view(-1) sort_idx = scores.argsort()[:beam_sz] scores = scores[sort_idx] nodes = torch.cat([nodes[:,None].expand(nodes.size(0),top_k,nodes.size(1)), indices[:,:,None].expand(nodes.size(0),top_k,1),], dim=2) nodes = nodes.view(-1, nodes.size(2))[sort_idx] self.model[0].select_hidden(indices_idx[sort_idx]) xb = nodes[:,-1][:,None] if temperature != 1.: scores.div_(temperature) node_idx = torch.multinomial(torch.exp(-scores), 1).item() return text + sep + sep.join(decoder(self.data.vocab.textify([i.item() for i in nodes[node_idx][1:] ], sep=None)))
[ "def", "beam_search", "(", "self", ",", "text", ":", "str", ",", "n_words", ":", "int", ",", "no_unk", ":", "bool", "=", "True", ",", "top_k", ":", "int", "=", "10", ",", "beam_sz", ":", "int", "=", "1000", ",", "temperature", ":", "float", "=", "1.", ",", "sep", ":", "str", "=", "' '", ",", "decoder", "=", "decode_spec_tokens", ")", ":", "ds", "=", "self", ".", "data", ".", "single_dl", ".", "dataset", "self", ".", "model", ".", "reset", "(", ")", "xb", ",", "yb", "=", "self", ".", "data", ".", "one_item", "(", "text", ")", "nodes", "=", "None", "xb", "=", "xb", ".", "repeat", "(", "top_k", ",", "1", ")", "nodes", "=", "xb", ".", "clone", "(", ")", "scores", "=", "xb", ".", "new_zeros", "(", "1", ")", ".", "float", "(", ")", "with", "torch", ".", "no_grad", "(", ")", ":", "for", "k", "in", "progress_bar", "(", "range", "(", "n_words", ")", ",", "leave", "=", "False", ")", ":", "out", "=", "F", ".", "log_softmax", "(", "self", ".", "model", "(", "xb", ")", "[", "0", "]", "[", ":", ",", "-", "1", "]", ",", "dim", "=", "-", "1", ")", "if", "no_unk", ":", "out", "[", ":", ",", "self", ".", "data", ".", "vocab", ".", "stoi", "[", "UNK", "]", "]", "=", "-", "float", "(", "'Inf'", ")", "values", ",", "indices", "=", "out", ".", "topk", "(", "top_k", ",", "dim", "=", "-", "1", ")", "scores", "=", "(", "-", "values", "+", "scores", "[", ":", ",", "None", "]", ")", ".", "view", "(", "-", "1", ")", "indices_idx", "=", "torch", ".", "arange", "(", "0", ",", "nodes", ".", "size", "(", "0", ")", ")", "[", ":", ",", "None", "]", ".", "expand", "(", "nodes", ".", "size", "(", "0", ")", ",", "top_k", ")", ".", "contiguous", "(", ")", ".", "view", "(", "-", "1", ")", "sort_idx", "=", "scores", ".", "argsort", "(", ")", "[", ":", "beam_sz", "]", "scores", "=", "scores", "[", "sort_idx", "]", "nodes", "=", "torch", ".", "cat", "(", "[", "nodes", "[", ":", ",", "None", "]", ".", "expand", "(", "nodes", ".", "size", "(", "0", ")", ",", "top_k", ",", "nodes", ".", "size", "(", "1", ")", ")", ",", "indices", "[", ":", ",", ":", ",", "None", "]", ".", "expand", "(", "nodes", ".", "size", "(", "0", ")", ",", "top_k", ",", "1", ")", ",", "]", ",", "dim", "=", "2", ")", "nodes", "=", "nodes", ".", "view", "(", "-", "1", ",", "nodes", ".", "size", "(", "2", ")", ")", "[", "sort_idx", "]", "self", ".", "model", "[", "0", "]", ".", "select_hidden", "(", "indices_idx", "[", "sort_idx", "]", ")", "xb", "=", "nodes", "[", ":", ",", "-", "1", "]", "[", ":", ",", "None", "]", "if", "temperature", "!=", "1.", ":", "scores", ".", "div_", "(", "temperature", ")", "node_idx", "=", "torch", ".", "multinomial", "(", "torch", ".", "exp", "(", "-", "scores", ")", ",", "1", ")", ".", "item", "(", ")", "return", "text", "+", "sep", "+", "sep", ".", "join", "(", "decoder", "(", "self", ".", "data", ".", "vocab", ".", "textify", "(", "[", "i", ".", "item", "(", ")", "for", "i", "in", "nodes", "[", "node_idx", "]", "[", "1", ":", "]", "]", ",", "sep", "=", "None", ")", ")", ")" ]
Return the `n_words` that come after `text` using beam search.
[ "Return", "the", "n_words", "that", "come", "after", "text", "using", "beam", "search", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L137-L163
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 = self.pred_batch(batch=(x,y)) y = y.view(*x.size()) z = preds.view(*x.size(),-1).argmax(dim=2) xs = [ds.x.reconstruct(grab_idx(x, i)) for i in range(rows)] ys = [ds.x.reconstruct(grab_idx(y, i)) for i in range(rows)] zs = [ds.x.reconstruct(grab_idx(z, i)) for i in range(rows)] items,names = [],['text', 'target', 'pred'] for i, (x,y,z) in enumerate(zip(xs,ys,zs)): txt_x = ' '.join(x.text.split(' ')[:max_len]) txt_y = ' '.join(y.text.split(' ')[max_len-1:2*max_len-1]) txt_z = ' '.join(z.text.split(' ')[max_len-1:2*max_len-1]) items.append([txt_x, txt_y, txt_z]) items = np.array(items) df = pd.DataFrame({n:items[:,i] for i,n in enumerate(names)}, columns=names) with pd.option_context('display.max_colwidth', -1): display(HTML(df.to_html(index=False)))
python
def show_results(self, ds_type=DatasetType.Valid, rows:int=5, max_len:int=20): from IPython.display import display, HTML "Show `rows` result of predictions on `ds_type` dataset." ds = self.dl(ds_type).dataset x,y = self.data.one_batch(ds_type, detach=False, denorm=False) preds = self.pred_batch(batch=(x,y)) y = y.view(*x.size()) z = preds.view(*x.size(),-1).argmax(dim=2) xs = [ds.x.reconstruct(grab_idx(x, i)) for i in range(rows)] ys = [ds.x.reconstruct(grab_idx(y, i)) for i in range(rows)] zs = [ds.x.reconstruct(grab_idx(z, i)) for i in range(rows)] items,names = [],['text', 'target', 'pred'] for i, (x,y,z) in enumerate(zip(xs,ys,zs)): txt_x = ' '.join(x.text.split(' ')[:max_len]) txt_y = ' '.join(y.text.split(' ')[max_len-1:2*max_len-1]) txt_z = ' '.join(z.text.split(' ')[max_len-1:2*max_len-1]) items.append([txt_x, txt_y, txt_z]) items = np.array(items) df = pd.DataFrame({n:items[:,i] for i,n in enumerate(names)}, columns=names) with pd.option_context('display.max_colwidth', -1): display(HTML(df.to_html(index=False)))
[ "def", "show_results", "(", "self", ",", "ds_type", "=", "DatasetType", ".", "Valid", ",", "rows", ":", "int", "=", "5", ",", "max_len", ":", "int", "=", "20", ")", ":", "from", "IPython", ".", "display", "import", "display", ",", "HTML", "ds", "=", "self", ".", "dl", "(", "ds_type", ")", ".", "dataset", "x", ",", "y", "=", "self", ".", "data", ".", "one_batch", "(", "ds_type", ",", "detach", "=", "False", ",", "denorm", "=", "False", ")", "preds", "=", "self", ".", "pred_batch", "(", "batch", "=", "(", "x", ",", "y", ")", ")", "y", "=", "y", ".", "view", "(", "*", "x", ".", "size", "(", ")", ")", "z", "=", "preds", ".", "view", "(", "*", "x", ".", "size", "(", ")", ",", "-", "1", ")", ".", "argmax", "(", "dim", "=", "2", ")", "xs", "=", "[", "ds", ".", "x", ".", "reconstruct", "(", "grab_idx", "(", "x", ",", "i", ")", ")", "for", "i", "in", "range", "(", "rows", ")", "]", "ys", "=", "[", "ds", ".", "x", ".", "reconstruct", "(", "grab_idx", "(", "y", ",", "i", ")", ")", "for", "i", "in", "range", "(", "rows", ")", "]", "zs", "=", "[", "ds", ".", "x", ".", "reconstruct", "(", "grab_idx", "(", "z", ",", "i", ")", ")", "for", "i", "in", "range", "(", "rows", ")", "]", "items", ",", "names", "=", "[", "]", ",", "[", "'text'", ",", "'target'", ",", "'pred'", "]", "for", "i", ",", "(", "x", ",", "y", ",", "z", ")", "in", "enumerate", "(", "zip", "(", "xs", ",", "ys", ",", "zs", ")", ")", ":", "txt_x", "=", "' '", ".", "join", "(", "x", ".", "text", ".", "split", "(", "' '", ")", "[", ":", "max_len", "]", ")", "txt_y", "=", "' '", ".", "join", "(", "y", ".", "text", ".", "split", "(", "' '", ")", "[", "max_len", "-", "1", ":", "2", "*", "max_len", "-", "1", "]", ")", "txt_z", "=", "' '", ".", "join", "(", "z", ".", "text", ".", "split", "(", "' '", ")", "[", "max_len", "-", "1", ":", "2", "*", "max_len", "-", "1", "]", ")", "items", ".", "append", "(", "[", "txt_x", ",", "txt_y", ",", "txt_z", "]", ")", "items", "=", "np", ".", "array", "(", "items", ")", "df", "=", "pd", ".", "DataFrame", "(", "{", "n", ":", "items", "[", ":", ",", "i", "]", "for", "i", ",", "n", "in", "enumerate", "(", "names", ")", "}", ",", "columns", "=", "names", ")", "with", "pd", ".", "option_context", "(", "'display.max_colwidth'", ",", "-", "1", ")", ":", "display", "(", "HTML", "(", "df", ".", "to_html", "(", "index", "=", "False", ")", ")", ")" ]
Show `rows` result of predictions on `ds_type` dataset.
[ "Show", "rows", "result", "of", "predictions", "on", "ds_type", "dataset", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L165-L185
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", "si", "in", "range_of", "(", "arrs", "[", "0", "]", ")", "]" ]
Concatenate the `arrs` along the batch dimension.
[ "Concatenate", "the", "arrs", "along", "the", "batch", "dimension", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/learner.py#L250-L252
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", ".", "fill_", "(", "1e-3", ")", "bn", ".", "weight", ".", "fill_", "(", "0.", "if", "norm_type", "==", "NormType", ".", "BatchZero", "else", "1.", ")", "return", "bn" ]
A batchnorm2d layer with `nf` features initialized depending on `norm_type`.
[ "A", "batchnorm2d", "layer", "with", "nf", "features", "initialized", "depending", "on", "norm_type", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L52-L58
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_() return spectral_norm(conv)
python
def conv1d(ni:int, no:int, ks:int=1, stride:int=1, padding:int=0, bias:bool=False): "Create and initialize a `nn.Conv1d` layer with spectral normalization." conv = nn.Conv1d(ni, no, ks, stride=stride, padding=padding, bias=bias) nn.init.kaiming_normal_(conv.weight) if bias: conv.bias.data.zero_() return spectral_norm(conv)
[ "def", "conv1d", "(", "ni", ":", "int", ",", "no", ":", "int", ",", "ks", ":", "int", "=", "1", ",", "stride", ":", "int", "=", "1", ",", "padding", ":", "int", "=", "0", ",", "bias", ":", "bool", "=", "False", ")", ":", "conv", "=", "nn", ".", "Conv1d", "(", "ni", ",", "no", ",", "ks", ",", "stride", "=", "stride", ",", "padding", "=", "padding", ",", "bias", "=", "bias", ")", "nn", ".", "init", ".", "kaiming_normal_", "(", "conv", ".", "weight", ")", "if", "bias", ":", "conv", ".", "bias", ".", "data", ".", "zero_", "(", ")", "return", "spectral_norm", "(", "conv", ")" ]
Create and initialize a `nn.Conv1d` layer with spectral normalization.
[ "Create", "and", "initialize", "a", "nn", ".", "Conv1d", "layer", "with", "spectral", "normalization", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L68-L73
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", ":", "return", "nn", ".", "ConvTranspose2d", "(", "ni", ",", "nf", ",", "kernel_size", "=", "ks", ",", "stride", "=", "stride", ",", "padding", "=", "padding", ",", "bias", "=", "bias", ")" ]
Create `nn.ConvTranspose2d` layer.
[ "Create", "nn", ".", "ConvTranspose2d", "layer", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L120-L122
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", "else", "nn", ".", "ReLU", "(", "inplace", "=", "inplace", ")" ]
Return a relu activation, maybe `leaky` and `inplace`.
[ "Return", "a", "relu", "activation", "maybe", "leaky", "and", "inplace", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L124-L126
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 bottle else nf return SequentialEx(conv_layer(nf, nf_inner, norm_type=norm_type, **conv_kwargs), conv_layer(nf_inner, nf, norm_type=norm2, **conv_kwargs), MergeLayer(dense))
python
def res_block(nf, dense:bool=False, norm_type:Optional[NormType]=NormType.Batch, bottle:bool=False, **conv_kwargs): "Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`." norm2 = norm_type if not dense and (norm_type==NormType.Batch): norm2 = NormType.BatchZero nf_inner = nf//2 if bottle else nf return SequentialEx(conv_layer(nf, nf_inner, norm_type=norm_type, **conv_kwargs), conv_layer(nf_inner, nf, norm_type=norm2, **conv_kwargs), MergeLayer(dense))
[ "def", "res_block", "(", "nf", ",", "dense", ":", "bool", "=", "False", ",", "norm_type", ":", "Optional", "[", "NormType", "]", "=", "NormType", ".", "Batch", ",", "bottle", ":", "bool", "=", "False", ",", "*", "*", "conv_kwargs", ")", ":", "norm2", "=", "norm_type", "if", "not", "dense", "and", "(", "norm_type", "==", "NormType", ".", "Batch", ")", ":", "norm2", "=", "NormType", ".", "BatchZero", "nf_inner", "=", "nf", "//", "2", "if", "bottle", "else", "nf", "return", "SequentialEx", "(", "conv_layer", "(", "nf", ",", "nf_inner", ",", "norm_type", "=", "norm_type", ",", "*", "*", "conv_kwargs", ")", ",", "conv_layer", "(", "nf_inner", ",", "nf", ",", "norm_type", "=", "norm2", ",", "*", "*", "conv_kwargs", ")", ",", "MergeLayer", "(", "dense", ")", ")" ]
Resnet block of `nf` features. `conv_kwargs` are passed to `conv_layer`.
[ "Resnet", "block", "of", "nf", "features", ".", "conv_kwargs", "are", "passed", "to", "conv_layer", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L174-L181
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([nf,ni,h,w]).transpose(0, 1) x.data.copy_(k)
python
def icnr(x, scale=2, init=nn.init.kaiming_normal_): "ICNR init of `x`, with `scale` and `init` function." ni,nf,h,w = x.shape ni2 = int(ni/(scale**2)) k = init(torch.zeros([ni2,nf,h,w])).transpose(0, 1) k = k.contiguous().view(ni2, nf, -1) k = k.repeat(1, 1, scale**2) k = k.contiguous().view([nf,ni,h,w]).transpose(0, 1) x.data.copy_(k)
[ "def", "icnr", "(", "x", ",", "scale", "=", "2", ",", "init", "=", "nn", ".", "init", ".", "kaiming_normal_", ")", ":", "ni", ",", "nf", ",", "h", ",", "w", "=", "x", ".", "shape", "ni2", "=", "int", "(", "ni", "/", "(", "scale", "**", "2", ")", ")", "k", "=", "init", "(", "torch", ".", "zeros", "(", "[", "ni2", ",", "nf", ",", "h", ",", "w", "]", ")", ")", ".", "transpose", "(", "0", ",", "1", ")", "k", "=", "k", ".", "contiguous", "(", ")", ".", "view", "(", "ni2", ",", "nf", ",", "-", "1", ")", "k", "=", "k", ".", "repeat", "(", "1", ",", "1", ",", "scale", "**", "2", ")", "k", "=", "k", ".", "contiguous", "(", ")", ".", "view", "(", "[", "nf", ",", "ni", ",", "h", ",", "w", "]", ")", ".", "transpose", "(", "0", ",", "1", ")", "x", ".", "data", ".", "copy_", "(", "k", ")" ]
ICNR init of `x`, with `scale` and `init` function.
[ "ICNR", "init", "of", "x", "with", "scale", "and", "init", "function", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L221-L229
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", ",", "*", "*", "kwargs", ")" ]
Same as `nn.CrossEntropyLoss`, but flattens input and target.
[ "Same", "as", "nn", ".", "CrossEntropyLoss", "but", "flattens", "input", "and", "target", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L269-L271
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", ",", "axis", "=", "axis", ",", "floatify", "=", "floatify", ",", "is_2d", "=", "False", ",", "*", "*", "kwargs", ")" ]
Same as `nn.BCEWithLogitsLoss`, but flattens input and target.
[ "Same", "as", "nn", ".", "BCEWithLogitsLoss", "but", "flattens", "input", "and", "target", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L273-L275
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", "=", "axis", ",", "floatify", "=", "floatify", ",", "is_2d", "=", "False", ",", "*", "*", "kwargs", ")" ]
Same as `nn.BCELoss`, but flattens input and target.
[ "Same", "as", "nn", ".", "BCELoss", "but", "flattens", "input", "and", "target", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L277-L279
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", "=", "axis", ",", "floatify", "=", "floatify", ",", "is_2d", "=", "False", ",", "*", "*", "kwargs", ")" ]
Same as `nn.MSELoss`, but flattens input and target.
[ "Same", "as", "nn", ".", "MSELoss", "but", "flattens", "input", "and", "target", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L281-L283
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) strides = ifnone(strides , [2]*nl) layers = [conv_layer(actns[i], actns[i+1], kernel_szs[i], stride=strides[i], norm_type=(NormType.Batch if bn and i<(len(strides)-1) else None)) for i in range_of(strides)] layers.append(PoolFlatten()) return nn.Sequential(*layers)
python
def simple_cnn(actns:Collection[int], kernel_szs:Collection[int]=None, strides:Collection[int]=None, bn=False) -> nn.Sequential: "CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`." nl = len(actns)-1 kernel_szs = ifnone(kernel_szs, [3]*nl) strides = ifnone(strides , [2]*nl) layers = [conv_layer(actns[i], actns[i+1], kernel_szs[i], stride=strides[i], norm_type=(NormType.Batch if bn and i<(len(strides)-1) else None)) for i in range_of(strides)] layers.append(PoolFlatten()) return nn.Sequential(*layers)
[ "def", "simple_cnn", "(", "actns", ":", "Collection", "[", "int", "]", ",", "kernel_szs", ":", "Collection", "[", "int", "]", "=", "None", ",", "strides", ":", "Collection", "[", "int", "]", "=", "None", ",", "bn", "=", "False", ")", "->", "nn", ".", "Sequential", ":", "nl", "=", "len", "(", "actns", ")", "-", "1", "kernel_szs", "=", "ifnone", "(", "kernel_szs", ",", "[", "3", "]", "*", "nl", ")", "strides", "=", "ifnone", "(", "strides", ",", "[", "2", "]", "*", "nl", ")", "layers", "=", "[", "conv_layer", "(", "actns", "[", "i", "]", ",", "actns", "[", "i", "+", "1", "]", ",", "kernel_szs", "[", "i", "]", ",", "stride", "=", "strides", "[", "i", "]", ",", "norm_type", "=", "(", "NormType", ".", "Batch", "if", "bn", "and", "i", "<", "(", "len", "(", "strides", ")", "-", "1", ")", "else", "None", ")", ")", "for", "i", "in", "range_of", "(", "strides", ")", "]", "layers", ".", "append", "(", "PoolFlatten", "(", ")", ")", "return", "nn", ".", "Sequential", "(", "*", "layers", ")" ]
CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`.
[ "CNN", "with", "conv_layer", "defined", "by", "actns", "kernel_szs", "and", "strides", "plus", "batchnorm", "if", "bn", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L293-L302
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", ".", "normal_", "(", ")", ".", "fmod_", "(", "2", ")", ".", "mul_", "(", "std", ")", ".", "add_", "(", "mean", ")" ]
Truncated normal initialization.
[ "Truncated", "normal", "initialization", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L304-L307
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", "(", ")", ":", "trunc_normal_", "(", "emb", ".", "weight", ",", "std", "=", "0.01", ")", "return", "emb" ]
Create an embedding layer.
[ "Create", "an", "embedding", "layer", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/layers.py#L309-L314
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.experiment_id run = self.client.create_run(experiment_id=self.exp_id) self.run = run.info.run_uuid for k,v in self.params.items(): self.client.log_param(run_id=self.run, key=k, value=v)
python
def on_train_begin(self, **kwargs: Any) -> None: "Prepare MLflow experiment and log params" self.client = mlflow.tracking.MlflowClient(self.uri) exp = self.client.get_experiment_by_name(self.exp_name) self.exp_id = self.client.create_experiment(self.exp_name) if exp is None else exp.experiment_id run = self.client.create_run(experiment_id=self.exp_id) self.run = run.info.run_uuid for k,v in self.params.items(): self.client.log_param(run_id=self.run, key=k, value=v)
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "client", "=", "mlflow", ".", "tracking", ".", "MlflowClient", "(", "self", ".", "uri", ")", "exp", "=", "self", ".", "client", ".", "get_experiment_by_name", "(", "self", ".", "exp_name", ")", "self", ".", "exp_id", "=", "self", ".", "client", ".", "create_experiment", "(", "self", ".", "exp_name", ")", "if", "exp", "is", "None", "else", "exp", ".", "experiment_id", "run", "=", "self", ".", "client", ".", "create_run", "(", "experiment_id", "=", "self", ".", "exp_id", ")", "self", ".", "run", "=", "run", ".", "info", ".", "run_uuid", "for", "k", ",", "v", "in", "self", ".", "params", ".", "items", "(", ")", ":", "self", ".", "client", ".", "log_param", "(", "run_id", "=", "self", ".", "run", ",", "key", "=", "k", ",", "value", "=", "v", ")" ]
Prepare MLflow experiment and log params
[ "Prepare", "MLflow", "experiment", "and", "log", "params" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L16-L24
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, metrics): self.client.log_metric(self.run, name, np.float(val))
python
def on_epoch_end(self, epoch, **kwargs:Any)->None: "Send loss and metrics values to MLFlow after each epoch" if kwargs['smooth_loss'] is None or kwargs["last_metrics"] is None: return metrics = [kwargs['smooth_loss']] + kwargs["last_metrics"] for name, val in zip(self.metrics_names, metrics): self.client.log_metric(self.run, name, np.float(val))
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "kwargs", "[", "'smooth_loss'", "]", "is", "None", "or", "kwargs", "[", "\"last_metrics\"", "]", "is", "None", ":", "return", "metrics", "=", "[", "kwargs", "[", "'smooth_loss'", "]", "]", "+", "kwargs", "[", "\"last_metrics\"", "]", "for", "name", ",", "val", "in", "zip", "(", "self", ".", "metrics_names", ",", "metrics", ")", ":", "self", ".", "client", ".", "log_metric", "(", "self", ".", "run", ",", "name", ",", "np", ".", "float", "(", "val", ")", ")" ]
Send loss and metrics values to MLFlow after each epoch
[ "Send", "loss", "and", "metrics", "values", "to", "MLFlow", "after", "each", "epoch" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L26-L31
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", ".", "client", ".", "set_terminated", "(", "run_id", "=", "self", ".", "run", ")" ]
Store the notebook and stop run
[ "Store", "the", "notebook", "and", "stop", "run" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/mlflow.py#L33-L36
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(dtype, copy=False) )
python
def pil2tensor(image:Union[NPImage,NPArray],dtype:np.dtype)->TensorImage: "Convert PIL style `image` array to torch style image tensor." a = np.asarray(image) if a.ndim==2 : a = np.expand_dims(a,2) a = np.transpose(a, (1, 0, 2)) a = np.transpose(a, (2, 1, 0)) return torch.from_numpy(a.astype(dtype, copy=False) )
[ "def", "pil2tensor", "(", "image", ":", "Union", "[", "NPImage", ",", "NPArray", "]", ",", "dtype", ":", "np", ".", "dtype", ")", "->", "TensorImage", ":", "a", "=", "np", ".", "asarray", "(", "image", ")", "if", "a", ".", "ndim", "==", "2", ":", "a", "=", "np", ".", "expand_dims", "(", "a", ",", "2", ")", "a", "=", "np", ".", "transpose", "(", "a", ",", "(", "1", ",", "0", ",", "2", ")", ")", "a", "=", "np", ".", "transpose", "(", "a", ",", "(", "2", ",", "1", ",", "0", ")", ")", "return", "torch", ".", "from_numpy", "(", "a", ".", "astype", "(", "dtype", ",", "copy", "=", "False", ")", ")" ]
Convert PIL style `image` array to torch style image tensor.
[ "Convert", "PIL", "style", "image", "array", "to", "torch", "style", "image", "tensor", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L14-L20
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, verticalalignment='top', color=color, fontsize=text_size, weight='bold') _draw_outline(patch,1)
python
def _draw_rect(ax:plt.Axes, b:Collection[int], color:str='white', text=None, text_size=14): "Draw bounding box on `ax`." patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor=color, lw=2)) _draw_outline(patch, 4) if text is not None: patch = ax.text(*b[:2], text, verticalalignment='top', color=color, fontsize=text_size, weight='bold') _draw_outline(patch,1)
[ "def", "_draw_rect", "(", "ax", ":", "plt", ".", "Axes", ",", "b", ":", "Collection", "[", "int", "]", ",", "color", ":", "str", "=", "'white'", ",", "text", "=", "None", ",", "text_size", "=", "14", ")", ":", "patch", "=", "ax", ".", "add_patch", "(", "patches", ".", "Rectangle", "(", "b", "[", ":", "2", "]", ",", "*", "b", "[", "-", "2", ":", "]", ",", "fill", "=", "False", ",", "edgecolor", "=", "color", ",", "lw", "=", "2", ")", ")", "_draw_outline", "(", "patch", ",", "4", ")", "if", "text", "is", "not", "None", ":", "patch", "=", "ax", ".", "text", "(", "*", "b", "[", ":", "2", "]", ",", "text", ",", "verticalalignment", "=", "'top'", ",", "color", "=", "color", ",", "fontsize", "=", "text_size", ",", "weight", "=", "'bold'", ")", "_draw_outline", "(", "patch", ",", "1", ")" ]
Draw bounding box on `ax`.
[ "Draw", "bounding", "box", "on", "ax", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L41-L47
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 = PIL.Image.open(fn).convert(convert_mode) if after_open: x = after_open(x) x = pil2tensor(x,np.float32) if div: x.div_(255) return cls(x)
python
def open_image(fn:PathOrStr, div:bool=True, convert_mode:str='RGB', cls:type=Image, after_open:Callable=None)->Image: "Return `Image` object created from image in file `fn`." with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) # EXIF warning from TiffPlugin x = PIL.Image.open(fn).convert(convert_mode) if after_open: x = after_open(x) x = pil2tensor(x,np.float32) if div: x.div_(255) return cls(x)
[ "def", "open_image", "(", "fn", ":", "PathOrStr", ",", "div", ":", "bool", "=", "True", ",", "convert_mode", ":", "str", "=", "'RGB'", ",", "cls", ":", "type", "=", "Image", ",", "after_open", ":", "Callable", "=", "None", ")", "->", "Image", ":", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ",", "UserWarning", ")", "# EXIF warning from TiffPlugin", "x", "=", "PIL", ".", "Image", ".", "open", "(", "fn", ")", ".", "convert", "(", "convert_mode", ")", "if", "after_open", ":", "x", "=", "after_open", "(", "x", ")", "x", "=", "pil2tensor", "(", "x", ",", "np", ".", "float32", ")", "if", "div", ":", "x", ".", "div_", "(", "255", ")", "return", "cls", "(", "x", ")" ]
Return `Image` object created from image in file `fn`.
[ "Return", "Image", "object", "created", "from", "image", "in", "file", "fn", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L388-L397
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", ",", "convert_mode", "=", "convert_mode", ",", "cls", "=", "ImageSegment", ",", "after_open", "=", "after_open", ")" ]
Return `ImageSegment` object create from mask in file `fn`. If `div`, divides pixel values by 255.
[ "Return", "ImageSegment", "object", "create", "from", "mask", "in", "file", "fn", ".", "If", "div", "divides", "pixel", "values", "by", "255", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L399-L401
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.permute(2,0,1))
python
def open_mask_rle(mask_rle:str, shape:Tuple[int, int])->ImageSegment: "Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`." x = FloatTensor(rle_decode(str(mask_rle), shape).astype(np.uint8)) x = x.view(shape[1], shape[0], -1) return ImageSegment(x.permute(2,0,1))
[ "def", "open_mask_rle", "(", "mask_rle", ":", "str", ",", "shape", ":", "Tuple", "[", "int", ",", "int", "]", ")", "->", "ImageSegment", ":", "x", "=", "FloatTensor", "(", "rle_decode", "(", "str", "(", "mask_rle", ")", ",", "shape", ")", ".", "astype", "(", "np", ".", "uint8", ")", ")", "x", "=", "x", ".", "view", "(", "shape", "[", "1", "]", ",", "shape", "[", "0", "]", ",", "-", "1", ")", "return", "ImageSegment", "(", "x", ".", "permute", "(", "2", ",", "0", ",", "1", ")", ")" ]
Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`.
[ "Return", "ImageSegment", "object", "create", "from", "run", "-", "length", "encoded", "string", "in", "mask_lre", "with", "size", "in", "shape", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L403-L407
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", "(", "pixels", "[", "1", ":", "]", "!=", "pixels", "[", ":", "-", "1", "]", ")", "[", "0", "]", "+", "1", "runs", "[", "1", ":", ":", "2", "]", "-=", "runs", "[", ":", ":", "2", "]", "return", "' '", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "runs", ")" ]
Return run-length encoding string from `img`.
[ "Return", "run", "-", "length", "encoding", "string", "from", "img", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L409-L414
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(shape[0]*shape[1], dtype=np.uint) for low, up in zip(starts, ends): img[low:up] = 1 return img.reshape(shape)
python
def rle_decode(mask_rle:str, shape:Tuple[int,int])->NPArrayMask: "Return an image array from run-length encoded string `mask_rle` with `shape`." s = mask_rle.split() starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])] starts -= 1 ends = starts + lengths img = np.zeros(shape[0]*shape[1], dtype=np.uint) for low, up in zip(starts, ends): img[low:up] = 1 return img.reshape(shape)
[ "def", "rle_decode", "(", "mask_rle", ":", "str", ",", "shape", ":", "Tuple", "[", "int", ",", "int", "]", ")", "->", "NPArrayMask", ":", "s", "=", "mask_rle", ".", "split", "(", ")", "starts", ",", "lengths", "=", "[", "np", ".", "asarray", "(", "x", ",", "dtype", "=", "int", ")", "for", "x", "in", "(", "s", "[", "0", ":", "]", "[", ":", ":", "2", "]", ",", "s", "[", "1", ":", "]", "[", ":", ":", "2", "]", ")", "]", "starts", "-=", "1", "ends", "=", "starts", "+", "lengths", "img", "=", "np", ".", "zeros", "(", "shape", "[", "0", "]", "*", "shape", "[", "1", "]", ",", "dtype", "=", "np", ".", "uint", ")", "for", "low", ",", "up", "in", "zip", "(", "starts", ",", "ends", ")", ":", "img", "[", "low", ":", "up", "]", "=", "1", "return", "img", ".", "reshape", "(", "shape", ")" ]
Return an image array from run-length encoded string `mask_rle` with `shape`.
[ "Return", "an", "image", "array", "from", "run", "-", "length", "encoded", "string", "mask_rle", "with", "shape", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L416-L424
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) if hide_axis: ax.axis('off') return ax
python
def show_image(img:Image, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True, cmap:str='binary', alpha:float=None, **kwargs)->plt.Axes: "Display `Image` in notebook." if ax is None: fig,ax = plt.subplots(figsize=figsize) ax.imshow(image2np(img.data), cmap=cmap, alpha=alpha, **kwargs) if hide_axis: ax.axis('off') return ax
[ "def", "show_image", "(", "img", ":", "Image", ",", "ax", ":", "plt", ".", "Axes", "=", "None", ",", "figsize", ":", "tuple", "=", "(", "3", ",", "3", ")", ",", "hide_axis", ":", "bool", "=", "True", ",", "cmap", ":", "str", "=", "'binary'", ",", "alpha", ":", "float", "=", "None", ",", "*", "*", "kwargs", ")", "->", "plt", ".", "Axes", ":", "if", "ax", "is", "None", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "figsize", ")", "ax", ".", "imshow", "(", "image2np", "(", "img", ".", "data", ")", ",", "cmap", "=", "cmap", ",", "alpha", "=", "alpha", ",", "*", "*", "kwargs", ")", "if", "hide_axis", ":", "ax", ".", "axis", "(", "'off'", ")", "return", "ax" ]
Display `Image` in notebook.
[ "Display", "Image", "in", "notebook", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L426-L432
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()).view(size) return c
python
def _affine_mult(c:FlowField,m:AffineMatrix)->FlowField: "Multiply `c` by `m` - can adjust for rectangular shaped `c`." if m is None: return c size = c.flow.size() h,w = c.size m[0,1] *= h/w m[1,0] *= w/h c.flow = c.flow.view(-1,2) c.flow = torch.addmm(m[:2,2], c.flow, m[:2,:2].t()).view(size) return c
[ "def", "_affine_mult", "(", "c", ":", "FlowField", ",", "m", ":", "AffineMatrix", ")", "->", "FlowField", ":", "if", "m", "is", "None", ":", "return", "c", "size", "=", "c", ".", "flow", ".", "size", "(", ")", "h", ",", "w", "=", "c", ".", "size", "m", "[", "0", ",", "1", "]", "*=", "h", "/", "w", "m", "[", "1", ",", "0", "]", "*=", "w", "/", "h", "c", ".", "flow", "=", "c", ".", "flow", ".", "view", "(", "-", "1", ",", "2", ")", "c", ".", "flow", "=", "torch", ".", "addmm", "(", "m", "[", ":", "2", ",", "2", "]", ",", "c", ".", "flow", ",", "m", "[", ":", "2", ",", ":", "2", "]", ".", "t", "(", ")", ")", ".", "view", "(", "size", ")", "return", "c" ]
Multiply `c` by `m` - can adjust for rectangular shaped `c`.
[ "Multiply", "c", "by", "m", "-", "can", "adjust", "for", "rectangular", "shaped", "c", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L547-L556
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", "]", "*=", "w", "/", "h", "c", ".", "flow", "=", "c", ".", "flow", ".", "view", "(", "-", "1", ",", "2", ")", "a", "=", "torch", ".", "inverse", "(", "m", "[", ":", "2", ",", ":", "2", "]", ".", "t", "(", ")", ")", "c", ".", "flow", "=", "torch", ".", "mm", "(", "c", ".", "flow", "-", "m", "[", ":", "2", ",", "2", "]", ",", "a", ")", ".", "view", "(", "size", ")", "return", "c" ]
Applies the inverse affine transform described in `m` to `c`.
[ "Applies", "the", "inverse", "affine", "transform", "described", "in", "m", "to", "c", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L558-L567
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", ")", "return", "_round_multiple", "(", "target_r", ",", "mult", ")", ",", "_round_multiple", "(", "target_c", ",", "mult", ")" ]
Calc crop shape of `target_px` to nearest multiple of `mult`.
[ "Calc", "crop", "shape", "of", "target_px", "to", "nearest", "multiple", "of", "mult", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L589-L592
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) return ch,int(round(r/ratio)),int(round(c/ratio))
python
def _get_resize_target(img, crop_target, do_crop=False)->TensorImageSize: "Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`." if crop_target is None: return None ch,r,c = img.shape target_r,target_c = crop_target ratio = (min if do_crop else max)(r/target_r, c/target_c) return ch,int(round(r/ratio)),int(round(c/ratio))
[ "def", "_get_resize_target", "(", "img", ",", "crop_target", ",", "do_crop", "=", "False", ")", "->", "TensorImageSize", ":", "if", "crop_target", "is", "None", ":", "return", "None", "ch", ",", "r", ",", "c", "=", "img", ".", "shape", "target_r", ",", "target_c", "=", "crop_target", "ratio", "=", "(", "min", "if", "do_crop", "else", "max", ")", "(", "r", "/", "target_r", ",", "c", "/", "target_c", ")", "return", "ch", ",", "int", "(", "round", "(", "r", "/", "ratio", ")", ")", ",", "int", "(", "round", "(", "c", "/", "ratio", ")", ")" ]
Calc size of `img` to fit in `crop_target` - adjust based on `do_crop`.
[ "Calc", "size", "of", "img", "to", "fit", "in", "crop_target", "-", "adjust", "based", "on", "do_crop", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L594-L600
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", ",", "6", ")", ")", ":", "axes", "=", "plt", ".", "subplots", "(", "r", ",", "c", ",", "figsize", "=", "figsize", ")", "[", "1", "]", "for", "i", "in", "range", "(", "r", ")", ":", "for", "j", "in", "range", "(", "c", ")", ":", "func", "(", "i", ",", "j", ",", "axes", "[", "i", ",", "j", "]", ")" ]
Call `func` for every combination of `r,c` on a subplot
[ "Call", "func", "for", "every", "combination", "of", "r", "c", "on", "a", "subplot" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L606-L610
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", "(", "imgs", ")", "if", "c", "is", "None", ":", "c", "=", "len", "(", "imgs", ")", "//", "r", "for", "i", ",", "ax", "in", "plot_flat", "(", "r", ",", "c", ",", "figsize", ")", ":", "imgs", "[", "i", "]", ".", "show", "(", "ax", ")" ]
Show all `imgs` using `r` rows
[ "Show", "all", "imgs", "using", "r", "rows" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L616-L620
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: "Apply all `tfms` to the `Image`, if `do_resolve` picks value for random args." if not (tfms or xtra or size): return self tfms = listify(tfms) xtra = ifnone(xtra, {}) default_rsz = ResizeMethod.SQUISH if (size is not None and is_listy(size)) else ResizeMethod.CROP resize_method = ifnone(resize_method, default_rsz) if resize_method <= 2 and size is not None: tfms = self._maybe_add_crop_pad(tfms) tfms = sorted(tfms, key=lambda o: o.tfm.order) if do_resolve: _resolve_tfms(tfms) x = self.clone() x.set_sample(padding_mode=padding_mode, mode=mode, remove_out=remove_out) if size is not None: crop_target = _get_crop_target(size, mult=mult) if resize_method in (ResizeMethod.CROP,ResizeMethod.PAD): target = _get_resize_target(x, crop_target, do_crop=(resize_method==ResizeMethod.CROP)) x.resize(target) elif resize_method==ResizeMethod.SQUISH: x.resize((x.shape[0],) + crop_target) else: size = x.size size_tfms = [o for o in tfms if isinstance(o.tfm,TfmCrop)] for tfm in tfms: if tfm.tfm in xtra: x = tfm(x, **xtra[tfm.tfm]) elif tfm in size_tfms: if resize_method in (ResizeMethod.CROP,ResizeMethod.PAD): x = tfm(x, size=_get_crop_target(size,mult=mult), padding_mode=padding_mode) else: x = tfm(x) return x.refresh()
python
def apply_tfms(self, tfms:TfmList, do_resolve:bool=True, xtra:Optional[Dict[Callable,dict]]=None, size:Optional[Union[int,TensorImageSize]]=None, resize_method:ResizeMethod=None, mult:int=None, padding_mode:str='reflection', mode:str='bilinear', remove_out:bool=True)->TensorImage: "Apply all `tfms` to the `Image`, if `do_resolve` picks value for random args." if not (tfms or xtra or size): return self tfms = listify(tfms) xtra = ifnone(xtra, {}) default_rsz = ResizeMethod.SQUISH if (size is not None and is_listy(size)) else ResizeMethod.CROP resize_method = ifnone(resize_method, default_rsz) if resize_method <= 2 and size is not None: tfms = self._maybe_add_crop_pad(tfms) tfms = sorted(tfms, key=lambda o: o.tfm.order) if do_resolve: _resolve_tfms(tfms) x = self.clone() x.set_sample(padding_mode=padding_mode, mode=mode, remove_out=remove_out) if size is not None: crop_target = _get_crop_target(size, mult=mult) if resize_method in (ResizeMethod.CROP,ResizeMethod.PAD): target = _get_resize_target(x, crop_target, do_crop=(resize_method==ResizeMethod.CROP)) x.resize(target) elif resize_method==ResizeMethod.SQUISH: x.resize((x.shape[0],) + crop_target) else: size = x.size size_tfms = [o for o in tfms if isinstance(o.tfm,TfmCrop)] for tfm in tfms: if tfm.tfm in xtra: x = tfm(x, **xtra[tfm.tfm]) elif tfm in size_tfms: if resize_method in (ResizeMethod.CROP,ResizeMethod.PAD): x = tfm(x, size=_get_crop_target(size,mult=mult), padding_mode=padding_mode) else: x = tfm(x) return x.refresh()
[ "def", "apply_tfms", "(", "self", ",", "tfms", ":", "TfmList", ",", "do_resolve", ":", "bool", "=", "True", ",", "xtra", ":", "Optional", "[", "Dict", "[", "Callable", ",", "dict", "]", "]", "=", "None", ",", "size", ":", "Optional", "[", "Union", "[", "int", ",", "TensorImageSize", "]", "]", "=", "None", ",", "resize_method", ":", "ResizeMethod", "=", "None", ",", "mult", ":", "int", "=", "None", ",", "padding_mode", ":", "str", "=", "'reflection'", ",", "mode", ":", "str", "=", "'bilinear'", ",", "remove_out", ":", "bool", "=", "True", ")", "->", "TensorImage", ":", "if", "not", "(", "tfms", "or", "xtra", "or", "size", ")", ":", "return", "self", "tfms", "=", "listify", "(", "tfms", ")", "xtra", "=", "ifnone", "(", "xtra", ",", "{", "}", ")", "default_rsz", "=", "ResizeMethod", ".", "SQUISH", "if", "(", "size", "is", "not", "None", "and", "is_listy", "(", "size", ")", ")", "else", "ResizeMethod", ".", "CROP", "resize_method", "=", "ifnone", "(", "resize_method", ",", "default_rsz", ")", "if", "resize_method", "<=", "2", "and", "size", "is", "not", "None", ":", "tfms", "=", "self", ".", "_maybe_add_crop_pad", "(", "tfms", ")", "tfms", "=", "sorted", "(", "tfms", ",", "key", "=", "lambda", "o", ":", "o", ".", "tfm", ".", "order", ")", "if", "do_resolve", ":", "_resolve_tfms", "(", "tfms", ")", "x", "=", "self", ".", "clone", "(", ")", "x", ".", "set_sample", "(", "padding_mode", "=", "padding_mode", ",", "mode", "=", "mode", ",", "remove_out", "=", "remove_out", ")", "if", "size", "is", "not", "None", ":", "crop_target", "=", "_get_crop_target", "(", "size", ",", "mult", "=", "mult", ")", "if", "resize_method", "in", "(", "ResizeMethod", ".", "CROP", ",", "ResizeMethod", ".", "PAD", ")", ":", "target", "=", "_get_resize_target", "(", "x", ",", "crop_target", ",", "do_crop", "=", "(", "resize_method", "==", "ResizeMethod", ".", "CROP", ")", ")", "x", ".", "resize", "(", "target", ")", "elif", "resize_method", "==", "ResizeMethod", ".", "SQUISH", ":", "x", ".", "resize", "(", "(", "x", ".", "shape", "[", "0", "]", ",", ")", "+", "crop_target", ")", "else", ":", "size", "=", "x", ".", "size", "size_tfms", "=", "[", "o", "for", "o", "in", "tfms", "if", "isinstance", "(", "o", ".", "tfm", ",", "TfmCrop", ")", "]", "for", "tfm", "in", "tfms", ":", "if", "tfm", ".", "tfm", "in", "xtra", ":", "x", "=", "tfm", "(", "x", ",", "*", "*", "xtra", "[", "tfm", ".", "tfm", "]", ")", "elif", "tfm", "in", "size_tfms", ":", "if", "resize_method", "in", "(", "ResizeMethod", ".", "CROP", ",", "ResizeMethod", ".", "PAD", ")", ":", "x", "=", "tfm", "(", "x", ",", "size", "=", "_get_crop_target", "(", "size", ",", "mult", "=", "mult", ")", ",", "padding_mode", "=", "padding_mode", ")", "else", ":", "x", "=", "tfm", "(", "x", ")", "return", "x", ".", "refresh", "(", ")" ]
Apply all `tfms` to the `Image`, if `do_resolve` picks value for random args.
[ "Apply", "all", "tfms", "to", "the", "Image", "if", "do_resolve", "picks", "value", "for", "random", "args", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L96-L124
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._px = _grid_sample(self._px, self.flow, **self.sample_kwargs) self.sample_kwargs = {} self._flow = None return self
python
def refresh(self)->None: "Apply any logit, flow, or affine transfers that have been sent to the `Image`." if self._logit_px is not None: self._px = self._logit_px.sigmoid_() self._logit_px = None if self._affine_mat is not None or self._flow is not None: self._px = _grid_sample(self._px, self.flow, **self.sample_kwargs) self.sample_kwargs = {} self._flow = None return self
[ "def", "refresh", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_logit_px", "is", "not", "None", ":", "self", ".", "_px", "=", "self", ".", "_logit_px", ".", "sigmoid_", "(", ")", "self", ".", "_logit_px", "=", "None", "if", "self", ".", "_affine_mat", "is", "not", "None", "or", "self", ".", "_flow", "is", "not", "None", ":", "self", ".", "_px", "=", "_grid_sample", "(", "self", ".", "_px", ",", "self", ".", "flow", ",", "*", "*", "self", ".", "sample_kwargs", ")", "self", ".", "sample_kwargs", "=", "{", "}", "self", ".", "_flow", "=", "None", "return", "self" ]
Apply any logit, flow, or affine transfers that have been sent to the `Image`.
[ "Apply", "any", "logit", "flow", "or", "affine", "transfers", "that", "have", "been", "sent", "to", "the", "Image", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L126-L135
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", "(", "fn", ")" ]
Save the image to `fn`.
[ "Save", "the", "image", "to", "fn", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L137-L140
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_mat = None return self._flow
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_mat = None return self._flow
[ "def", "flow", "(", "self", ")", "->", "FlowField", ":", "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_mat", "=", "None", "return", "self", ".", "_flow" ]
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", ".", "device", ")", "self", ".", "affine_mat", "=", "self", ".", "affine_mat", "@", "m", "return", "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", ".", "_affine_mat" ]
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_image(self, ax=ax, hide_axis=hide_axis, cmap=cmap, figsize=figsize) if y is not None: y.show(ax=ax, **kwargs) if title is not None: ax.set_title(title)
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_image(self, ax=ax, hide_axis=hide_axis, cmap=cmap, figsize=figsize) if y is not None: y.show(ax=ax, **kwargs) if title is not None: ax.set_title(title)
[ "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", ")", ":", "cmap", "=", "ifnone", "(", "cmap", ",", "defaults", ".", "cmap", ")", "ax", "=", "show_image", "(", "self", ",", "ax", "=", "ax", ",", "hide_axis", "=", "hide_axis", ",", "cmap", "=", "cmap", ",", "figsize", "=", "figsize", ")", "if", "y", "is", "not", "None", ":", "y", ".", "show", "(", "ax", "=", "ax", ",", "*", "*", "kwargs", ")", "if", "title", "is", "not", "None", ":", "ax", ".", "set_title", "(", "title", ")" ]
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, interpolation='nearest', alpha=alpha, vmin=0) if title: ax.set_title(title)
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, interpolation='nearest', alpha=alpha, vmin=0) if title: ax.set_title(title)
[ "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", ")", ":", "ax", "=", "show_image", "(", "self", ",", "ax", "=", "ax", ",", "hide_axis", "=", "hide_axis", ",", "cmap", "=", "cmap", ",", "figsize", "=", "figsize", ",", "interpolation", "=", "'nearest'", ",", "alpha", "=", "alpha", ",", "vmin", "=", "0", ")", "if", "title", ":", "ax", ".", "set_title", "(", "title", ")" ]
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.flow_func) != 0: for f in self.flow_func[::-1]: self._flow = f(self._flow) self.transformed = True self.flow_func = [] return self._flow
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.flow_func) != 0: for f in self.flow_func[::-1]: self._flow = f(self._flow) self.transformed = True self.flow_func = [] return self._flow
[ "def", "flow", "(", "self", ")", "->", "FlowField", ":", "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", ".", "flow_func", ")", "!=", "0", ":", "for", "f", "in", "self", ".", "flow_func", "[", ":", ":", "-", "1", "]", ":", "self", ".", "_flow", "=", "f", "(", "self", ".", "_flow", ")", "self", ".", "transformed", "=", "True", "self", ".", "flow_func", "=", "[", "]", "return", "self", ".", "_flow" ]
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, *args, **kwargs)) return self
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, *args, **kwargs)) return self
[ "def", "coord", "(", "self", ",", "func", ":", "CoordFunc", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "'ImagePoints'", ":", "if", "'invert'", "in", "kwargs", ":", "kwargs", "[", "'invert'", "]", "=", "True", "else", ":", "warn", "(", "f\"{func.__name__} isn't implemented for {self.__class__}.\"", ")", "self", ".", "flow_func", ".", "append", "(", "partial", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")", "return", "self" ]
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_points_out(flow) self.transformed=False return flow.flow.flip(1)
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_points_out(flow) self.transformed=False return flow.flow.flip(1)
[ "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", "self", ".", "sample_kwargs", "[", "'remove_out'", "]", ":", "flow", "=", "_remove_points_out", "(", "flow", ")", "self", ".", "transformed", "=", "False", "return", "flow", ".", "flow", ".", "flip", "(", "1", ")" ]
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': 10, 'marker': '.', 'c': 'r', **kwargs} ax.scatter(pnt[:, 0], pnt[:, 1], **params) if hide_axis: ax.axis('off') if title: ax.set_title(title)
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': 10, 'marker': '.', 'c': 'r', **kwargs} ax.scatter(pnt[:, 0], pnt[:, 1], **params) if hide_axis: ax.axis('off') if title: ax.set_title(title)
[ "def", "show", "(", "self", ",", "ax", ":", "plt", ".", "Axes", "=", "None", ",", "figsize", ":", "tuple", "=", "(", "3", ",", "3", ")", ",", "title", ":", "Optional", "[", "str", "]", "=", "None", ",", "hide_axis", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ")", ":", "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'", ":", "10", ",", "'marker'", ":", "'.'", ",", "'c'", ":", "'r'", ",", "*", "*", "kwargs", "}", "ax", ".", "scatter", "(", "pnt", "[", ":", ",", "0", "]", ",", "pnt", "[", ":", ",", "1", "]", ",", "*", "*", "params", ")", "if", "hide_axis", ":", "ax", ".", "axis", "(", "'off'", ")", "if", "title", ":", "ax", ".", "set_title", "(", "title", ")" ]
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", "=", "False", ",", "y_first", "=", "False", ",", "labels", "=", "self", ".", "labels", ",", "pad_idx", "=", "self", ".", "pad_idx", ")" ]
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 bb in bboxes]) bboxes = tensor(bboxes).float() tr_corners = torch.cat([bboxes[:,0][:,None], bboxes[:,3][:,None]], 1) bl_corners = bboxes[:,1:3].flip(1) bboxes = torch.cat([bboxes[:,:2], tr_corners, bl_corners, bboxes[:,2:]], 1) flow = FlowField((h,w), bboxes.view(-1,2)) return cls(flow, labels=labels, classes=classes, pad_idx=pad_idx, y_first=True, scale=scale)
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 bb in bboxes]) bboxes = tensor(bboxes).float() tr_corners = torch.cat([bboxes[:,0][:,None], bboxes[:,3][:,None]], 1) bl_corners = bboxes[:,1:3].flip(1) bboxes = torch.cat([bboxes[:,:2], tr_corners, bl_corners, bboxes[:,2:]], 1) flow = FlowField((h,w), bboxes.view(-1,2)) return cls(flow, labels=labels, classes=classes, pad_idx=pad_idx, y_first=True, scale=scale)
[ "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'", ":", "if", "isinstance", "(", "bboxes", ",", "np", ".", "ndarray", ")", "and", "bboxes", ".", "dtype", "==", "np", ".", "object", ":", "bboxes", "=", "np", ".", "array", "(", "[", "bb", "for", "bb", "in", "bboxes", "]", ")", "bboxes", "=", "tensor", "(", "bboxes", ")", ".", "float", "(", ")", "tr_corners", "=", "torch", ".", "cat", "(", "[", "bboxes", "[", ":", ",", "0", "]", "[", ":", ",", "None", "]", ",", "bboxes", "[", ":", ",", "3", "]", "[", ":", ",", "None", "]", "]", ",", "1", ")", "bl_corners", "=", "bboxes", "[", ":", ",", "1", ":", "3", "]", ".", "flip", "(", "1", ")", "bboxes", "=", "torch", ".", "cat", "(", "[", "bboxes", "[", ":", ",", ":", "2", "]", ",", "tr_corners", ",", "bl_corners", ",", "bboxes", "[", ":", ",", "2", ":", "]", "]", ",", "1", ")", "flow", "=", "FlowField", "(", "(", "h", ",", "w", ")", ",", "bboxes", ".", "view", "(", "-", "1", ",", "2", ")", ")", "return", "cls", "(", "flow", ",", "labels", "=", "labels", ",", "classes", "=", "classes", ",", "pad_idx", "=", "pad_idx", ",", "y_first", "=", "True", ",", "scale", "=", "scale", ")" ]
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.flow.size bboxes.add_(1).mul_(torch.tensor([h/2, w/2, h/2, w/2])).long() for i, bbox in enumerate(bboxes): if lbls is not None: text = str(lbls[i]) else: text=None _draw_rect(ax, bb2hw(bbox), text=text, color=color)
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.flow.size bboxes.add_(1).mul_(torch.tensor([h/2, w/2, h/2, w/2])).long() for i, bbox in enumerate(bboxes): if lbls is not None: text = str(lbls[i]) else: text=None _draw_rect(ax, bb2hw(bbox), text=text, color=color)
[ "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", ")", ":", "if", "ax", "is", "None", ":", "_", ",", "ax", "=", "plt", ".", "subplots", "(", "figsize", "=", "figsize", ")", "bboxes", ",", "lbls", "=", "self", ".", "_compute_boxes", "(", ")", "h", ",", "w", "=", "self", ".", "flow", ".", "size", "bboxes", ".", "add_", "(", "1", ")", ".", "mul_", "(", "torch", ".", "tensor", "(", "[", "h", "/", "2", ",", "w", "/", "2", ",", "h", "/", "2", ",", "w", "/", "2", "]", ")", ")", ".", "long", "(", ")", "for", "i", ",", "bbox", "in", "enumerate", "(", "bboxes", ")", ":", "if", "lbls", "is", "not", "None", ":", "text", "=", "str", "(", "lbls", "[", "i", "]", ")", "else", ":", "text", "=", "None", "_draw_rect", "(", "ax", ",", "bb2hw", "(", "bbox", ")", ",", "text", "=", "text", ",", "color", "=", "color", ")" ]
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", ")", "(", "self", ".", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "return", "self", ".", "func", "(", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
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", ")", "if", "data", "else", "modelpath4file", "(", "name", ",", "ext", "=", "ext", ")" ]
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", "(", "ext", ")", ".", "exists", "(", ")", ":", "return", "local_path", "else", ":", "return", "Config", ".", "model_path", "(", ")", "/", "filename" ]
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_archive_path() / filename else: return Config.data_path() / filename
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_archive_path() / filename else: return Config.data_path() / filename
[ "def", "datapath4file", "(", "filename", ",", "ext", ":", "str", "=", "'.tgz'", ",", "archive", "=", "True", ")", ":", "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_archive_path", "(", ")", "/", "filename", "else", ":", "return", "Config", ".", "data_path", "(", ")", "/", "filename" ]
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}') download_url(f'{url}{ext}', fname) return fname
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}') download_url(f'{url}{ext}', fname) return fname
[ "def", "download_data", "(", "url", ":", "str", ",", "fname", ":", "PathOrStr", "=", "None", ",", "data", ":", "bool", "=", "True", ",", "ext", ":", "str", "=", "'.tgz'", ")", "->", "Path", ":", "fname", "=", "Path", "(", "ifnone", "(", "fname", ",", "_url2tgz", "(", "url", ",", "data", ",", "ext", "=", "ext", ")", ")", ")", "os", ".", "makedirs", "(", "fname", ".", "parent", ",", "exist_ok", "=", "True", ")", "if", "not", "fname", ".", "exists", "(", ")", ":", "print", "(", "f'Downloading {url}'", ")", "download_url", "(", "f'{url}{ext}'", ",", "fname", ")", "return", "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, data))) if force_download or (fname.exists() and url in _checks and _check_file(fname) != _checks[url]): print(f"A new version of the {'dataset' if data else 'model'} is available.") if fname.exists(): os.remove(fname) if dest.exists(): shutil.rmtree(dest) if not dest.exists(): fname = download_data(url, fname=fname, data=data) if url in _checks: assert _check_file(fname) == _checks[url], f"Downloaded file {fname} does not match checksum expected! Remove that file from {Config().data_archive_path()} and try your code again." tarfile.open(fname, 'r:gz').extractall(dest.parent) return dest
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, data))) if force_download or (fname.exists() and url in _checks and _check_file(fname) != _checks[url]): print(f"A new version of the {'dataset' if data else 'model'} is available.") if fname.exists(): os.remove(fname) if dest.exists(): shutil.rmtree(dest) if not dest.exists(): fname = download_data(url, fname=fname, data=data) if url in _checks: assert _check_file(fname) == _checks[url], f"Downloaded file {fname} does not match checksum expected! Remove that file from {Config().data_archive_path()} and try your code again." tarfile.open(fname, 'r:gz').extractall(dest.parent) return dest
[ "def", "untar_data", "(", "url", ":", "str", ",", "fname", ":", "PathOrStr", "=", "None", ",", "dest", ":", "PathOrStr", "=", "None", ",", "data", "=", "True", ",", "force_download", "=", "False", ")", "->", "Path", ":", "dest", "=", "url2path", "(", "url", ",", "data", ")", "if", "dest", "is", "None", "else", "Path", "(", "dest", ")", "/", "url2name", "(", "url", ")", "fname", "=", "Path", "(", "ifnone", "(", "fname", ",", "_url2tgz", "(", "url", ",", "data", ")", ")", ")", "if", "force_download", "or", "(", "fname", ".", "exists", "(", ")", "and", "url", "in", "_checks", "and", "_check_file", "(", "fname", ")", "!=", "_checks", "[", "url", "]", ")", ":", "print", "(", "f\"A new version of the {'dataset' if data else 'model'} is available.\"", ")", "if", "fname", ".", "exists", "(", ")", ":", "os", ".", "remove", "(", "fname", ")", "if", "dest", ".", "exists", "(", ")", ":", "shutil", ".", "rmtree", "(", "dest", ")", "if", "not", "dest", ".", "exists", "(", ")", ":", "fname", "=", "download_data", "(", "url", ",", "fname", "=", "fname", ",", "data", "=", "data", ")", "if", "url", "in", "_checks", ":", "assert", "_check_file", "(", "fname", ")", "==", "_checks", "[", "url", "]", ",", "f\"Downloaded file {fname} does not match checksum expected! Remove that file from {Config().data_archive_path()} and try your code again.\"", "tarfile", ".", "open", "(", "fname", ",", "'r:gz'", ")", ".", "extractall", "(", "dest", ".", "parent", ")", "return", "dest" ]
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 open(fpath, 'r') as yaml_file: return yaml.safe_load(yaml_file)
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 open(fpath, 'r') as yaml_file: return yaml.safe_load(yaml_file)
[ "def", "get", "(", "cls", ",", "fpath", "=", "None", ",", "create_missing", "=", "True", ")", ":", "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", "open", "(", "fpath", ",", "'r'", ")", "as", "yaml_file", ":", "return", "yaml", ".", "safe_load", "(", "yaml_file", ")" ]
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, yaml_file, default_flow_style=False)
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, yaml_file, default_flow_style=False)
[ "def", "create", "(", "cls", ",", "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", ",", "yaml_file", ",", "default_flow_style", "=", "False", ")" ]
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) lambd = last_input.new(lambd) shuffle = torch.randperm(last_target.size(0)).to(last_input.device) x1, y1 = last_input[shuffle], last_target[shuffle] if self.stack_x: new_input = [last_input, last_input[shuffle], lambd] else: new_input = (last_input * lambd.view(lambd.size(0),1,1,1) + x1 * (1-lambd).view(lambd.size(0),1,1,1)) if self.stack_y: new_target = torch.cat([last_target[:,None].float(), y1[:,None].float(), lambd[:,None].float()], 1) else: if len(last_target.shape) == 2: lambd = lambd.unsqueeze(1).float() new_target = last_target.float() * lambd + y1.float() * (1-lambd) return {'last_input': new_input, 'last_target': new_target}
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) lambd = last_input.new(lambd) shuffle = torch.randperm(last_target.size(0)).to(last_input.device) x1, y1 = last_input[shuffle], last_target[shuffle] if self.stack_x: new_input = [last_input, last_input[shuffle], lambd] else: new_input = (last_input * lambd.view(lambd.size(0),1,1,1) + x1 * (1-lambd).view(lambd.size(0),1,1,1)) if self.stack_y: new_target = torch.cat([last_target[:,None].float(), y1[:,None].float(), lambd[:,None].float()], 1) else: if len(last_target.shape) == 2: lambd = lambd.unsqueeze(1).float() new_target = last_target.float() * lambd + y1.float() * (1-lambd) return {'last_input': new_input, 'last_target': new_target}
[ "def", "on_batch_begin", "(", "self", ",", "last_input", ",", "last_target", ",", "train", ",", "*", "*", "kwargs", ")", ":", "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", ")", "lambd", "=", "last_input", ".", "new", "(", "lambd", ")", "shuffle", "=", "torch", ".", "randperm", "(", "last_target", ".", "size", "(", "0", ")", ")", ".", "to", "(", "last_input", ".", "device", ")", "x1", ",", "y1", "=", "last_input", "[", "shuffle", "]", ",", "last_target", "[", "shuffle", "]", "if", "self", ".", "stack_x", ":", "new_input", "=", "[", "last_input", ",", "last_input", "[", "shuffle", "]", ",", "lambd", "]", "else", ":", "new_input", "=", "(", "last_input", "*", "lambd", ".", "view", "(", "lambd", ".", "size", "(", "0", ")", ",", "1", ",", "1", ",", "1", ")", "+", "x1", "*", "(", "1", "-", "lambd", ")", ".", "view", "(", "lambd", ".", "size", "(", "0", ")", ",", "1", ",", "1", ",", "1", ")", ")", "if", "self", ".", "stack_y", ":", "new_target", "=", "torch", ".", "cat", "(", "[", "last_target", "[", ":", ",", "None", "]", ".", "float", "(", ")", ",", "y1", "[", ":", ",", "None", "]", ".", "float", "(", ")", ",", "lambd", "[", ":", ",", "None", "]", ".", "float", "(", ")", "]", ",", "1", ")", "else", ":", "if", "len", "(", "last_target", ".", "shape", ")", "==", "2", ":", "lambd", "=", "lambd", ".", "unsqueeze", "(", "1", ")", ".", "float", "(", ")", "new_target", "=", "last_target", ".", "float", "(", ")", "*", "lambd", "+", "y1", ".", "float", "(", ")", "*", "(", "1", "-", "lambd", ")", "return", "{", "'last_input'", ":", "new_input", ",", "'last_target'", ":", "new_target", "}" ]
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)) attr = ['Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear', 'Is_month_end', 'Is_month_start', 'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start'] if time: attr = attr + ['Hour', 'Minute', 'Second'] for n in attr: df[prefix + n] = getattr(field.dt, n.lower()) df[prefix + 'Elapsed'] = field.astype(np.int64) // 10 ** 9 if drop: df.drop(field_name, axis=1, inplace=True) return df
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)) attr = ['Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear', 'Is_month_end', 'Is_month_start', 'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start'] if time: attr = attr + ['Hour', 'Minute', 'Second'] for n in attr: df[prefix + n] = getattr(field.dt, n.lower()) df[prefix + 'Elapsed'] = field.astype(np.int64) // 10 ** 9 if drop: df.drop(field_name, axis=1, inplace=True) return df
[ "def", "add_datepart", "(", "df", ":", "DataFrame", ",", "field_name", ":", "str", ",", "prefix", ":", "str", "=", "None", ",", "drop", ":", "bool", "=", "True", ",", "time", ":", "bool", "=", "False", ")", ":", "make_date", "(", "df", ",", "field_name", ")", "field", "=", "df", "[", "field_name", "]", "prefix", "=", "ifnone", "(", "prefix", ",", "re", ".", "sub", "(", "'[Dd]ate$'", ",", "''", ",", "field_name", ")", ")", "attr", "=", "[", "'Year'", ",", "'Month'", ",", "'Week'", ",", "'Day'", ",", "'Dayofweek'", ",", "'Dayofyear'", ",", "'Is_month_end'", ",", "'Is_month_start'", ",", "'Is_quarter_end'", ",", "'Is_quarter_start'", ",", "'Is_year_end'", ",", "'Is_year_start'", "]", "if", "time", ":", "attr", "=", "attr", "+", "[", "'Hour'", ",", "'Minute'", ",", "'Second'", "]", "for", "n", "in", "attr", ":", "df", "[", "prefix", "+", "n", "]", "=", "getattr", "(", "field", ".", "dt", ",", "n", ".", "lower", "(", ")", ")", "df", "[", "prefix", "+", "'Elapsed'", "]", "=", "field", ".", "astype", "(", "np", ".", "int64", ")", "//", "10", "**", "9", "if", "drop", ":", "df", ".", "drop", "(", "field_name", ",", "axis", "=", "1", ",", "inplace", "=", "True", ")", "return", "df" ]
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] > max_card or df[label].dtype == float: cont_names.append(label) else: cat_names.append(label) return cont_names, cat_names
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] > max_card or df[label].dtype == float: cont_names.append(label) else: cat_names.append(label) return cont_names, cat_names
[ "def", "cont_cat_split", "(", "df", ",", "max_card", "=", "20", ",", "dep_var", "=", "None", ")", "->", "Tuple", "[", "List", ",", "List", "]", ":", "cont_names", ",", "cat_names", "=", "[", "]", ",", "[", "]", "for", "label", "in", "df", ":", "if", "label", "==", "dep_var", ":", "continue", "if", "df", "[", "label", "]", ".", "dtype", "==", "int", "and", "df", "[", "label", "]", ".", "unique", "(", ")", ".", "shape", "[", "0", "]", ">", "max_card", "or", "df", "[", "label", "]", ".", "dtype", "==", "float", ":", "cont_names", ".", "append", "(", "label", ")", "else", ":", "cat_names", ".", "append", "(", "label", ")", "return", "cont_names", ",", "cat_names" ]
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", "[", ":", ",", "n", "]", ".", "astype", "(", "'category'", ")", ".", "cat", ".", "as_ordered", "(", ")", "self", ".", "categories", "[", "n", "]", "=", "df", "[", "n", "]", ".", "cat", ".", "categories" ]
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 sure it doesn't belong in the categorical set of columns?""") self.means[n],self.stds[n] = df[n].mean(),df[n].std() df[n] = (df[n]-self.means[n]) / (1e-7 + self.stds[n])
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 sure it doesn't belong in the categorical set of columns?""") self.means[n],self.stds[n] = df[n].mean(),df[n].std() df[n] = (df[n]-self.means[n]) / (1e-7 + self.stds[n])
[ "def", "apply_train", "(", "self", ",", "df", ":", "DataFrame", ")", ":", "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.\n Are you sure it doesn't belong in the categorical set of columns?\"\"\"", ")", "self", ".", "means", "[", "n", "]", ",", "self", ".", "stds", "[", "n", "]", "=", "df", "[", "n", "]", ".", "mean", "(", ")", ",", "df", "[", "n", "]", ".", "std", "(", ")", "df", "[", "n", "]", "=", "(", "df", "[", "n", "]", "-", "self", ".", "means", "[", "n", "]", ")", "/", "(", "1e-7", "+", "self", ".", "stds", "[", "n", "]", ")" ]
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", "(", "n", ",", "int", "(", "emb_sz_rule", "(", "n_cat", ")", ")", ")", "# rule of thumb", "return", "n_cat", ",", "sz" ]
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 params." emb_szs = data.get_emb_szs(ifnone(emb_szs, {})) model = TabularModel(emb_szs, len(data.cont_names), out_sz=data.c, layers=layers, ps=ps, emb_drop=emb_drop, y_range=y_range, use_bn=use_bn) return Learner(data, model, metrics=metrics, **learn_kwargs)
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 params." emb_szs = data.get_emb_szs(ifnone(emb_szs, {})) model = TabularModel(emb_szs, len(data.cont_names), out_sz=data.c, layers=layers, ps=ps, emb_drop=emb_drop, y_range=y_range, use_bn=use_bn) return Learner(data, model, metrics=metrics, **learn_kwargs)
[ "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", ")", ":", "emb_szs", "=", "data", ".", "get_emb_szs", "(", "ifnone", "(", "emb_szs", ",", "{", "}", ")", ")", "model", "=", "TabularModel", "(", "emb_szs", ",", "len", "(", "data", ".", "cont_names", ")", ",", "out_sz", "=", "data", ".", "c", ",", "layers", "=", "layers", ",", "ps", "=", "ps", ",", "emb_drop", "=", "emb_drop", ",", "y_range", "=", "y_range", ",", "use_bn", "=", "use_bn", ")", "return", "Learner", "(", "data", ",", "model", ",", "metrics", "=", "metrics", ",", "*", "*", "learn_kwargs", ")" ]
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[Callable]]=None, device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False)->DataBunch: "Create a `DataBunch` from `df` and `valid_idx` with `dep_var`. `kwargs` are passed to `DataBunch.create`." cat_names = ifnone(cat_names, []).copy() cont_names = ifnone(cont_names, list(set(df)-set(cat_names)-{dep_var})) procs = listify(procs) src = (TabularList.from_df(df, path=path, cat_names=cat_names, cont_names=cont_names, procs=procs) .split_by_idx(valid_idx)) src = src.label_from_df(cols=dep_var) if classes is None else src.label_from_df(cols=dep_var, classes=classes) if test_df is not None: src.add_test(TabularList.from_df(test_df, cat_names=cat_names, cont_names=cont_names, processor = src.train.x.processor)) return src.databunch(path=path, bs=bs, val_bs=val_bs, num_workers=num_workers, device=device, collate_fn=collate_fn, no_check=no_check)
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[Callable]]=None, device:torch.device=None, collate_fn:Callable=data_collate, no_check:bool=False)->DataBunch: "Create a `DataBunch` from `df` and `valid_idx` with `dep_var`. `kwargs` are passed to `DataBunch.create`." cat_names = ifnone(cat_names, []).copy() cont_names = ifnone(cont_names, list(set(df)-set(cat_names)-{dep_var})) procs = listify(procs) src = (TabularList.from_df(df, path=path, cat_names=cat_names, cont_names=cont_names, procs=procs) .split_by_idx(valid_idx)) src = src.label_from_df(cols=dep_var) if classes is None else src.label_from_df(cols=dep_var, classes=classes) if test_df is not None: src.add_test(TabularList.from_df(test_df, cat_names=cat_names, cont_names=cont_names, processor = src.train.x.processor)) return src.databunch(path=path, bs=bs, val_bs=val_bs, num_workers=num_workers, device=device, collate_fn=collate_fn, no_check=no_check)
[ "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", "[", "Callable", "]", "]", "=", "None", ",", "device", ":", "torch", ".", "device", "=", "None", ",", "collate_fn", ":", "Callable", "=", "data_collate", ",", "no_check", ":", "bool", "=", "False", ")", "->", "DataBunch", ":", "cat_names", "=", "ifnone", "(", "cat_names", ",", "[", "]", ")", ".", "copy", "(", ")", "cont_names", "=", "ifnone", "(", "cont_names", ",", "list", "(", "set", "(", "df", ")", "-", "set", "(", "cat_names", ")", "-", "{", "dep_var", "}", ")", ")", "procs", "=", "listify", "(", "procs", ")", "src", "=", "(", "TabularList", ".", "from_df", "(", "df", ",", "path", "=", "path", ",", "cat_names", "=", "cat_names", ",", "cont_names", "=", "cont_names", ",", "procs", "=", "procs", ")", ".", "split_by_idx", "(", "valid_idx", ")", ")", "src", "=", "src", ".", "label_from_df", "(", "cols", "=", "dep_var", ")", "if", "classes", "is", "None", "else", "src", ".", "label_from_df", "(", "cols", "=", "dep_var", ",", "classes", "=", "classes", ")", "if", "test_df", "is", "not", "None", ":", "src", ".", "add_test", "(", "TabularList", ".", "from_df", "(", "test_df", ",", "cat_names", "=", "cat_names", ",", "cont_names", "=", "cont_names", ",", "processor", "=", "src", ".", "train", ".", "x", ".", "processor", ")", ")", "return", "src", ".", "databunch", "(", "path", "=", "path", ",", "bs", "=", "bs", ",", "val_bs", "=", "val_bs", ",", "num_workers", "=", "num_workers", ",", "device", "=", "device", ",", "collate_fn", "=", "collate_fn", ",", "no_check", "=", "no_check", ")" ]
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: string to int mapping, trained classifer model """ # load the int to string mapping file itos = pickle.load(Path(itos_filename).open('rb')) # turn it into a string to int mapping (which is what we need) stoi = collections.defaultdict(lambda:0, {str(v):int(k) for k,v in enumerate(itos)}) # these parameters aren't used, but this is the easiest way to get a model bptt,em_sz,nh,nl = 70,400,1150,3 dps = np.array([0.4,0.5,0.05,0.3,0.4])*0.5 vs = len(itos) model = get_rnn_classifer(bptt, 20*70, num_classes, vs, emb_sz=em_sz, n_hid=nh, n_layers=nl, pad_token=1, layers=[em_sz*3, 50, num_classes], drops=[dps[4], 0.1], dropouti=dps[0], wdrop=dps[1], dropoute=dps[2], dropouth=dps[3]) # load the trained classifier model.load_state_dict(torch.load(classifier_filename, map_location=lambda storage, loc: storage)) # put the classifier into evaluation mode model.reset() model.eval() return stoi, model
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: string to int mapping, trained classifer model """ # load the int to string mapping file itos = pickle.load(Path(itos_filename).open('rb')) # turn it into a string to int mapping (which is what we need) stoi = collections.defaultdict(lambda:0, {str(v):int(k) for k,v in enumerate(itos)}) # these parameters aren't used, but this is the easiest way to get a model bptt,em_sz,nh,nl = 70,400,1150,3 dps = np.array([0.4,0.5,0.05,0.3,0.4])*0.5 vs = len(itos) model = get_rnn_classifer(bptt, 20*70, num_classes, vs, emb_sz=em_sz, n_hid=nh, n_layers=nl, pad_token=1, layers=[em_sz*3, 50, num_classes], drops=[dps[4], 0.1], dropouti=dps[0], wdrop=dps[1], dropoute=dps[2], dropouth=dps[3]) # load the trained classifier model.load_state_dict(torch.load(classifier_filename, map_location=lambda storage, loc: storage)) # put the classifier into evaluation mode model.reset() model.eval() return stoi, model
[ "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 it into a string to int mapping (which is what we need)", "stoi", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "0", ",", "{", "str", "(", "v", ")", ":", "int", "(", "k", ")", "for", "k", ",", "v", "in", "enumerate", "(", "itos", ")", "}", ")", "# these parameters aren't used, but this is the easiest way to get a model", "bptt", ",", "em_sz", ",", "nh", ",", "nl", "=", "70", ",", "400", ",", "1150", ",", "3", "dps", "=", "np", ".", "array", "(", "[", "0.4", ",", "0.5", ",", "0.05", ",", "0.3", ",", "0.4", "]", ")", "*", "0.5", "vs", "=", "len", "(", "itos", ")", "model", "=", "get_rnn_classifer", "(", "bptt", ",", "20", "*", "70", ",", "num_classes", ",", "vs", ",", "emb_sz", "=", "em_sz", ",", "n_hid", "=", "nh", ",", "n_layers", "=", "nl", ",", "pad_token", "=", "1", ",", "layers", "=", "[", "em_sz", "*", "3", ",", "50", ",", "num_classes", "]", ",", "drops", "=", "[", "dps", "[", "4", "]", ",", "0.1", "]", ",", "dropouti", "=", "dps", "[", "0", "]", ",", "wdrop", "=", "dps", "[", "1", "]", ",", "dropoute", "=", "dps", "[", "2", "]", ",", "dropouth", "=", "dps", "[", "3", "]", ")", "# load the trained classifier", "model", ".", "load_state_dict", "(", "torch", ".", "load", "(", "classifier_filename", ",", "map_location", "=", "lambda", "storage", ",", "loc", ":", "storage", ")", ")", "# put the classifier into evaluation mode", "model", ".", "reset", "(", ")", "model", ".", "eval", "(", ")", "return", "stoi", ",", "model" ]
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 on arrays of input. # We only have a single input, so turn it into a 1x1 array texts = [input_str] # tokenize using the fastai wrapper around spacy tok = Tokenizer().proc_all_mp(partition_by_cores(texts)) # turn into integers for each word encoded = [stoi[p] for p in tok[0]] # we want a [x,1] array where x is the number # of words inputted (including the prefix tokens) ary = np.reshape(np.array(encoded),(-1,1)) # turn this array into a tensor tensor = torch.from_numpy(ary) # wrap in a torch Variable variable = Variable(tensor) # do the predictions predictions = model(variable) # convert back to numpy numpy_preds = predictions[0].data.numpy() return softmax(numpy_preds[0])[0]
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 on arrays of input. # We only have a single input, so turn it into a 1x1 array texts = [input_str] # tokenize using the fastai wrapper around spacy tok = Tokenizer().proc_all_mp(partition_by_cores(texts)) # turn into integers for each word encoded = [stoi[p] for p in tok[0]] # we want a [x,1] array where x is the number # of words inputted (including the prefix tokens) ary = np.reshape(np.array(encoded),(-1,1)) # turn this array into a tensor tensor = torch.from_numpy(ary) # wrap in a torch Variable variable = Variable(tensor) # do the predictions predictions = model(variable) # convert back to numpy numpy_preds = predictions[0].data.numpy() return softmax(numpy_preds[0])[0]
[ "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.", "# We only have a single input, so turn it into a 1x1 array", "texts", "=", "[", "input_str", "]", "# tokenize using the fastai wrapper around spacy", "tok", "=", "Tokenizer", "(", ")", ".", "proc_all_mp", "(", "partition_by_cores", "(", "texts", ")", ")", "# turn into integers for each word", "encoded", "=", "[", "stoi", "[", "p", "]", "for", "p", "in", "tok", "[", "0", "]", "]", "# we want a [x,1] array where x is the number", "# of words inputted (including the prefix tokens)", "ary", "=", "np", ".", "reshape", "(", "np", ".", "array", "(", "encoded", ")", ",", "(", "-", "1", ",", "1", ")", ")", "# turn this array into a tensor", "tensor", "=", "torch", ".", "from_numpy", "(", "ary", ")", "# wrap in a torch Variable", "variable", "=", "Variable", "(", "tensor", ")", "# do the predictions", "predictions", "=", "model", "(", "variable", ")", "# convert back to numpy", "numpy_preds", "=", "predictions", "[", "0", "]", ".", "data", ".", "numpy", "(", ")", "return", "softmax", "(", "numpy_preds", "[", "0", "]", ")", "[", "0", "]" ]
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 options object. :Args: - caps - A dictionary of capabilities requested by the caller. """ caps = copy.deepcopy(caps) profile = caps.get('firefox_profile') always_match = {} if caps.get('proxy') and caps['proxy'].get('proxyType'): caps['proxy']['proxyType'] = caps['proxy']['proxyType'].lower() for k, v in caps.items(): if v and k in _OSS_W3C_CONVERSION: always_match[_OSS_W3C_CONVERSION[k]] = v.lower() if k == 'platform' else v if k in _W3C_CAPABILITY_NAMES or ':' in k: always_match[k] = v if profile: moz_opts = always_match.get('moz:firefoxOptions', {}) # If it's already present, assume the caller did that intentionally. if 'profile' not in moz_opts: # Don't mutate the original capabilities. new_opts = copy.deepcopy(moz_opts) new_opts['profile'] = profile always_match['moz:firefoxOptions'] = new_opts return {"firstMatch": [{}], "alwaysMatch": always_match}
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 options object. :Args: - caps - A dictionary of capabilities requested by the caller. """ caps = copy.deepcopy(caps) profile = caps.get('firefox_profile') always_match = {} if caps.get('proxy') and caps['proxy'].get('proxyType'): caps['proxy']['proxyType'] = caps['proxy']['proxyType'].lower() for k, v in caps.items(): if v and k in _OSS_W3C_CONVERSION: always_match[_OSS_W3C_CONVERSION[k]] = v.lower() if k == 'platform' else v if k in _W3C_CAPABILITY_NAMES or ':' in k: always_match[k] = v if profile: moz_opts = always_match.get('moz:firefoxOptions', {}) # If it's already present, assume the caller did that intentionally. if 'profile' not in moz_opts: # Don't mutate the original capabilities. new_opts = copy.deepcopy(moz_opts) new_opts['profile'] = profile always_match['moz:firefoxOptions'] = new_opts return {"firstMatch": [{}], "alwaysMatch": always_match}
[ "def", "_make_w3c_caps", "(", "caps", ")", ":", "caps", "=", "copy", ".", "deepcopy", "(", "caps", ")", "profile", "=", "caps", ".", "get", "(", "'firefox_profile'", ")", "always_match", "=", "{", "}", "if", "caps", ".", "get", "(", "'proxy'", ")", "and", "caps", "[", "'proxy'", "]", ".", "get", "(", "'proxyType'", ")", ":", "caps", "[", "'proxy'", "]", "[", "'proxyType'", "]", "=", "caps", "[", "'proxy'", "]", "[", "'proxyType'", "]", ".", "lower", "(", ")", "for", "k", ",", "v", "in", "caps", ".", "items", "(", ")", ":", "if", "v", "and", "k", "in", "_OSS_W3C_CONVERSION", ":", "always_match", "[", "_OSS_W3C_CONVERSION", "[", "k", "]", "]", "=", "v", ".", "lower", "(", ")", "if", "k", "==", "'platform'", "else", "v", "if", "k", "in", "_W3C_CAPABILITY_NAMES", "or", "':'", "in", "k", ":", "always_match", "[", "k", "]", "=", "v", "if", "profile", ":", "moz_opts", "=", "always_match", ".", "get", "(", "'moz:firefoxOptions'", ",", "{", "}", ")", "# If it's already present, assume the caller did that intentionally.", "if", "'profile'", "not", "in", "moz_opts", ":", "# Don't mutate the original capabilities.", "new_opts", "=", "copy", ".", "deepcopy", "(", "moz_opts", ")", "new_opts", "[", "'profile'", "]", "=", "profile", "always_match", "[", "'moz:firefoxOptions'", "]", "=", "new_opts", "return", "{", "\"firstMatch\"", ":", "[", "{", "}", "]", ",", "\"alwaysMatch\"", ":", "always_match", "}" ]
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: - caps - A dictionary of capabilities requested by the caller.
[ "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 browser on. - javascript_enabled - Whether the new session should support JavaScript. - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested. """ if not isinstance(capabilities, dict): raise InvalidArgumentException("Capabilities must be a dictionary") if browser_profile: if "moz:firefoxOptions" in capabilities: capabilities["moz:firefoxOptions"]["profile"] = browser_profile.encoded else: capabilities.update({'firefox_profile': browser_profile.encoded}) w3c_caps = _make_w3c_caps(capabilities) parameters = {"capabilities": w3c_caps, "desiredCapabilities": capabilities} response = self.execute(Command.NEW_SESSION, parameters) if 'sessionId' not in response: response = response['value'] self.session_id = response['sessionId'] self.capabilities = response.get('value') # if capabilities is none we are probably speaking to # a W3C endpoint if self.capabilities is None: self.capabilities = response.get('capabilities') # Double check to see if we have a W3C Compliant browser self.w3c = response.get('status') is None self.command_executor.w3c = self.w3c
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 browser on. - javascript_enabled - Whether the new session should support JavaScript. - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested. """ if not isinstance(capabilities, dict): raise InvalidArgumentException("Capabilities must be a dictionary") if browser_profile: if "moz:firefoxOptions" in capabilities: capabilities["moz:firefoxOptions"]["profile"] = browser_profile.encoded else: capabilities.update({'firefox_profile': browser_profile.encoded}) w3c_caps = _make_w3c_caps(capabilities) parameters = {"capabilities": w3c_caps, "desiredCapabilities": capabilities} response = self.execute(Command.NEW_SESSION, parameters) if 'sessionId' not in response: response = response['value'] self.session_id = response['sessionId'] self.capabilities = response.get('value') # if capabilities is none we are probably speaking to # a W3C endpoint if self.capabilities is None: self.capabilities = response.get('capabilities') # Double check to see if we have a W3C Compliant browser self.w3c = response.get('status') is None self.command_executor.w3c = self.w3c
[ "def", "start_session", "(", "self", ",", "capabilities", ",", "browser_profile", "=", "None", ")", ":", "if", "not", "isinstance", "(", "capabilities", ",", "dict", ")", ":", "raise", "InvalidArgumentException", "(", "\"Capabilities must be a dictionary\"", ")", "if", "browser_profile", ":", "if", "\"moz:firefoxOptions\"", "in", "capabilities", ":", "capabilities", "[", "\"moz:firefoxOptions\"", "]", "[", "\"profile\"", "]", "=", "browser_profile", ".", "encoded", "else", ":", "capabilities", ".", "update", "(", "{", "'firefox_profile'", ":", "browser_profile", ".", "encoded", "}", ")", "w3c_caps", "=", "_make_w3c_caps", "(", "capabilities", ")", "parameters", "=", "{", "\"capabilities\"", ":", "w3c_caps", ",", "\"desiredCapabilities\"", ":", "capabilities", "}", "response", "=", "self", ".", "execute", "(", "Command", ".", "NEW_SESSION", ",", "parameters", ")", "if", "'sessionId'", "not", "in", "response", ":", "response", "=", "response", "[", "'value'", "]", "self", ".", "session_id", "=", "response", "[", "'sessionId'", "]", "self", ".", "capabilities", "=", "response", ".", "get", "(", "'value'", ")", "# if capabilities is none we are probably speaking to", "# a W3C endpoint", "if", "self", ".", "capabilities", "is", "None", ":", "self", ".", "capabilities", "=", "response", ".", "get", "(", "'capabilities'", ")", "# Double check to see if we have a W3C Compliant browser", "self", ".", "w3c", "=", "response", ".", "get", "(", "'status'", ")", "is", "None", "self", ".", "command_executor", ".", "w3c", "=", "self", ".", "w3c" ]
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 JavaScript. - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested.
[ "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: The command's JSON response loaded into a dictionary object. """ if self.session_id is not None: if not params: params = {'sessionId': self.session_id} elif 'sessionId' not in params: params['sessionId'] = self.session_id params = self._wrap_value(params) response = self.command_executor.execute(driver_command, params) if response: self.error_handler.check_response(response) response['value'] = self._unwrap_value( response.get('value', None)) return response # If the server doesn't send a response, assume the command was # a success return {'success': 0, 'value': None, 'sessionId': self.session_id}
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: The command's JSON response loaded into a dictionary object. """ if self.session_id is not None: if not params: params = {'sessionId': self.session_id} elif 'sessionId' not in params: params['sessionId'] = self.session_id params = self._wrap_value(params) response = self.command_executor.execute(driver_command, params) if response: self.error_handler.check_response(response) response['value'] = self._unwrap_value( response.get('value', None)) return response # If the server doesn't send a response, assume the command was # a success return {'success': 0, 'value': None, 'sessionId': self.session_id}
[ "def", "execute", "(", "self", ",", "driver_command", ",", "params", "=", "None", ")", ":", "if", "self", ".", "session_id", "is", "not", "None", ":", "if", "not", "params", ":", "params", "=", "{", "'sessionId'", ":", "self", ".", "session_id", "}", "elif", "'sessionId'", "not", "in", "params", ":", "params", "[", "'sessionId'", "]", "=", "self", ".", "session_id", "params", "=", "self", ".", "_wrap_value", "(", "params", ")", "response", "=", "self", ".", "command_executor", ".", "execute", "(", "driver_command", ",", "params", ")", "if", "response", ":", "self", ".", "error_handler", ".", "check_response", "(", "response", ")", "response", "[", "'value'", "]", "=", "self", ".", "_unwrap_value", "(", "response", ".", "get", "(", "'value'", ",", "None", ")", ")", "return", "response", "# If the server doesn't send a response, assume the command was", "# a success", "return", "{", "'success'", ":", "0", ",", "'value'", ":", "None", ",", "'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 found :Usage: :: element = driver.find_element_by_link_text('Sign In') """ return self.find_element(by=By.LINK_TEXT, value=link_text)
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 found :Usage: :: element = driver.find_element_by_link_text('Sign In') """ return self.find_element(by=By.LINK_TEXT, value=link_text)
[ "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 = driver.find_element_by_link_text('Sign In')
[ "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: :: elements = driver.find_elements_by_link_text('Sign In') """ return self.find_elements(by=By.LINK_TEXT, value=text)
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: :: elements = driver.find_elements_by_link_text('Sign In') """ return self.find_elements(by=By.LINK_TEXT, value=text)
[ "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_text('Sign In')
[ "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: - NoSuchElementException - if the element wasn't found :Usage: :: element = driver.find_element_by_partial_link_text('Sign') """ return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text)
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: - NoSuchElementException - if the element wasn't found :Usage: :: element = driver.find_element_by_partial_link_text('Sign') """ return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text)
[ "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: :: element = driver.find_element_by_partial_link_text('Sign')
[ "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 empty list if not :Usage: :: elements = driver.find_elements_by_partial_link_text('Sign') """ return self.find_elements(by=By.PARTIAL_LINK_TEXT, value=link_text)
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 empty list if not :Usage: :: elements = driver.find_elements_by_partial_link_text('Sign') """ return self.find_elements(by=By.PARTIAL_LINK_TEXT, value=link_text)
[ "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 = driver.find_elements_by_partial_link_text('Sign')
[ "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: :: elements = driver.find_elements_by_name('foo') """ return self.find_elements(by=By.NAME, value=name)
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: :: elements = driver.find_elements_by_name('foo') """ return self.find_elements(by=By.NAME, value=name)
[ "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 :Usage: :: element = driver.find_element_by_tag_name('h1') """ return self.find_element(by=By.TAG_NAME, value=name)
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 :Usage: :: element = driver.find_element_by_tag_name('h1') """ return self.find_element(by=By.TAG_NAME, value=name)
[ "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.find_element_by_tag_name('h1')
[ "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: :: elements = driver.find_elements_by_tag_name('h1') """ return self.find_elements(by=By.TAG_NAME, value=name)
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: :: elements = driver.find_elements_by_tag_name('h1') """ return self.find_elements(by=By.TAG_NAME, value=name)
[ "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 :Usage: :: element = driver.find_element_by_class_name('foo') """ return self.find_element(by=By.CLASS_NAME, value=name)
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 :Usage: :: element = driver.find_element_by_class_name('foo') """ return self.find_element(by=By.CLASS_NAME, value=name)
[ "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 = driver.find_element_by_class_name('foo')
[ "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: :: elements = driver.find_elements_by_class_name('foo') """ return self.find_elements(by=By.CLASS_NAME, value=name)
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: :: elements = driver.find_elements_by_class_name('foo') """ return self.find_elements(by=By.CLASS_NAME, value=name)
[ "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('foo')
[ "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 element wasn't found :Usage: :: element = driver.find_element_by_css_selector('#foo') """ return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
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 element wasn't found :Usage: :: element = driver.find_element_by_css_selector('#foo') """ return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
[ "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: :: element = driver.find_element_by_css_selector('#foo')
[ "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 :Usage: :: elements = driver.find_elements_by_css_selector('.foo') """ return self.find_elements(by=By.CSS_SELECTOR, value=css_selector)
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 :Usage: :: elements = driver.find_elements_by_css_selector('.foo') """ return self.find_elements(by=By.CSS_SELECTOR, value=css_selector)
[ "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_css_selector('.foo')
[ "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 self.execute(Command.GET_CURRENT_WINDOW_HANDLE)['value']
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 self.execute(Command.GET_CURRENT_WINDOW_HANDLE)['value']
[ "def", "current_window_handle", "(", "self", ")", ":", "if", "self", ".", "w3c", ":", "return", "self", ".", "execute", "(", "Command", ".", "W3C_GET_CURRENT_WINDOW_HANDLE", ")", "[", "'value'", "]", "else", ":", "return", "self", ".", "execute", "(", "Command", ".", "GET_CURRENT_WINDOW_HANDLE", ")", "[", "'value'", "]" ]
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 self.execute(Command.GET_WINDOW_HANDLES)['value']
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 self.execute(Command.GET_WINDOW_HANDLES)['value']
[ "def", "window_handles", "(", "self", ")", ":", "if", "self", ".", "w3c", ":", "return", "self", ".", "execute", "(", "Command", ".", "W3C_GET_WINDOW_HANDLES", ")", "[", "'value'", "]", "else", ":", "return", "self", ".", "execute", "(", "Command", ".", "GET_WINDOW_HANDLES", ")", "[", "'value'", "]" ]
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(command, params)
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(command, params)
[ "def", "maximize_window", "(", "self", ")", ":", "params", "=", "None", "command", "=", "Command", ".", "W3C_MAXIMIZE_WINDOW", "if", "not", "self", ".", "w3c", ":", "command", "=", "Command", ".", "MAXIMIZE_WINDOW", "params", "=", "{", "'windowHandle'", ":", "'current'", "}", "self", ".", "execute", "(", "command", ",", "params", ")" ]
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})['value'] except NoSuchCookieException: return None else: cookies = self.get_cookies() for cookie in cookies: if cookie['name'] == name: return cookie return None
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})['value'] except NoSuchCookieException: return None else: cookies = self.get_cookies() for cookie in cookies: if cookie['name'] == name: return cookie return None
[ "def", "get_cookie", "(", "self", ",", "name", ")", ":", "if", "self", ".", "w3c", ":", "try", ":", "return", "self", ".", "execute", "(", "Command", ".", "GET_COOKIE", ",", "{", "'name'", ":", "name", "}", ")", "[", "'value'", "]", "except", "NoSuchCookieException", ":", "return", "None", "else", ":", "cookies", "=", "self", ".", "get_cookies", "(", ")", "for", "cookie", "in", "cookies", ":", "if", "cookie", "[", "'name'", "]", "==", "name", ":", "return", "cookie", "return", "None" ]
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_timeout. :Args: - time_to_wait: Amount of time to wait (in seconds) :Usage: :: driver.implicitly_wait(30) """ if self.w3c: self.execute(Command.SET_TIMEOUTS, { 'implicit': int(float(time_to_wait) * 1000)}) else: self.execute(Command.IMPLICIT_WAIT, { 'ms': float(time_to_wait) * 1000})
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_timeout. :Args: - time_to_wait: Amount of time to wait (in seconds) :Usage: :: driver.implicitly_wait(30) """ if self.w3c: self.execute(Command.SET_TIMEOUTS, { 'implicit': int(float(time_to_wait) * 1000)}) else: self.execute(Command.IMPLICIT_WAIT, { 'ms': float(time_to_wait) * 1000})
[ "def", "implicitly_wait", "(", "self", ",", "time_to_wait", ")", ":", "if", "self", ".", "w3c", ":", "self", ".", "execute", "(", "Command", ".", "SET_TIMEOUTS", ",", "{", "'implicit'", ":", "int", "(", "float", "(", "time_to_wait", ")", "*", "1000", ")", "}", ")", "else", ":", "self", ".", "execute", "(", "Command", ".", "IMPLICIT_WAIT", ",", "{", "'ms'", ":", "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 to wait (in seconds) :Usage: :: driver.implicitly_wait(30)
[ "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", "." ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webdriver.py#L925-L945