repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
fastai/fastai
fastai/torch_core.py
add_metrics
def add_metrics(last_metrics:Collection[Rank0Tensor], mets:Union[Rank0Tensor, Collection[Rank0Tensor]]): "Return a dictionary for updating `last_metrics` with `mets`." last_metrics,mets = listify(last_metrics),listify(mets) return {'last_metrics': last_metrics + mets}
python
def add_metrics(last_metrics:Collection[Rank0Tensor], mets:Union[Rank0Tensor, Collection[Rank0Tensor]]): "Return a dictionary for updating `last_metrics` with `mets`." last_metrics,mets = listify(last_metrics),listify(mets) return {'last_metrics': last_metrics + mets}
[ "def", "add_metrics", "(", "last_metrics", ":", "Collection", "[", "Rank0Tensor", "]", ",", "mets", ":", "Union", "[", "Rank0Tensor", ",", "Collection", "[", "Rank0Tensor", "]", "]", ")", ":", "last_metrics", ",", "mets", "=", "listify", "(", "last_metrics",...
Return a dictionary for updating `last_metrics` with `mets`.
[ "Return", "a", "dictionary", "for", "updating", "last_metrics", "with", "mets", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/torch_core.py#L402-L405
train
fastai/fastai
old/fastai/executors.py
LazyThreadPoolExecutor.map
def map(self, fn, *iterables, timeout=None, chunksize=1, prefetch=None): """ Collects iterables lazily, rather than immediately. Docstring same as parent: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor Implmentation taken from this PR: https://githu...
python
def map(self, fn, *iterables, timeout=None, chunksize=1, prefetch=None): """ Collects iterables lazily, rather than immediately. Docstring same as parent: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor Implmentation taken from this PR: https://githu...
[ "def", "map", "(", "self", ",", "fn", ",", "*", "iterables", ",", "timeout", "=", "None", ",", "chunksize", "=", "1", ",", "prefetch", "=", "None", ")", ":", "if", "timeout", "is", "not", "None", ":", "end_time", "=", "timeout", "+", "time", ".", ...
Collects iterables lazily, rather than immediately. Docstring same as parent: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor Implmentation taken from this PR: https://github.com/python/cpython/pull/707
[ "Collects", "iterables", "lazily", "rather", "than", "immediately", ".", "Docstring", "same", "as", "parent", ":", "https", ":", "//", "docs", ".", "python", ".", "org", "/", "3", "/", "library", "/", "concurrent", ".", "futures", ".", "html#concurrent", "...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/executors.py#L7-L37
train
fastai/fastai
old/docs/gen_ascii_docs.py
gen_ascii_docs
def gen_ascii_docs(src='fastai'): """Generate documentation for fastai library in HTML (asciidoctor required) :param str src: The absolute/relative path of source file/dir """ os.chdir(Path(__file__).absolute().parent) with working_directory('..'): path = Path(src) if path.is_dir(): ...
python
def gen_ascii_docs(src='fastai'): """Generate documentation for fastai library in HTML (asciidoctor required) :param str src: The absolute/relative path of source file/dir """ os.chdir(Path(__file__).absolute().parent) with working_directory('..'): path = Path(src) if path.is_dir(): ...
[ "def", "gen_ascii_docs", "(", "src", "=", "'fastai'", ")", ":", "os", ".", "chdir", "(", "Path", "(", "__file__", ")", ".", "absolute", "(", ")", ".", "parent", ")", "with", "working_directory", "(", "'..'", ")", ":", "path", "=", "Path", "(", "src",...
Generate documentation for fastai library in HTML (asciidoctor required) :param str src: The absolute/relative path of source file/dir
[ "Generate", "documentation", "for", "fastai", "library", "in", "HTML", "(", "asciidoctor", "required", ")", ":", "param", "str", "src", ":", "The", "absolute", "/", "relative", "path", "of", "source", "file", "/", "dir" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/docs/gen_ascii_docs.py#L104-L128
train
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter._get_new_batch
def _get_new_batch(self, ds_type:DatasetType)->Collection[Tensor]: "Retrieves new batch of DatasetType, and detaches it." return self.learn.data.one_batch(ds_type=ds_type, detach=True, denorm=False, cpu=False)
python
def _get_new_batch(self, ds_type:DatasetType)->Collection[Tensor]: "Retrieves new batch of DatasetType, and detaches it." return self.learn.data.one_batch(ds_type=ds_type, detach=True, denorm=False, cpu=False)
[ "def", "_get_new_batch", "(", "self", ",", "ds_type", ":", "DatasetType", ")", "->", "Collection", "[", "Tensor", "]", ":", "return", "self", ".", "learn", ".", "data", ".", "one_batch", "(", "ds_type", "=", "ds_type", ",", "detach", "=", "True", ",", ...
Retrieves new batch of DatasetType, and detaches it.
[ "Retrieves", "new", "batch", "of", "DatasetType", "and", "detaches", "it", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L40-L42
train
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter._update_batches_if_needed
def _update_batches_if_needed(self)->None: "one_batch function is extremely slow with large datasets. This is caching the result as an optimization." if self.learn.data.valid_dl is None: return # Running learning rate finder, so return update_batches = self.data is not self.learn.data i...
python
def _update_batches_if_needed(self)->None: "one_batch function is extremely slow with large datasets. This is caching the result as an optimization." if self.learn.data.valid_dl is None: return # Running learning rate finder, so return update_batches = self.data is not self.learn.data i...
[ "def", "_update_batches_if_needed", "(", "self", ")", "->", "None", ":", "if", "self", ".", "learn", ".", "data", ".", "valid_dl", "is", "None", ":", "return", "# Running learning rate finder, so return", "update_batches", "=", "self", ".", "data", "is", "not", ...
one_batch function is extremely slow with large datasets. This is caching the result as an optimization.
[ "one_batch", "function", "is", "extremely", "slow", "with", "large", "datasets", ".", "This", "is", "caching", "the", "result", "as", "an", "optimization", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L44-L51
train
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter._write_model_stats
def _write_model_stats(self, iteration:int)->None: "Writes gradient statistics to Tensorboard." self.stats_writer.write(model=self.learn.model, iteration=iteration, tbwriter=self.tbwriter)
python
def _write_model_stats(self, iteration:int)->None: "Writes gradient statistics to Tensorboard." self.stats_writer.write(model=self.learn.model, iteration=iteration, tbwriter=self.tbwriter)
[ "def", "_write_model_stats", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "self", ".", "stats_writer", ".", "write", "(", "model", "=", "self", ".", "learn", ".", "model", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", ...
Writes gradient statistics to Tensorboard.
[ "Writes", "gradient", "statistics", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L53-L55
train
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter._write_training_loss
def _write_training_loss(self, iteration:int, last_loss:Tensor)->None: "Writes training loss to Tensorboard." scalar_value = to_np(last_loss) tag = self.metrics_root + 'train_loss' self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration)
python
def _write_training_loss(self, iteration:int, last_loss:Tensor)->None: "Writes training loss to Tensorboard." scalar_value = to_np(last_loss) tag = self.metrics_root + 'train_loss' self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration)
[ "def", "_write_training_loss", "(", "self", ",", "iteration", ":", "int", ",", "last_loss", ":", "Tensor", ")", "->", "None", ":", "scalar_value", "=", "to_np", "(", "last_loss", ")", "tag", "=", "self", ".", "metrics_root", "+", "'train_loss'", "self", "....
Writes training loss to Tensorboard.
[ "Writes", "training", "loss", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L57-L61
train
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter._write_weight_histograms
def _write_weight_histograms(self, iteration:int)->None: "Writes model weight histograms to Tensorboard." self.hist_writer.write(model=self.learn.model, iteration=iteration, tbwriter=self.tbwriter)
python
def _write_weight_histograms(self, iteration:int)->None: "Writes model weight histograms to Tensorboard." self.hist_writer.write(model=self.learn.model, iteration=iteration, tbwriter=self.tbwriter)
[ "def", "_write_weight_histograms", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "self", ".", "hist_writer", ".", "write", "(", "model", "=", "self", ".", "learn", ".", "model", ",", "iteration", "=", "iteration", ",", "tbwriter", "=...
Writes model weight histograms to Tensorboard.
[ "Writes", "model", "weight", "histograms", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L63-L65
train
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter._write_scalar
def _write_scalar(self, name:str, scalar_value, iteration:int)->None: "Writes single scalar value to Tensorboard." tag = self.metrics_root + name self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration)
python
def _write_scalar(self, name:str, scalar_value, iteration:int)->None: "Writes single scalar value to Tensorboard." tag = self.metrics_root + name self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration)
[ "def", "_write_scalar", "(", "self", ",", "name", ":", "str", ",", "scalar_value", ",", "iteration", ":", "int", ")", "->", "None", ":", "tag", "=", "self", ".", "metrics_root", "+", "name", "self", ".", "tbwriter", ".", "add_scalar", "(", "tag", "=", ...
Writes single scalar value to Tensorboard.
[ "Writes", "single", "scalar", "value", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L67-L70
train
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter._write_metrics
def _write_metrics(self, iteration:int, last_metrics:MetricsList, start_idx:int=2)->None: "Writes training metrics to Tensorboard." recorder = self.learn.recorder for i, name in enumerate(recorder.names[start_idx:]): if last_metrics is None or len(last_metrics) < i+1: return ...
python
def _write_metrics(self, iteration:int, last_metrics:MetricsList, start_idx:int=2)->None: "Writes training metrics to Tensorboard." recorder = self.learn.recorder for i, name in enumerate(recorder.names[start_idx:]): if last_metrics is None or len(last_metrics) < i+1: return ...
[ "def", "_write_metrics", "(", "self", ",", "iteration", ":", "int", ",", "last_metrics", ":", "MetricsList", ",", "start_idx", ":", "int", "=", "2", ")", "->", "None", ":", "recorder", "=", "self", ".", "learn", ".", "recorder", "for", "i", ",", "name"...
Writes training metrics to Tensorboard.
[ "Writes", "training", "metrics", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L73-L79
train
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter.on_batch_end
def on_batch_end(self, last_loss:Tensor, iteration:int, **kwargs)->None: "Callback function that writes batch end appropriate data to Tensorboard." if iteration == 0: return self._update_batches_if_needed() if iteration % self.loss_iters == 0: self._write_training_loss(iteration=iteratio...
python
def on_batch_end(self, last_loss:Tensor, iteration:int, **kwargs)->None: "Callback function that writes batch end appropriate data to Tensorboard." if iteration == 0: return self._update_batches_if_needed() if iteration % self.loss_iters == 0: self._write_training_loss(iteration=iteratio...
[ "def", "on_batch_end", "(", "self", ",", "last_loss", ":", "Tensor", ",", "iteration", ":", "int", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "iteration", "==", "0", ":", "return", "self", ".", "_update_batches_if_needed", "(", ")", "if", "...
Callback function that writes batch end appropriate data to Tensorboard.
[ "Callback", "function", "that", "writes", "batch", "end", "appropriate", "data", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L85-L90
train
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter.on_backward_end
def on_backward_end(self, iteration:int, **kwargs)->None: "Callback function that writes backward end appropriate data to Tensorboard." if iteration == 0: return self._update_batches_if_needed() if iteration % self.stats_iters == 0: self._write_model_stats(iteration=iteration)
python
def on_backward_end(self, iteration:int, **kwargs)->None: "Callback function that writes backward end appropriate data to Tensorboard." if iteration == 0: return self._update_batches_if_needed() if iteration % self.stats_iters == 0: self._write_model_stats(iteration=iteration)
[ "def", "on_backward_end", "(", "self", ",", "iteration", ":", "int", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "iteration", "==", "0", ":", "return", "self", ".", "_update_batches_if_needed", "(", ")", "if", "iteration", "%", "self", ".", ...
Callback function that writes backward end appropriate data to Tensorboard.
[ "Callback", "function", "that", "writes", "backward", "end", "appropriate", "data", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L93-L97
train
fastai/fastai
fastai/callbacks/tensorboard.py
LearnerTensorboardWriter.on_epoch_end
def on_epoch_end(self, last_metrics:MetricsList, iteration:int, **kwargs)->None: "Callback function that writes epoch end appropriate data to Tensorboard." self._write_metrics(iteration=iteration, last_metrics=last_metrics)
python
def on_epoch_end(self, last_metrics:MetricsList, iteration:int, **kwargs)->None: "Callback function that writes epoch end appropriate data to Tensorboard." self._write_metrics(iteration=iteration, last_metrics=last_metrics)
[ "def", "on_epoch_end", "(", "self", ",", "last_metrics", ":", "MetricsList", ",", "iteration", ":", "int", ",", "*", "*", "kwargs", ")", "->", "None", ":", "self", ".", "_write_metrics", "(", "iteration", "=", "iteration", ",", "last_metrics", "=", "last_m...
Callback function that writes epoch end appropriate data to Tensorboard.
[ "Callback", "function", "that", "writes", "epoch", "end", "appropriate", "data", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L99-L101
train
fastai/fastai
fastai/callbacks/tensorboard.py
GANTensorboardWriter._write_weight_histograms
def _write_weight_histograms(self, iteration:int)->None: "Writes model weight histograms to Tensorboard." generator, critic = self.learn.gan_trainer.generator, self.learn.gan_trainer.critic self.hist_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='generator') ...
python
def _write_weight_histograms(self, iteration:int)->None: "Writes model weight histograms to Tensorboard." generator, critic = self.learn.gan_trainer.generator, self.learn.gan_trainer.critic self.hist_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='generator') ...
[ "def", "_write_weight_histograms", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "generator", ",", "critic", "=", "self", ".", "learn", ".", "gan_trainer", ".", "generator", ",", "self", ".", "learn", ".", "gan_trainer", ".", "critic",...
Writes model weight histograms to Tensorboard.
[ "Writes", "model", "weight", "histograms", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L114-L118
train
fastai/fastai
fastai/callbacks/tensorboard.py
GANTensorboardWriter._write_gen_model_stats
def _write_gen_model_stats(self, iteration:int)->None: "Writes gradient statistics for generator to Tensorboard." generator = self.learn.gan_trainer.generator self.stats_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='gen_model_stats') self.gen_stats_upda...
python
def _write_gen_model_stats(self, iteration:int)->None: "Writes gradient statistics for generator to Tensorboard." generator = self.learn.gan_trainer.generator self.stats_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='gen_model_stats') self.gen_stats_upda...
[ "def", "_write_gen_model_stats", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "generator", "=", "self", ".", "learn", ".", "gan_trainer", ".", "generator", "self", ".", "stats_writer", ".", "write", "(", "model", "=", "generator", ","...
Writes gradient statistics for generator to Tensorboard.
[ "Writes", "gradient", "statistics", "for", "generator", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L120-L124
train
fastai/fastai
fastai/callbacks/tensorboard.py
GANTensorboardWriter._write_critic_model_stats
def _write_critic_model_stats(self, iteration:int)->None: "Writes gradient statistics for critic to Tensorboard." critic = self.learn.gan_trainer.critic self.stats_writer.write(model=critic, iteration=iteration, tbwriter=self.tbwriter, name='crit_model_stats') self.crit_stats_updated = T...
python
def _write_critic_model_stats(self, iteration:int)->None: "Writes gradient statistics for critic to Tensorboard." critic = self.learn.gan_trainer.critic self.stats_writer.write(model=critic, iteration=iteration, tbwriter=self.tbwriter, name='crit_model_stats') self.crit_stats_updated = T...
[ "def", "_write_critic_model_stats", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "critic", "=", "self", ".", "learn", ".", "gan_trainer", ".", "critic", "self", ".", "stats_writer", ".", "write", "(", "model", "=", "critic", ",", "i...
Writes gradient statistics for critic to Tensorboard.
[ "Writes", "gradient", "statistics", "for", "critic", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L126-L130
train
fastai/fastai
fastai/callbacks/tensorboard.py
GANTensorboardWriter._write_model_stats
def _write_model_stats(self, iteration:int)->None: "Writes gradient statistics to Tensorboard." # We don't want to write stats when model is not iterated on and hence has zeroed out gradients gen_mode = self.learn.gan_trainer.gen_mode if gen_mode and not self.gen_stats_updated: self._wri...
python
def _write_model_stats(self, iteration:int)->None: "Writes gradient statistics to Tensorboard." # We don't want to write stats when model is not iterated on and hence has zeroed out gradients gen_mode = self.learn.gan_trainer.gen_mode if gen_mode and not self.gen_stats_updated: self._wri...
[ "def", "_write_model_stats", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "# We don't want to write stats when model is not iterated on and hence has zeroed out gradients", "gen_mode", "=", "self", ".", "learn", ".", "gan_trainer", ".", "gen_mode", "...
Writes gradient statistics to Tensorboard.
[ "Writes", "gradient", "statistics", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L132-L137
train
fastai/fastai
fastai/callbacks/tensorboard.py
GANTensorboardWriter._write_training_loss
def _write_training_loss(self, iteration:int, last_loss:Tensor)->None: "Writes training loss to Tensorboard." recorder = self.learn.gan_trainer.recorder if len(recorder.losses) == 0: return scalar_value = to_np((recorder.losses[-1:])[0]) tag = self.metrics_root + 'train_loss' ...
python
def _write_training_loss(self, iteration:int, last_loss:Tensor)->None: "Writes training loss to Tensorboard." recorder = self.learn.gan_trainer.recorder if len(recorder.losses) == 0: return scalar_value = to_np((recorder.losses[-1:])[0]) tag = self.metrics_root + 'train_loss' ...
[ "def", "_write_training_loss", "(", "self", ",", "iteration", ":", "int", ",", "last_loss", ":", "Tensor", ")", "->", "None", ":", "recorder", "=", "self", ".", "learn", ".", "gan_trainer", ".", "recorder", "if", "len", "(", "recorder", ".", "losses", ")...
Writes training loss to Tensorboard.
[ "Writes", "training", "loss", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L139-L145
train
fastai/fastai
fastai/callbacks/tensorboard.py
GANTensorboardWriter._write_images
def _write_images(self, iteration:int)->None: "Writes model generated, original and real images to Tensorboard." trainer = self.learn.gan_trainer #TODO: Switching gen_mode temporarily seems a bit hacky here. Certainly not a good side-effect. Is there a better way? gen_mode = trainer.g...
python
def _write_images(self, iteration:int)->None: "Writes model generated, original and real images to Tensorboard." trainer = self.learn.gan_trainer #TODO: Switching gen_mode temporarily seems a bit hacky here. Certainly not a good side-effect. Is there a better way? gen_mode = trainer.g...
[ "def", "_write_images", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "trainer", "=", "self", ".", "learn", ".", "gan_trainer", "#TODO: Switching gen_mode temporarily seems a bit hacky here. Certainly not a good side-effect. Is there a better way?", "g...
Writes model generated, original and real images to Tensorboard.
[ "Writes", "model", "generated", "original", "and", "real", "images", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L147-L156
train
fastai/fastai
fastai/callbacks/tensorboard.py
GANTensorboardWriter.on_batch_end
def on_batch_end(self, iteration:int, **kwargs)->None: "Callback function that writes batch end appropriate data to Tensorboard." super().on_batch_end(iteration=iteration, **kwargs) if iteration == 0: return if iteration % self.visual_iters == 0: self._write_images(iteration=iteration)
python
def on_batch_end(self, iteration:int, **kwargs)->None: "Callback function that writes batch end appropriate data to Tensorboard." super().on_batch_end(iteration=iteration, **kwargs) if iteration == 0: return if iteration % self.visual_iters == 0: self._write_images(iteration=iteration)
[ "def", "on_batch_end", "(", "self", ",", "iteration", ":", "int", ",", "*", "*", "kwargs", ")", "->", "None", ":", "super", "(", ")", ".", "on_batch_end", "(", "iteration", "=", "iteration", ",", "*", "*", "kwargs", ")", "if", "iteration", "==", "0",...
Callback function that writes batch end appropriate data to Tensorboard.
[ "Callback", "function", "that", "writes", "batch", "end", "appropriate", "data", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L158-L162
train
fastai/fastai
fastai/callbacks/tensorboard.py
GANTensorboardWriter.on_backward_end
def on_backward_end(self, iteration:int, **kwargs)->None: "Callback function that writes backward end appropriate data to Tensorboard." if iteration == 0: return self._update_batches_if_needed() #TODO: This could perhaps be implemented as queues of requests instead but that seemed like ...
python
def on_backward_end(self, iteration:int, **kwargs)->None: "Callback function that writes backward end appropriate data to Tensorboard." if iteration == 0: return self._update_batches_if_needed() #TODO: This could perhaps be implemented as queues of requests instead but that seemed like ...
[ "def", "on_backward_end", "(", "self", ",", "iteration", ":", "int", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "iteration", "==", "0", ":", "return", "self", ".", "_update_batches_if_needed", "(", ")", "#TODO: This could perhaps be implemented as q...
Callback function that writes backward end appropriate data to Tensorboard.
[ "Callback", "function", "that", "writes", "backward", "end", "appropriate", "data", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L164-L171
train
fastai/fastai
fastai/callbacks/tensorboard.py
ImageGenTensorboardWriter._write_images
def _write_images(self, iteration:int)->None: "Writes model generated, original and real images to Tensorboard" self.img_gen_vis.write(learn=self.learn, trn_batch=self.trn_batch, val_batch=self.val_batch, iteration=iteration, tbwriter=self.tbwriter)
python
def _write_images(self, iteration:int)->None: "Writes model generated, original and real images to Tensorboard" self.img_gen_vis.write(learn=self.learn, trn_batch=self.trn_batch, val_batch=self.val_batch, iteration=iteration, tbwriter=self.tbwriter)
[ "def", "_write_images", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "self", ".", "img_gen_vis", ".", "write", "(", "learn", "=", "self", ".", "learn", ",", "trn_batch", "=", "self", ".", "trn_batch", ",", "val_batch", "=", "self"...
Writes model generated, original and real images to Tensorboard
[ "Writes", "model", "generated", "original", "and", "real", "images", "to", "Tensorboard" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L182-L185
train
fastai/fastai
fastai/callbacks/tensorboard.py
AsyncTBWriter.request_write
def request_write(self, request: TBWriteRequest)->None: "Queues up an asynchronous write request to Tensorboard." if self.stop_request.isSet(): return self.queue.put(request)
python
def request_write(self, request: TBWriteRequest)->None: "Queues up an asynchronous write request to Tensorboard." if self.stop_request.isSet(): return self.queue.put(request)
[ "def", "request_write", "(", "self", ",", "request", ":", "TBWriteRequest", ")", "->", "None", ":", "if", "self", ".", "stop_request", ".", "isSet", "(", ")", ":", "return", "self", ".", "queue", ".", "put", "(", "request", ")" ]
Queues up an asynchronous write request to Tensorboard.
[ "Queues", "up", "an", "asynchronous", "write", "request", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L216-L219
train
fastai/fastai
fastai/callbacks/tensorboard.py
AsyncTBWriter._queue_processor
def _queue_processor(self)->None: "Processes queued up write requests asynchronously to Tensorboard." while not self.stop_request.isSet(): while not self.queue.empty(): if self.stop_request.isSet(): return request = self.queue.get() request.wri...
python
def _queue_processor(self)->None: "Processes queued up write requests asynchronously to Tensorboard." while not self.stop_request.isSet(): while not self.queue.empty(): if self.stop_request.isSet(): return request = self.queue.get() request.wri...
[ "def", "_queue_processor", "(", "self", ")", "->", "None", ":", "while", "not", "self", ".", "stop_request", ".", "isSet", "(", ")", ":", "while", "not", "self", ".", "queue", ".", "empty", "(", ")", ":", "if", "self", ".", "stop_request", ".", "isSe...
Processes queued up write requests asynchronously to Tensorboard.
[ "Processes", "queued", "up", "write", "requests", "asynchronously", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L221-L228
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelImageSet.get_list_from_model
def get_list_from_model(learn:Learner, ds_type:DatasetType, batch:Tuple)->[]: "Factory method to convert a batch of model images to a list of ModelImageSet." image_sets = [] x,y = batch[0],batch[1] preds = learn.pred_batch(ds_type=ds_type, batch=(x,y), reconstruct=True) for ori...
python
def get_list_from_model(learn:Learner, ds_type:DatasetType, batch:Tuple)->[]: "Factory method to convert a batch of model images to a list of ModelImageSet." image_sets = [] x,y = batch[0],batch[1] preds = learn.pred_batch(ds_type=ds_type, batch=(x,y), reconstruct=True) for ori...
[ "def", "get_list_from_model", "(", "learn", ":", "Learner", ",", "ds_type", ":", "DatasetType", ",", "batch", ":", "Tuple", ")", "->", "[", "]", ":", "image_sets", "=", "[", "]", "x", ",", "y", "=", "batch", "[", "0", "]", ",", "batch", "[", "1", ...
Factory method to convert a batch of model images to a list of ModelImageSet.
[ "Factory", "method", "to", "convert", "a", "batch", "of", "model", "images", "to", "a", "list", "of", "ModelImageSet", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L248-L257
train
fastai/fastai
fastai/callbacks/tensorboard.py
HistogramTBRequest._write_histogram
def _write_histogram(self, param_name:str, values)->None: "Writes single model histogram to Tensorboard." tag = self.name + '/weights/' + param_name self.tbwriter.add_histogram(tag=tag, values=values, global_step=self.iteration)
python
def _write_histogram(self, param_name:str, values)->None: "Writes single model histogram to Tensorboard." tag = self.name + '/weights/' + param_name self.tbwriter.add_histogram(tag=tag, values=values, global_step=self.iteration)
[ "def", "_write_histogram", "(", "self", ",", "param_name", ":", "str", ",", "values", ")", "->", "None", ":", "tag", "=", "self", ".", "name", "+", "'/weights/'", "+", "param_name", "self", ".", "tbwriter", ".", "add_histogram", "(", "tag", "=", "tag", ...
Writes single model histogram to Tensorboard.
[ "Writes", "single", "model", "histogram", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L268-L271
train
fastai/fastai
fastai/callbacks/tensorboard.py
HistogramTBRequest.write
def write(self)->None: "Writes model histograms to Tensorboard." for param_name, values in self.params: self._write_histogram(param_name=param_name, values=values)
python
def write(self)->None: "Writes model histograms to Tensorboard." for param_name, values in self.params: self._write_histogram(param_name=param_name, values=values)
[ "def", "write", "(", "self", ")", "->", "None", ":", "for", "param_name", ",", "values", "in", "self", ".", "params", ":", "self", ".", "_write_histogram", "(", "param_name", "=", "param_name", ",", "values", "=", "values", ")" ]
Writes model histograms to Tensorboard.
[ "Writes", "model", "histograms", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L273-L275
train
fastai/fastai
fastai/callbacks/tensorboard.py
HistogramTBWriter.write
def write(self, model:nn.Module, iteration:int, tbwriter:SummaryWriter, name:str='model')->None: "Writes model histograms to Tensorboard." request = HistogramTBRequest(model=model, iteration=iteration, tbwriter=tbwriter, name=name) asyncTBWriter.request_write(request)
python
def write(self, model:nn.Module, iteration:int, tbwriter:SummaryWriter, name:str='model')->None: "Writes model histograms to Tensorboard." request = HistogramTBRequest(model=model, iteration=iteration, tbwriter=tbwriter, name=name) asyncTBWriter.request_write(request)
[ "def", "write", "(", "self", ",", "model", ":", "nn", ".", "Module", ",", "iteration", ":", "int", ",", "tbwriter", ":", "SummaryWriter", ",", "name", ":", "str", "=", "'model'", ")", "->", "None", ":", "request", "=", "HistogramTBRequest", "(", "model...
Writes model histograms to Tensorboard.
[ "Writes", "model", "histograms", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L282-L285
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._add_gradient_scalar
def _add_gradient_scalar(self, name:str, scalar_value)->None: "Writes a single scalar value for a gradient statistic to Tensorboard." tag = self.name + '/gradients/' + name self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=self.iteration)
python
def _add_gradient_scalar(self, name:str, scalar_value)->None: "Writes a single scalar value for a gradient statistic to Tensorboard." tag = self.name + '/gradients/' + name self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=self.iteration)
[ "def", "_add_gradient_scalar", "(", "self", ",", "name", ":", "str", ",", "scalar_value", ")", "->", "None", ":", "tag", "=", "self", ".", "name", "+", "'/gradients/'", "+", "name", "self", ".", "tbwriter", ".", "add_scalar", "(", "tag", "=", "tag", ",...
Writes a single scalar value for a gradient statistic to Tensorboard.
[ "Writes", "a", "single", "scalar", "value", "for", "a", "gradient", "statistic", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L294-L297
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_avg_norm
def _write_avg_norm(self, norms:[])->None: "Writes the average norm of the gradients to Tensorboard." avg_norm = sum(norms)/len(self.gradients) self._add_gradient_scalar('avg_norm', scalar_value=avg_norm)
python
def _write_avg_norm(self, norms:[])->None: "Writes the average norm of the gradients to Tensorboard." avg_norm = sum(norms)/len(self.gradients) self._add_gradient_scalar('avg_norm', scalar_value=avg_norm)
[ "def", "_write_avg_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "avg_norm", "=", "sum", "(", "norms", ")", "/", "len", "(", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'avg_norm'", ",", "scalar_...
Writes the average norm of the gradients to Tensorboard.
[ "Writes", "the", "average", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L299-L302
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_median_norm
def _write_median_norm(self, norms:[])->None: "Writes the median norm of the gradients to Tensorboard." median_norm = statistics.median(norms) self._add_gradient_scalar('median_norm', scalar_value=median_norm)
python
def _write_median_norm(self, norms:[])->None: "Writes the median norm of the gradients to Tensorboard." median_norm = statistics.median(norms) self._add_gradient_scalar('median_norm', scalar_value=median_norm)
[ "def", "_write_median_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "median_norm", "=", "statistics", ".", "median", "(", "norms", ")", "self", ".", "_add_gradient_scalar", "(", "'median_norm'", ",", "scalar_value", "=", "median_no...
Writes the median norm of the gradients to Tensorboard.
[ "Writes", "the", "median", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L304-L307
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_max_norm
def _write_max_norm(self, norms:[])->None: "Writes the maximum norm of the gradients to Tensorboard." max_norm = max(norms) self._add_gradient_scalar('max_norm', scalar_value=max_norm)
python
def _write_max_norm(self, norms:[])->None: "Writes the maximum norm of the gradients to Tensorboard." max_norm = max(norms) self._add_gradient_scalar('max_norm', scalar_value=max_norm)
[ "def", "_write_max_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "max_norm", "=", "max", "(", "norms", ")", "self", ".", "_add_gradient_scalar", "(", "'max_norm'", ",", "scalar_value", "=", "max_norm", ")" ]
Writes the maximum norm of the gradients to Tensorboard.
[ "Writes", "the", "maximum", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L309-L312
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_min_norm
def _write_min_norm(self, norms:[])->None: "Writes the minimum norm of the gradients to Tensorboard." min_norm = min(norms) self._add_gradient_scalar('min_norm', scalar_value=min_norm)
python
def _write_min_norm(self, norms:[])->None: "Writes the minimum norm of the gradients to Tensorboard." min_norm = min(norms) self._add_gradient_scalar('min_norm', scalar_value=min_norm)
[ "def", "_write_min_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "min_norm", "=", "min", "(", "norms", ")", "self", ".", "_add_gradient_scalar", "(", "'min_norm'", ",", "scalar_value", "=", "min_norm", ")" ]
Writes the minimum norm of the gradients to Tensorboard.
[ "Writes", "the", "minimum", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L314-L317
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_num_zeros
def _write_num_zeros(self)->None: "Writes the number of zeroes in the gradients to Tensorboard." gradient_nps = [to_np(x.data) for x in self.gradients] num_zeros = sum((np.asarray(x) == 0.0).sum() for x in gradient_nps) self._add_gradient_scalar('num_zeros', scalar_value=num_zeros)
python
def _write_num_zeros(self)->None: "Writes the number of zeroes in the gradients to Tensorboard." gradient_nps = [to_np(x.data) for x in self.gradients] num_zeros = sum((np.asarray(x) == 0.0).sum() for x in gradient_nps) self._add_gradient_scalar('num_zeros', scalar_value=num_zeros)
[ "def", "_write_num_zeros", "(", "self", ")", "->", "None", ":", "gradient_nps", "=", "[", "to_np", "(", "x", ".", "data", ")", "for", "x", "in", "self", ".", "gradients", "]", "num_zeros", "=", "sum", "(", "(", "np", ".", "asarray", "(", "x", ")", ...
Writes the number of zeroes in the gradients to Tensorboard.
[ "Writes", "the", "number", "of", "zeroes", "in", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L319-L323
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_avg_gradient
def _write_avg_gradient(self)->None: "Writes the average of the gradients to Tensorboard." avg_gradient = sum(x.data.mean() for x in self.gradients)/len(self.gradients) self._add_gradient_scalar('avg_gradient', scalar_value=avg_gradient)
python
def _write_avg_gradient(self)->None: "Writes the average of the gradients to Tensorboard." avg_gradient = sum(x.data.mean() for x in self.gradients)/len(self.gradients) self._add_gradient_scalar('avg_gradient', scalar_value=avg_gradient)
[ "def", "_write_avg_gradient", "(", "self", ")", "->", "None", ":", "avg_gradient", "=", "sum", "(", "x", ".", "data", ".", "mean", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "/", "len", "(", "self", ".", "gradients", ")", "self", "....
Writes the average of the gradients to Tensorboard.
[ "Writes", "the", "average", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L325-L328
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_median_gradient
def _write_median_gradient(self)->None: "Writes the median of the gradients to Tensorboard." median_gradient = statistics.median(x.data.median() for x in self.gradients) self._add_gradient_scalar('median_gradient', scalar_value=median_gradient)
python
def _write_median_gradient(self)->None: "Writes the median of the gradients to Tensorboard." median_gradient = statistics.median(x.data.median() for x in self.gradients) self._add_gradient_scalar('median_gradient', scalar_value=median_gradient)
[ "def", "_write_median_gradient", "(", "self", ")", "->", "None", ":", "median_gradient", "=", "statistics", ".", "median", "(", "x", ".", "data", ".", "median", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar",...
Writes the median of the gradients to Tensorboard.
[ "Writes", "the", "median", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L330-L333
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_max_gradient
def _write_max_gradient(self)->None: "Writes the maximum of the gradients to Tensorboard." max_gradient = max(x.data.max() for x in self.gradients) self._add_gradient_scalar('max_gradient', scalar_value=max_gradient)
python
def _write_max_gradient(self)->None: "Writes the maximum of the gradients to Tensorboard." max_gradient = max(x.data.max() for x in self.gradients) self._add_gradient_scalar('max_gradient', scalar_value=max_gradient)
[ "def", "_write_max_gradient", "(", "self", ")", "->", "None", ":", "max_gradient", "=", "max", "(", "x", ".", "data", ".", "max", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'max_gradient'", ",", ...
Writes the maximum of the gradients to Tensorboard.
[ "Writes", "the", "maximum", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L335-L338
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest._write_min_gradient
def _write_min_gradient(self)->None: "Writes the minimum of the gradients to Tensorboard." min_gradient = min(x.data.min() for x in self.gradients) self._add_gradient_scalar('min_gradient', scalar_value=min_gradient)
python
def _write_min_gradient(self)->None: "Writes the minimum of the gradients to Tensorboard." min_gradient = min(x.data.min() for x in self.gradients) self._add_gradient_scalar('min_gradient', scalar_value=min_gradient)
[ "def", "_write_min_gradient", "(", "self", ")", "->", "None", ":", "min_gradient", "=", "min", "(", "x", ".", "data", ".", "min", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'min_gradient'", ",", ...
Writes the minimum of the gradients to Tensorboard.
[ "Writes", "the", "minimum", "of", "the", "gradients", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L340-L343
train
fastai/fastai
fastai/callbacks/tensorboard.py
ModelStatsTBRequest.write
def write(self)->None: "Writes model gradient statistics to Tensorboard." if len(self.gradients) == 0: return norms = [x.data.norm() for x in self.gradients] self._write_avg_norm(norms=norms) self._write_median_norm(norms=norms) self._write_max_norm(norms=norms) s...
python
def write(self)->None: "Writes model gradient statistics to Tensorboard." if len(self.gradients) == 0: return norms = [x.data.norm() for x in self.gradients] self._write_avg_norm(norms=norms) self._write_median_norm(norms=norms) self._write_max_norm(norms=norms) s...
[ "def", "write", "(", "self", ")", "->", "None", ":", "if", "len", "(", "self", ".", "gradients", ")", "==", "0", ":", "return", "norms", "=", "[", "x", ".", "data", ".", "norm", "(", ")", "for", "x", "in", "self", ".", "gradients", "]", "self",...
Writes model gradient statistics to Tensorboard.
[ "Writes", "model", "gradient", "statistics", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L345-L357
train
fastai/fastai
fastai/callbacks/tensorboard.py
ImageTBRequest._write_images
def _write_images(self, name:str, images:[Tensor])->None: "Writes list of images as tensors to Tensorboard." tag = self.ds_type.name + ' ' + name self.tbwriter.add_image(tag=tag, img_tensor=vutils.make_grid(images, normalize=True), global_step=self.iteration)
python
def _write_images(self, name:str, images:[Tensor])->None: "Writes list of images as tensors to Tensorboard." tag = self.ds_type.name + ' ' + name self.tbwriter.add_image(tag=tag, img_tensor=vutils.make_grid(images, normalize=True), global_step=self.iteration)
[ "def", "_write_images", "(", "self", ",", "name", ":", "str", ",", "images", ":", "[", "Tensor", "]", ")", "->", "None", ":", "tag", "=", "self", ".", "ds_type", ".", "name", "+", "' '", "+", "name", "self", ".", "tbwriter", ".", "add_image", "(", ...
Writes list of images as tensors to Tensorboard.
[ "Writes", "list", "of", "images", "as", "tensors", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L373-L376
train
fastai/fastai
fastai/callbacks/tensorboard.py
ImageTBRequest._get_image_tensors
def _get_image_tensors(self)->([Tensor], [Tensor], [Tensor]): "Gets list of image tensors from lists of Image objects, as a tuple of original, generated and real(target) images." orig_images, gen_images, real_images = [], [], [] for image_set in self.image_sets: orig_images.append(im...
python
def _get_image_tensors(self)->([Tensor], [Tensor], [Tensor]): "Gets list of image tensors from lists of Image objects, as a tuple of original, generated and real(target) images." orig_images, gen_images, real_images = [], [], [] for image_set in self.image_sets: orig_images.append(im...
[ "def", "_get_image_tensors", "(", "self", ")", "->", "(", "[", "Tensor", "]", ",", "[", "Tensor", "]", ",", "[", "Tensor", "]", ")", ":", "orig_images", ",", "gen_images", ",", "real_images", "=", "[", "]", ",", "[", "]", ",", "[", "]", "for", "i...
Gets list of image tensors from lists of Image objects, as a tuple of original, generated and real(target) images.
[ "Gets", "list", "of", "image", "tensors", "from", "lists", "of", "Image", "objects", "as", "a", "tuple", "of", "original", "generated", "and", "real", "(", "target", ")", "images", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L378-L385
train
fastai/fastai
fastai/callbacks/tensorboard.py
ImageTBRequest.write
def write(self)->None: "Writes original, generated and real(target) images to Tensorboard." orig_images, gen_images, real_images = self._get_image_tensors() self._write_images(name='orig images', images=orig_images) self._write_images(name='gen images', images=gen_images) self._...
python
def write(self)->None: "Writes original, generated and real(target) images to Tensorboard." orig_images, gen_images, real_images = self._get_image_tensors() self._write_images(name='orig images', images=orig_images) self._write_images(name='gen images', images=gen_images) self._...
[ "def", "write", "(", "self", ")", "->", "None", ":", "orig_images", ",", "gen_images", ",", "real_images", "=", "self", ".", "_get_image_tensors", "(", ")", "self", ".", "_write_images", "(", "name", "=", "'orig images'", ",", "images", "=", "orig_images", ...
Writes original, generated and real(target) images to Tensorboard.
[ "Writes", "original", "generated", "and", "real", "(", "target", ")", "images", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L387-L392
train
fastai/fastai
fastai/callbacks/tensorboard.py
ImageTBWriter.write
def write(self, learn:Learner, trn_batch:Tuple, val_batch:Tuple, iteration:int, tbwriter:SummaryWriter)->None: "Writes training and validation batch images to Tensorboard." self._write_for_dstype(learn=learn, batch=val_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Valid) sel...
python
def write(self, learn:Learner, trn_batch:Tuple, val_batch:Tuple, iteration:int, tbwriter:SummaryWriter)->None: "Writes training and validation batch images to Tensorboard." self._write_for_dstype(learn=learn, batch=val_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Valid) sel...
[ "def", "write", "(", "self", ",", "learn", ":", "Learner", ",", "trn_batch", ":", "Tuple", ",", "val_batch", ":", "Tuple", ",", "iteration", ":", "int", ",", "tbwriter", ":", "SummaryWriter", ")", "->", "None", ":", "self", ".", "_write_for_dstype", "(",...
Writes training and validation batch images to Tensorboard.
[ "Writes", "training", "and", "validation", "batch", "images", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L399-L402
train
fastai/fastai
fastai/callbacks/tensorboard.py
ImageTBWriter._write_for_dstype
def _write_for_dstype(self, learn:Learner, batch:Tuple, iteration:int, tbwriter:SummaryWriter, ds_type:DatasetType)->None: "Writes batch images of specified DatasetType to Tensorboard." request = ImageTBRequest(learn=learn, batch=batch, iteration=iteration, tbwriter=tbwriter, ds_type=ds_type) as...
python
def _write_for_dstype(self, learn:Learner, batch:Tuple, iteration:int, tbwriter:SummaryWriter, ds_type:DatasetType)->None: "Writes batch images of specified DatasetType to Tensorboard." request = ImageTBRequest(learn=learn, batch=batch, iteration=iteration, tbwriter=tbwriter, ds_type=ds_type) as...
[ "def", "_write_for_dstype", "(", "self", ",", "learn", ":", "Learner", ",", "batch", ":", "Tuple", ",", "iteration", ":", "int", ",", "tbwriter", ":", "SummaryWriter", ",", "ds_type", ":", "DatasetType", ")", "->", "None", ":", "request", "=", "ImageTBRequ...
Writes batch images of specified DatasetType to Tensorboard.
[ "Writes", "batch", "images", "of", "specified", "DatasetType", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L404-L407
train
fastai/fastai
fastai/callbacks/tensorboard.py
GraphTBRequest.write
def write(self)->None: "Writes single model graph to Tensorboard." self.tbwriter.add_graph(model=self.model, input_to_model=self.input_to_model)
python
def write(self)->None: "Writes single model graph to Tensorboard." self.tbwriter.add_graph(model=self.model, input_to_model=self.input_to_model)
[ "def", "write", "(", "self", ")", "->", "None", ":", "self", ".", "tbwriter", ".", "add_graph", "(", "model", "=", "self", ".", "model", ",", "input_to_model", "=", "self", ".", "input_to_model", ")" ]
Writes single model graph to Tensorboard.
[ "Writes", "single", "model", "graph", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L415-L417
train
fastai/fastai
fastai/callbacks/tensorboard.py
GraphTBWriter.write
def write(self, model:nn.Module, tbwriter:SummaryWriter, input_to_model:torch.Tensor)->None: "Writes model graph to Tensorboard." request = GraphTBRequest(model=model, tbwriter=tbwriter, input_to_model=input_to_model) asyncTBWriter.request_write(request)
python
def write(self, model:nn.Module, tbwriter:SummaryWriter, input_to_model:torch.Tensor)->None: "Writes model graph to Tensorboard." request = GraphTBRequest(model=model, tbwriter=tbwriter, input_to_model=input_to_model) asyncTBWriter.request_write(request)
[ "def", "write", "(", "self", ",", "model", ":", "nn", ".", "Module", ",", "tbwriter", ":", "SummaryWriter", ",", "input_to_model", ":", "torch", ".", "Tensor", ")", "->", "None", ":", "request", "=", "GraphTBRequest", "(", "model", "=", "model", ",", "...
Writes model graph to Tensorboard.
[ "Writes", "model", "graph", "to", "Tensorboard", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L421-L424
train
fastai/fastai
old/fastai/swa.py
fix_batchnorm
def fix_batchnorm(swa_model, train_dl): """ During training, batch norm layers keep track of a running mean and variance of the previous layer's activations. Because the parameters of the SWA model are computed as the average of other models' parameters, the SWA model never sees the training data it...
python
def fix_batchnorm(swa_model, train_dl): """ During training, batch norm layers keep track of a running mean and variance of the previous layer's activations. Because the parameters of the SWA model are computed as the average of other models' parameters, the SWA model never sees the training data it...
[ "def", "fix_batchnorm", "(", "swa_model", ",", "train_dl", ")", ":", "bn_modules", "=", "[", "]", "swa_model", ".", "apply", "(", "lambda", "module", ":", "collect_bn_modules", "(", "module", ",", "bn_modules", ")", ")", "if", "not", "bn_modules", ":", "re...
During training, batch norm layers keep track of a running mean and variance of the previous layer's activations. Because the parameters of the SWA model are computed as the average of other models' parameters, the SWA model never sees the training data itself, and therefore has no opportunity to comput...
[ "During", "training", "batch", "norm", "layers", "keep", "track", "of", "a", "running", "mean", "and", "variance", "of", "the", "previous", "layer", "s", "activations", ".", "Because", "the", "parameters", "of", "the", "SWA", "model", "are", "computed", "as"...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/swa.py#L45-L83
train
fastai/fastai
old/fastai/lm_rnn.py
repackage_var
def repackage_var(h): """Wraps h in new Variables, to detach them from their history.""" if IS_TORCH_04: return h.detach() if type(h) == torch.Tensor else tuple(repackage_var(v) for v in h) else: return Variable(h.data) if type(h) == Variable else tuple(repackage_var(v) for v in h)
python
def repackage_var(h): """Wraps h in new Variables, to detach them from their history.""" if IS_TORCH_04: return h.detach() if type(h) == torch.Tensor else tuple(repackage_var(v) for v in h) else: return Variable(h.data) if type(h) == Variable else tuple(repackage_var(v) for v in h)
[ "def", "repackage_var", "(", "h", ")", ":", "if", "IS_TORCH_04", ":", "return", "h", ".", "detach", "(", ")", "if", "type", "(", "h", ")", "==", "torch", ".", "Tensor", "else", "tuple", "(", "repackage_var", "(", "v", ")", "for", "v", "in", "h", ...
Wraps h in new Variables, to detach them from their history.
[ "Wraps", "h", "in", "new", "Variables", "to", "detach", "them", "from", "their", "history", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/lm_rnn.py#L20-L23
train
fastai/fastai
old/fastai/lm_rnn.py
get_language_model
def get_language_model(n_tok, emb_sz, n_hid, n_layers, pad_token, dropout=0.4, dropouth=0.3, dropouti=0.5, dropoute=0.1, wdrop=0.5, tie_weights=True, qrnn=False, bias=False): """Returns a SequentialRNN model. A RNN_Encoder layer is instantiated using the parameters provided. This is follo...
python
def get_language_model(n_tok, emb_sz, n_hid, n_layers, pad_token, dropout=0.4, dropouth=0.3, dropouti=0.5, dropoute=0.1, wdrop=0.5, tie_weights=True, qrnn=False, bias=False): """Returns a SequentialRNN model. A RNN_Encoder layer is instantiated using the parameters provided. This is follo...
[ "def", "get_language_model", "(", "n_tok", ",", "emb_sz", ",", "n_hid", ",", "n_layers", ",", "pad_token", ",", "dropout", "=", "0.4", ",", "dropouth", "=", "0.3", ",", "dropouti", "=", "0.5", ",", "dropoute", "=", "0.1", ",", "wdrop", "=", "0.5", ",",...
Returns a SequentialRNN model. A RNN_Encoder layer is instantiated using the parameters provided. This is followed by the creation of a LinearDecoder layer. Also by default (i.e. tie_weights = True), the embedding matrix used in the RNN_Encoder is used to instantiate the weights for the LinearDecode...
[ "Returns", "a", "SequentialRNN", "model", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/lm_rnn.py#L204-L238
train
fastai/fastai
old/fastai/lm_rnn.py
RNN_Encoder.forward
def forward(self, input): """ Invoked during the forward propagation of the RNN_Encoder module. Args: input (Tensor): input of shape (sentence length x batch_size) Returns: raw_outputs (tuple(list (Tensor), list(Tensor)): list of tensors evaluated from each RNN layer wit...
python
def forward(self, input): """ Invoked during the forward propagation of the RNN_Encoder module. Args: input (Tensor): input of shape (sentence length x batch_size) Returns: raw_outputs (tuple(list (Tensor), list(Tensor)): list of tensors evaluated from each RNN layer wit...
[ "def", "forward", "(", "self", ",", "input", ")", ":", "sl", ",", "bs", "=", "input", ".", "size", "(", ")", "if", "bs", "!=", "self", ".", "bs", ":", "self", ".", "bs", "=", "bs", "self", ".", "reset", "(", ")", "with", "set_grad_enabled", "("...
Invoked during the forward propagation of the RNN_Encoder module. Args: input (Tensor): input of shape (sentence length x batch_size) Returns: raw_outputs (tuple(list (Tensor), list(Tensor)): list of tensors evaluated from each RNN layer without using dropouth, list ...
[ "Invoked", "during", "the", "forward", "propagation", "of", "the", "RNN_Encoder", "module", ".", "Args", ":", "input", "(", "Tensor", ")", ":", "input", "of", "shape", "(", "sentence", "length", "x", "batch_size", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/lm_rnn.py#L84-L113
train
fastai/fastai
fastai/text/transform.py
replace_rep
def replace_rep(t:str) -> str: "Replace repetitions at the character level in `t`." def _replace_rep(m:Collection[str]) -> str: c,cc = m.groups() return f' {TK_REP} {len(cc)+1} {c} ' re_rep = re.compile(r'(\S)(\1{3,})') return re_rep.sub(_replace_rep, t)
python
def replace_rep(t:str) -> str: "Replace repetitions at the character level in `t`." def _replace_rep(m:Collection[str]) -> str: c,cc = m.groups() return f' {TK_REP} {len(cc)+1} {c} ' re_rep = re.compile(r'(\S)(\1{3,})') return re_rep.sub(_replace_rep, t)
[ "def", "replace_rep", "(", "t", ":", "str", ")", "->", "str", ":", "def", "_replace_rep", "(", "m", ":", "Collection", "[", "str", "]", ")", "->", "str", ":", "c", ",", "cc", "=", "m", ".", "groups", "(", ")", "return", "f' {TK_REP} {len(cc)+1} {c} '...
Replace repetitions at the character level in `t`.
[ "Replace", "repetitions", "at", "the", "character", "level", "in", "t", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L42-L48
train
fastai/fastai
fastai/text/transform.py
replace_wrep
def replace_wrep(t:str) -> str: "Replace word repetitions in `t`." def _replace_wrep(m:Collection[str]) -> str: c,cc = m.groups() return f' {TK_WREP} {len(cc.split())+1} {c} ' re_wrep = re.compile(r'(\b\w+\W+)(\1{3,})') return re_wrep.sub(_replace_wrep, t)
python
def replace_wrep(t:str) -> str: "Replace word repetitions in `t`." def _replace_wrep(m:Collection[str]) -> str: c,cc = m.groups() return f' {TK_WREP} {len(cc.split())+1} {c} ' re_wrep = re.compile(r'(\b\w+\W+)(\1{3,})') return re_wrep.sub(_replace_wrep, t)
[ "def", "replace_wrep", "(", "t", ":", "str", ")", "->", "str", ":", "def", "_replace_wrep", "(", "m", ":", "Collection", "[", "str", "]", ")", "->", "str", ":", "c", ",", "cc", "=", "m", ".", "groups", "(", ")", "return", "f' {TK_WREP} {len(cc.split(...
Replace word repetitions in `t`.
[ "Replace", "word", "repetitions", "in", "t", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L50-L56
train
fastai/fastai
fastai/text/transform.py
fix_html
def fix_html(x:str) -> str: "List of replacements from html strings in `x`." re1 = re.compile(r' +') x = x.replace('#39;', "'").replace('amp;', '&').replace('#146;', "'").replace( 'nbsp;', ' ').replace('#36;', '$').replace('\\n', "\n").replace('quot;', "'").replace( '<br />', "\n").replace(...
python
def fix_html(x:str) -> str: "List of replacements from html strings in `x`." re1 = re.compile(r' +') x = x.replace('#39;', "'").replace('amp;', '&').replace('#146;', "'").replace( 'nbsp;', ' ').replace('#36;', '$').replace('\\n', "\n").replace('quot;', "'").replace( '<br />', "\n").replace(...
[ "def", "fix_html", "(", "x", ":", "str", ")", "->", "str", ":", "re1", "=", "re", ".", "compile", "(", "r' +'", ")", "x", "=", "x", ".", "replace", "(", "'#39;'", ",", "\"'\"", ")", ".", "replace", "(", "'amp;'", ",", "'&'", ")", ".", "replace...
List of replacements from html strings in `x`.
[ "List", "of", "replacements", "from", "html", "strings", "in", "x", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L58-L65
train
fastai/fastai
fastai/text/transform.py
replace_all_caps
def replace_all_caps(x:Collection[str]) -> Collection[str]: "Replace tokens in ALL CAPS in `x` by their lower version and add `TK_UP` before." res = [] for t in x: if t.isupper() and len(t) > 1: res.append(TK_UP); res.append(t.lower()) else: res.append(t) return res
python
def replace_all_caps(x:Collection[str]) -> Collection[str]: "Replace tokens in ALL CAPS in `x` by their lower version and add `TK_UP` before." res = [] for t in x: if t.isupper() and len(t) > 1: res.append(TK_UP); res.append(t.lower()) else: res.append(t) return res
[ "def", "replace_all_caps", "(", "x", ":", "Collection", "[", "str", "]", ")", "->", "Collection", "[", "str", "]", ":", "res", "=", "[", "]", "for", "t", "in", "x", ":", "if", "t", ".", "isupper", "(", ")", "and", "len", "(", "t", ")", ">", "...
Replace tokens in ALL CAPS in `x` by their lower version and add `TK_UP` before.
[ "Replace", "tokens", "in", "ALL", "CAPS", "in", "x", "by", "their", "lower", "version", "and", "add", "TK_UP", "before", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L67-L73
train
fastai/fastai
fastai/text/transform.py
deal_caps
def deal_caps(x:Collection[str]) -> Collection[str]: "Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before." res = [] for t in x: if t == '': continue if t[0].isupper() and len(t) > 1 and t[1:].islower(): res.append(TK_MAJ) res.append(t.lower()) re...
python
def deal_caps(x:Collection[str]) -> Collection[str]: "Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before." res = [] for t in x: if t == '': continue if t[0].isupper() and len(t) > 1 and t[1:].islower(): res.append(TK_MAJ) res.append(t.lower()) re...
[ "def", "deal_caps", "(", "x", ":", "Collection", "[", "str", "]", ")", "->", "Collection", "[", "str", "]", ":", "res", "=", "[", "]", "for", "t", "in", "x", ":", "if", "t", "==", "''", ":", "continue", "if", "t", "[", "0", "]", ".", "isupper...
Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before.
[ "Replace", "all", "Capitalized", "tokens", "in", "x", "by", "their", "lower", "version", "and", "add", "TK_MAJ", "before", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L75-L82
train
fastai/fastai
fastai/text/transform.py
Tokenizer.process_text
def process_text(self, t:str, tok:BaseTokenizer) -> List[str]: "Process one text `t` with tokenizer `tok`." for rule in self.pre_rules: t = rule(t) toks = tok.tokenizer(t) for rule in self.post_rules: toks = rule(toks) return toks
python
def process_text(self, t:str, tok:BaseTokenizer) -> List[str]: "Process one text `t` with tokenizer `tok`." for rule in self.pre_rules: t = rule(t) toks = tok.tokenizer(t) for rule in self.post_rules: toks = rule(toks) return toks
[ "def", "process_text", "(", "self", ",", "t", ":", "str", ",", "tok", ":", "BaseTokenizer", ")", "->", "List", "[", "str", "]", ":", "for", "rule", "in", "self", ".", "pre_rules", ":", "t", "=", "rule", "(", "t", ")", "toks", "=", "tok", ".", "...
Process one text `t` with tokenizer `tok`.
[ "Process", "one", "text", "t", "with", "tokenizer", "tok", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L103-L108
train
fastai/fastai
fastai/text/transform.py
Tokenizer._process_all_1
def _process_all_1(self, texts:Collection[str]) -> List[List[str]]: "Process a list of `texts` in one process." tok = self.tok_func(self.lang) if self.special_cases: tok.add_special_cases(self.special_cases) return [self.process_text(str(t), tok) for t in texts]
python
def _process_all_1(self, texts:Collection[str]) -> List[List[str]]: "Process a list of `texts` in one process." tok = self.tok_func(self.lang) if self.special_cases: tok.add_special_cases(self.special_cases) return [self.process_text(str(t), tok) for t in texts]
[ "def", "_process_all_1", "(", "self", ",", "texts", ":", "Collection", "[", "str", "]", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "tok", "=", "self", ".", "tok_func", "(", "self", ".", "lang", ")", "if", "self", ".", "special_cases...
Process a list of `texts` in one process.
[ "Process", "a", "list", "of", "texts", "in", "one", "process", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L110-L114
train
fastai/fastai
fastai/text/transform.py
Tokenizer.process_all
def process_all(self, texts:Collection[str]) -> List[List[str]]: "Process a list of `texts`." if self.n_cpus <= 1: return self._process_all_1(texts) with ProcessPoolExecutor(self.n_cpus) as e: return sum(e.map(self._process_all_1, partition_by_cores(texts, self.n_cpus)), [])
python
def process_all(self, texts:Collection[str]) -> List[List[str]]: "Process a list of `texts`." if self.n_cpus <= 1: return self._process_all_1(texts) with ProcessPoolExecutor(self.n_cpus) as e: return sum(e.map(self._process_all_1, partition_by_cores(texts, self.n_cpus)), [])
[ "def", "process_all", "(", "self", ",", "texts", ":", "Collection", "[", "str", "]", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "if", "self", ".", "n_cpus", "<=", "1", ":", "return", "self", ".", "_process_all_1", "(", "texts", ")",...
Process a list of `texts`.
[ "Process", "a", "list", "of", "texts", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L116-L120
train
fastai/fastai
fastai/text/transform.py
Vocab.numericalize
def numericalize(self, t:Collection[str]) -> List[int]: "Convert a list of tokens `t` to their ids." return [self.stoi[w] for w in t]
python
def numericalize(self, t:Collection[str]) -> List[int]: "Convert a list of tokens `t` to their ids." return [self.stoi[w] for w in t]
[ "def", "numericalize", "(", "self", ",", "t", ":", "Collection", "[", "str", "]", ")", "->", "List", "[", "int", "]", ":", "return", "[", "self", ".", "stoi", "[", "w", "]", "for", "w", "in", "t", "]" ]
Convert a list of tokens `t` to their ids.
[ "Convert", "a", "list", "of", "tokens", "t", "to", "their", "ids", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L128-L130
train
fastai/fastai
fastai/text/transform.py
Vocab.textify
def textify(self, nums:Collection[int], sep=' ') -> List[str]: "Convert a list of `nums` to their tokens." return sep.join([self.itos[i] for i in nums]) if sep is not None else [self.itos[i] for i in nums]
python
def textify(self, nums:Collection[int], sep=' ') -> List[str]: "Convert a list of `nums` to their tokens." return sep.join([self.itos[i] for i in nums]) if sep is not None else [self.itos[i] for i in nums]
[ "def", "textify", "(", "self", ",", "nums", ":", "Collection", "[", "int", "]", ",", "sep", "=", "' '", ")", "->", "List", "[", "str", "]", ":", "return", "sep", ".", "join", "(", "[", "self", ".", "itos", "[", "i", "]", "for", "i", "in", "nu...
Convert a list of `nums` to their tokens.
[ "Convert", "a", "list", "of", "nums", "to", "their", "tokens", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L132-L134
train
fastai/fastai
fastai/text/transform.py
Vocab.create
def create(cls, tokens:Tokens, max_vocab:int, min_freq:int) -> 'Vocab': "Create a vocabulary from a set of `tokens`." freq = Counter(p for o in tokens for p in o) itos = [o for o,c in freq.most_common(max_vocab) if c >= min_freq] for o in reversed(defaults.text_spec_tok): if ...
python
def create(cls, tokens:Tokens, max_vocab:int, min_freq:int) -> 'Vocab': "Create a vocabulary from a set of `tokens`." freq = Counter(p for o in tokens for p in o) itos = [o for o,c in freq.most_common(max_vocab) if c >= min_freq] for o in reversed(defaults.text_spec_tok): if ...
[ "def", "create", "(", "cls", ",", "tokens", ":", "Tokens", ",", "max_vocab", ":", "int", ",", "min_freq", ":", "int", ")", "->", "'Vocab'", ":", "freq", "=", "Counter", "(", "p", "for", "o", "in", "tokens", "for", "p", "in", "o", ")", "itos", "="...
Create a vocabulary from a set of `tokens`.
[ "Create", "a", "vocabulary", "from", "a", "set", "of", "tokens", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L148-L155
train
fastai/fastai
fastai/text/transform.py
Vocab.load
def load(cls, path): "Load the `Vocab` contained in `path`" itos = pickle.load(open(path, 'rb')) return cls(itos)
python
def load(cls, path): "Load the `Vocab` contained in `path`" itos = pickle.load(open(path, 'rb')) return cls(itos)
[ "def", "load", "(", "cls", ",", "path", ")", ":", "itos", "=", "pickle", ".", "load", "(", "open", "(", "path", ",", "'rb'", ")", ")", "return", "cls", "(", "itos", ")" ]
Load the `Vocab` contained in `path`
[ "Load", "the", "Vocab", "contained", "in", "path" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L158-L161
train
fastai/fastai
old/fastai/sgdr.py
LossRecorder.plot_loss
def plot_loss(self, n_skip=10, n_skip_end=5): ''' plots loss function as function of iterations. When used in Jupyternotebook, plot will be displayed in notebook. Else, plot will be displayed in console and both plot and loss are saved in save_path. ''' if not in_ipynb(): plt.s...
python
def plot_loss(self, n_skip=10, n_skip_end=5): ''' plots loss function as function of iterations. When used in Jupyternotebook, plot will be displayed in notebook. Else, plot will be displayed in console and both plot and loss are saved in save_path. ''' if not in_ipynb(): plt.s...
[ "def", "plot_loss", "(", "self", ",", "n_skip", "=", "10", ",", "n_skip_end", "=", "5", ")", ":", "if", "not", "in_ipynb", "(", ")", ":", "plt", ".", "switch_backend", "(", "'agg'", ")", "plt", ".", "plot", "(", "self", ".", "iterations", "[", "n_s...
plots loss function as function of iterations. When used in Jupyternotebook, plot will be displayed in notebook. Else, plot will be displayed in console and both plot and loss are saved in save_path.
[ "plots", "loss", "function", "as", "function", "of", "iterations", ".", "When", "used", "in", "Jupyternotebook", "plot", "will", "be", "displayed", "in", "notebook", ".", "Else", "plot", "will", "be", "displayed", "in", "console", "and", "both", "plot", "and...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/sgdr.py#L100-L109
train
fastai/fastai
old/fastai/sgdr.py
LossRecorder.plot_lr
def plot_lr(self): '''Plots learning rate in jupyter notebook or console, depending on the enviroment of the learner.''' if not in_ipynb(): plt.switch_backend('agg') if self.record_mom: fig, axs = plt.subplots(1,2,figsize=(12,4)) for i in range(0,2): axs[i].se...
python
def plot_lr(self): '''Plots learning rate in jupyter notebook or console, depending on the enviroment of the learner.''' if not in_ipynb(): plt.switch_backend('agg') if self.record_mom: fig, axs = plt.subplots(1,2,figsize=(12,4)) for i in range(0,2): axs[i].se...
[ "def", "plot_lr", "(", "self", ")", ":", "if", "not", "in_ipynb", "(", ")", ":", "plt", ".", "switch_backend", "(", "'agg'", ")", "if", "self", ".", "record_mom", ":", "fig", ",", "axs", "=", "plt", ".", "subplots", "(", "1", ",", "2", ",", "figs...
Plots learning rate in jupyter notebook or console, depending on the enviroment of the learner.
[ "Plots", "learning", "rate", "in", "jupyter", "notebook", "or", "console", "depending", "on", "the", "enviroment", "of", "the", "learner", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/sgdr.py#L111-L127
train
fastai/fastai
old/fastai/sgdr.py
LR_Finder.plot
def plot(self, n_skip=10, n_skip_end=5): ''' Plots the loss function with respect to learning rate, in log scale. ''' plt.ylabel("validation loss") plt.xlabel("learning rate (log scale)") plt.plot(self.lrs[n_skip:-(n_skip_end+1)], self.losses[n_skip:-(n_skip_end+1)]) ...
python
def plot(self, n_skip=10, n_skip_end=5): ''' Plots the loss function with respect to learning rate, in log scale. ''' plt.ylabel("validation loss") plt.xlabel("learning rate (log scale)") plt.plot(self.lrs[n_skip:-(n_skip_end+1)], self.losses[n_skip:-(n_skip_end+1)]) ...
[ "def", "plot", "(", "self", ",", "n_skip", "=", "10", ",", "n_skip_end", "=", "5", ")", ":", "plt", ".", "ylabel", "(", "\"validation loss\"", ")", "plt", ".", "xlabel", "(", "\"learning rate (log scale)\"", ")", "plt", ".", "plot", "(", "self", ".", "...
Plots the loss function with respect to learning rate, in log scale.
[ "Plots", "the", "loss", "function", "with", "respect", "to", "learning", "rate", "in", "log", "scale", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/sgdr.py#L190-L197
train
fastai/fastai
old/fastai/sgdr.py
OptimScheduler.plot_lr
def plot_lr(self, show_text=True, show_moms=True): """Plots the lr rate/momentum schedule""" phase_limits = [0] for nb_batch, phase in zip(self.nb_batches, self.phases): phase_limits.append(phase_limits[-1] + nb_batch * phase.epochs) if not in_ipynb(): plt.switch_...
python
def plot_lr(self, show_text=True, show_moms=True): """Plots the lr rate/momentum schedule""" phase_limits = [0] for nb_batch, phase in zip(self.nb_batches, self.phases): phase_limits.append(phase_limits[-1] + nb_batch * phase.epochs) if not in_ipynb(): plt.switch_...
[ "def", "plot_lr", "(", "self", ",", "show_text", "=", "True", ",", "show_moms", "=", "True", ")", ":", "phase_limits", "=", "[", "0", "]", "for", "nb_batch", ",", "phase", "in", "zip", "(", "self", ".", "nb_batches", ",", "self", ".", "phases", ")", ...
Plots the lr rate/momentum schedule
[ "Plots", "the", "lr", "rate", "/", "momentum", "schedule" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/sgdr.py#L557-L583
train
fastai/fastai
examples/train_imagenette.py
main
def main( gpu:Param("GPU to run on", str)=None, woof: Param("Use imagewoof (otherwise imagenette)", int)=0, lr: Param("Learning rate", float)=1e-3, size: Param("Size (px: 128,192,224)", int)=128, alpha: Param("Alpha", float)=0.99, mom: Param("Momentum", float)=0.9, ...
python
def main( gpu:Param("GPU to run on", str)=None, woof: Param("Use imagewoof (otherwise imagenette)", int)=0, lr: Param("Learning rate", float)=1e-3, size: Param("Size (px: 128,192,224)", int)=128, alpha: Param("Alpha", float)=0.99, mom: Param("Momentum", float)=0.9, ...
[ "def", "main", "(", "gpu", ":", "Param", "(", "\"GPU to run on\"", ",", "str", ")", "=", "None", ",", "woof", ":", "Param", "(", "\"Use imagewoof (otherwise imagenette)\"", ",", "int", ")", "=", "0", ",", "lr", ":", "Param", "(", "\"Learning rate\"", ",", ...
Distributed training of Imagenette.
[ "Distributed", "training", "of", "Imagenette", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/examples/train_imagenette.py#L30-L71
train
fastai/fastai
fastai/callbacks/tracker.py
TerminateOnNaNCallback.on_batch_end
def on_batch_end(self, last_loss, epoch, num_batch, **kwargs:Any)->None: "Test if `last_loss` is NaN and interrupts training." if self.stop: return True #to skip validation after stopping during training if torch.isnan(last_loss): print (f'Epoch/Batch ({epoch}/{num_batch}): Invalid l...
python
def on_batch_end(self, last_loss, epoch, num_batch, **kwargs:Any)->None: "Test if `last_loss` is NaN and interrupts training." if self.stop: return True #to skip validation after stopping during training if torch.isnan(last_loss): print (f'Epoch/Batch ({epoch}/{num_batch}): Invalid l...
[ "def", "on_batch_end", "(", "self", ",", "last_loss", ",", "epoch", ",", "num_batch", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "stop", ":", "return", "True", "#to skip validation after stopping during training", "if", "...
Test if `last_loss` is NaN and interrupts training.
[ "Test", "if", "last_loss", "is", "NaN", "and", "interrupts", "training", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L16-L21
train
fastai/fastai
fastai/callbacks/tracker.py
TrackerCallback.on_train_begin
def on_train_begin(self, **kwargs:Any)->None: "Initializes the best value." self.best = float('inf') if self.operator == np.less else -float('inf')
python
def on_train_begin(self, **kwargs:Any)->None: "Initializes the best value." self.best = float('inf') if self.operator == np.less else -float('inf')
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "best", "=", "float", "(", "'inf'", ")", "if", "self", ".", "operator", "==", "np", ".", "less", "else", "-", "float", "(", "'inf'", "...
Initializes the best value.
[ "Initializes", "the", "best", "value", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L35-L37
train
fastai/fastai
fastai/callbacks/tracker.py
TrackerCallback.get_monitor_value
def get_monitor_value(self): "Pick the monitored value." if self.monitor=='trn_loss' and len(self.learn.recorder.losses) == 0: return None elif len(self.learn.recorder.val_losses) == 0: return None values = {'train_loss':self.learn.recorder.losses[-1].cpu().numpy(), 'va...
python
def get_monitor_value(self): "Pick the monitored value." if self.monitor=='trn_loss' and len(self.learn.recorder.losses) == 0: return None elif len(self.learn.recorder.val_losses) == 0: return None values = {'train_loss':self.learn.recorder.losses[-1].cpu().numpy(), 'va...
[ "def", "get_monitor_value", "(", "self", ")", ":", "if", "self", ".", "monitor", "==", "'trn_loss'", "and", "len", "(", "self", ".", "learn", ".", "recorder", ".", "losses", ")", "==", "0", ":", "return", "None", "elif", "len", "(", "self", ".", "lea...
Pick the monitored value.
[ "Pick", "the", "monitored", "value", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L39-L51
train
fastai/fastai
fastai/callbacks/tracker.py
SaveModelCallback.on_epoch_end
def on_epoch_end(self, epoch:int, **kwargs:Any)->None: "Compare the value monitored to its best score and maybe save the model." if self.every=="epoch": self.learn.save(f'{self.name}_{epoch}') else: #every="improvement" current = self.get_monitor_value() if current is not...
python
def on_epoch_end(self, epoch:int, **kwargs:Any)->None: "Compare the value monitored to its best score and maybe save the model." if self.every=="epoch": self.learn.save(f'{self.name}_{epoch}') else: #every="improvement" current = self.get_monitor_value() if current is not...
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ":", "int", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "every", "==", "\"epoch\"", ":", "self", ".", "learn", ".", "save", "(", "f'{self.name}_{epoch}'", ")", "els...
Compare the value monitored to its best score and maybe save the model.
[ "Compare", "the", "value", "monitored", "to", "its", "best", "score", "and", "maybe", "save", "the", "model", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L93-L101
train
fastai/fastai
fastai/callbacks/tracker.py
SaveModelCallback.on_train_end
def on_train_end(self, **kwargs): "Load the best model." if self.every=="improvement" and (self.learn.path/f'{self.learn.model_dir}/{self.name}.pth').is_file(): self.learn.load(f'{self.name}', purge=False)
python
def on_train_end(self, **kwargs): "Load the best model." if self.every=="improvement" and (self.learn.path/f'{self.learn.model_dir}/{self.name}.pth').is_file(): self.learn.load(f'{self.name}', purge=False)
[ "def", "on_train_end", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "every", "==", "\"improvement\"", "and", "(", "self", ".", "learn", ".", "path", "/", "f'{self.learn.model_dir}/{self.name}.pth'", ")", ".", "is_file", "(", ")", ":",...
Load the best model.
[ "Load", "the", "best", "model", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L103-L106
train
fastai/fastai
fastai/callbacks/tracker.py
ReduceLROnPlateauCallback.on_train_begin
def on_train_begin(self, **kwargs:Any)->None: "Initialize inner arguments." self.wait, self.opt = 0, self.learn.opt super().on_train_begin(**kwargs)
python
def on_train_begin(self, **kwargs:Any)->None: "Initialize inner arguments." self.wait, self.opt = 0, self.learn.opt super().on_train_begin(**kwargs)
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "wait", ",", "self", ".", "opt", "=", "0", ",", "self", ".", "learn", ".", "opt", "super", "(", ")", ".", "on_train_begin", "(", "*", ...
Initialize inner arguments.
[ "Initialize", "inner", "arguments", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L116-L119
train
fastai/fastai
fastai/callbacks/tracker.py
ReduceLROnPlateauCallback.on_epoch_end
def on_epoch_end(self, epoch, **kwargs:Any)->None: "Compare the value monitored to its best and maybe reduce lr." current = self.get_monitor_value() if current is None: return if self.operator(current - self.min_delta, self.best): self.best,self.wait = current,0 else: ...
python
def on_epoch_end(self, epoch, **kwargs:Any)->None: "Compare the value monitored to its best and maybe reduce lr." current = self.get_monitor_value() if current is None: return if self.operator(current - self.min_delta, self.best): self.best,self.wait = current,0 else: ...
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "current", "=", "self", ".", "get_monitor_value", "(", ")", "if", "current", "is", "None", ":", "return", "if", "self", ".", "operator", "(...
Compare the value monitored to its best and maybe reduce lr.
[ "Compare", "the", "value", "monitored", "to", "its", "best", "and", "maybe", "reduce", "lr", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L121-L131
train
fastai/fastai
fastai/gen_doc/convert2html.py
convert_nb
def convert_nb(fname, dest_path='.'): "Convert a notebook `fname` to html file in `dest_path`." from .gen_notebooks import remove_undoc_cells, remove_code_cell_jupyter_widget_state_elem nb = read_nb(fname) nb['cells'] = remove_undoc_cells(nb['cells']) nb['cells'] = remove_code_cell_jupyter_widget_st...
python
def convert_nb(fname, dest_path='.'): "Convert a notebook `fname` to html file in `dest_path`." from .gen_notebooks import remove_undoc_cells, remove_code_cell_jupyter_widget_state_elem nb = read_nb(fname) nb['cells'] = remove_undoc_cells(nb['cells']) nb['cells'] = remove_code_cell_jupyter_widget_st...
[ "def", "convert_nb", "(", "fname", ",", "dest_path", "=", "'.'", ")", ":", "from", ".", "gen_notebooks", "import", "remove_undoc_cells", ",", "remove_code_cell_jupyter_widget_state_elem", "nb", "=", "read_nb", "(", "fname", ")", "nb", "[", "'cells'", "]", "=", ...
Convert a notebook `fname` to html file in `dest_path`.
[ "Convert", "a", "notebook", "fname", "to", "html", "file", "in", "dest_path", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/convert2html.py#L21-L33
train
fastai/fastai
fastai/gen_doc/convert2html.py
convert_all
def convert_all(folder, dest_path='.', force_all=False): "Convert modified notebooks in `folder` to html pages in `dest_path`." path = Path(folder) changed_cnt = 0 for fname in path.glob("*.ipynb"): # only rebuild modified files fname_out = Path(dest_path)/fname.with_suffix('.html').nam...
python
def convert_all(folder, dest_path='.', force_all=False): "Convert modified notebooks in `folder` to html pages in `dest_path`." path = Path(folder) changed_cnt = 0 for fname in path.glob("*.ipynb"): # only rebuild modified files fname_out = Path(dest_path)/fname.with_suffix('.html').nam...
[ "def", "convert_all", "(", "folder", ",", "dest_path", "=", "'.'", ",", "force_all", "=", "False", ")", ":", "path", "=", "Path", "(", "folder", ")", "changed_cnt", "=", "0", "for", "fname", "in", "path", ".", "glob", "(", "\"*.ipynb\"", ")", ":", "#...
Convert modified notebooks in `folder` to html pages in `dest_path`.
[ "Convert", "modified", "notebooks", "in", "folder", "to", "html", "pages", "in", "dest_path", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/convert2html.py#L35-L51
train
fastai/fastai
fastai/text/data.py
pad_collate
def pad_collate(samples:BatchSamples, pad_idx:int=1, pad_first:bool=True, backwards:bool=False) -> Tuple[LongTensor, LongTensor]: "Function that collect samples and adds padding. Flips token order if needed" samples = to_data(samples) max_len = max([len(s[0]) for s in samples]) res = torch.zeros(len(sam...
python
def pad_collate(samples:BatchSamples, pad_idx:int=1, pad_first:bool=True, backwards:bool=False) -> Tuple[LongTensor, LongTensor]: "Function that collect samples and adds padding. Flips token order if needed" samples = to_data(samples) max_len = max([len(s[0]) for s in samples]) res = torch.zeros(len(sam...
[ "def", "pad_collate", "(", "samples", ":", "BatchSamples", ",", "pad_idx", ":", "int", "=", "1", ",", "pad_first", ":", "bool", "=", "True", ",", "backwards", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "LongTensor", ",", "LongTensor", "]", ":"...
Function that collect samples and adds padding. Flips token order if needed
[ "Function", "that", "collect", "samples", "and", "adds", "padding", ".", "Flips", "token", "order", "if", "needed" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L128-L138
train
fastai/fastai
fastai/text/data.py
open_text
def open_text(fn:PathOrStr, enc='utf-8'): "Read the text in `fn`." with open(fn,'r', encoding = enc) as f: return ''.join(f.readlines())
python
def open_text(fn:PathOrStr, enc='utf-8'): "Read the text in `fn`." with open(fn,'r', encoding = enc) as f: return ''.join(f.readlines())
[ "def", "open_text", "(", "fn", ":", "PathOrStr", ",", "enc", "=", "'utf-8'", ")", ":", "with", "open", "(", "fn", ",", "'r'", ",", "encoding", "=", "enc", ")", "as", "f", ":", "return", "''", ".", "join", "(", "f", ".", "readlines", "(", ")", "...
Read the text in `fn`.
[ "Read", "the", "text", "in", "fn", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L272-L274
train
fastai/fastai
fastai/text/data.py
LanguageModelPreLoader.allocate_buffers
def allocate_buffers(self): "Create the ragged array that will be filled when we ask for items." if self.ite_len is None: len(self) self.idx = LanguageModelPreLoader.CircularIndex(len(self.dataset.x.items), not self.backwards) self.batch = np.zeros((self.bs, self.bptt+1), dtype=np.int6...
python
def allocate_buffers(self): "Create the ragged array that will be filled when we ask for items." if self.ite_len is None: len(self) self.idx = LanguageModelPreLoader.CircularIndex(len(self.dataset.x.items), not self.backwards) self.batch = np.zeros((self.bs, self.bptt+1), dtype=np.int6...
[ "def", "allocate_buffers", "(", "self", ")", ":", "if", "self", ".", "ite_len", "is", "None", ":", "len", "(", "self", ")", "self", ".", "idx", "=", "LanguageModelPreLoader", ".", "CircularIndex", "(", "len", "(", "self", ".", "dataset", ".", "x", ".",...
Create the ragged array that will be filled when we ask for items.
[ "Create", "the", "ragged", "array", "that", "will", "be", "filled", "when", "we", "ask", "for", "items", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L42-L51
train
fastai/fastai
fastai/text/data.py
LanguageModelPreLoader.fill_row
def fill_row(self, forward, items, idx, row, ro, ri, overlap,lengths): "Fill the row with tokens from the ragged array. --OBS-- overlap != 1 has not been implemented" ibuf = n = 0 ro -= 1 while ibuf < row.size: ro += 1 ix = idx[ro] rag = items[...
python
def fill_row(self, forward, items, idx, row, ro, ri, overlap,lengths): "Fill the row with tokens from the ragged array. --OBS-- overlap != 1 has not been implemented" ibuf = n = 0 ro -= 1 while ibuf < row.size: ro += 1 ix = idx[ro] rag = items[...
[ "def", "fill_row", "(", "self", ",", "forward", ",", "items", ",", "idx", ",", "row", ",", "ro", ",", "ri", ",", "overlap", ",", "lengths", ")", ":", "ibuf", "=", "n", "=", "0", "ro", "-=", "1", "while", "ibuf", "<", "row", ".", "size", ":", ...
Fill the row with tokens from the ragged array. --OBS-- overlap != 1 has not been implemented
[ "Fill", "the", "row", "with", "tokens", "from", "the", "ragged", "array", ".", "--", "OBS", "--", "overlap", "!", "=", "1", "has", "not", "been", "implemented" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L80-L97
train
fastai/fastai
fastai/text/data.py
TextDataBunch.from_ids
def from_ids(cls, path:PathOrStr, vocab:Vocab, train_ids:Collection[Collection[int]], valid_ids:Collection[Collection[int]], test_ids:Collection[Collection[int]]=None, train_lbls:Collection[Union[int,float]]=None, valid_lbls:Collection[Union[int,float]]=None, classes:Collection[Any]=No...
python
def from_ids(cls, path:PathOrStr, vocab:Vocab, train_ids:Collection[Collection[int]], valid_ids:Collection[Collection[int]], test_ids:Collection[Collection[int]]=None, train_lbls:Collection[Union[int,float]]=None, valid_lbls:Collection[Union[int,float]]=None, classes:Collection[Any]=No...
[ "def", "from_ids", "(", "cls", ",", "path", ":", "PathOrStr", ",", "vocab", ":", "Vocab", ",", "train_ids", ":", "Collection", "[", "Collection", "[", "int", "]", "]", ",", "valid_ids", ":", "Collection", "[", "Collection", "[", "int", "]", "]", ",", ...
Create a `TextDataBunch` from ids, labels and a `vocab`. `kwargs` are passed to the dataloader creation.
[ "Create", "a", "TextDataBunch", "from", "ids", "labels", "and", "a", "vocab", ".", "kwargs", "are", "passed", "to", "the", "dataloader", "creation", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L150-L161
train
fastai/fastai
fastai/text/data.py
TextDataBunch.load
def load(cls, path:PathOrStr, cache_name:PathOrStr='tmp', processor:PreProcessor=None, **kwargs): "Load a `TextDataBunch` from `path/cache_name`. `kwargs` are passed to the dataloader creation." warn("""This method is deprecated and only kept to load data serialized in v1.0.43 or earlier. ...
python
def load(cls, path:PathOrStr, cache_name:PathOrStr='tmp', processor:PreProcessor=None, **kwargs): "Load a `TextDataBunch` from `path/cache_name`. `kwargs` are passed to the dataloader creation." warn("""This method is deprecated and only kept to load data serialized in v1.0.43 or earlier. ...
[ "def", "load", "(", "cls", ",", "path", ":", "PathOrStr", ",", "cache_name", ":", "PathOrStr", "=", "'tmp'", ",", "processor", ":", "PreProcessor", "=", "None", ",", "*", "*", "kwargs", ")", ":", "warn", "(", "\"\"\"This method is deprecated and only kept to l...
Load a `TextDataBunch` from `path/cache_name`. `kwargs` are passed to the dataloader creation.
[ "Load", "a", "TextDataBunch", "from", "path", "/", "cache_name", ".", "kwargs", "are", "passed", "to", "the", "dataloader", "creation", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L164-L174
train
fastai/fastai
fastai/text/data.py
TextDataBunch.from_tokens
def from_tokens(cls, path:PathOrStr, trn_tok:Collection[Collection[str]], trn_lbls:Collection[Union[int,float]], val_tok:Collection[Collection[str]], val_lbls:Collection[Union[int,float]], vocab:Vocab=None, tst_tok:Collection[Collection[str]]=None, classes:Collection[Any]=None, max_voc...
python
def from_tokens(cls, path:PathOrStr, trn_tok:Collection[Collection[str]], trn_lbls:Collection[Union[int,float]], val_tok:Collection[Collection[str]], val_lbls:Collection[Union[int,float]], vocab:Vocab=None, tst_tok:Collection[Collection[str]]=None, classes:Collection[Any]=None, max_voc...
[ "def", "from_tokens", "(", "cls", ",", "path", ":", "PathOrStr", ",", "trn_tok", ":", "Collection", "[", "Collection", "[", "str", "]", "]", ",", "trn_lbls", ":", "Collection", "[", "Union", "[", "int", ",", "float", "]", "]", ",", "val_tok", ":", "C...
Create a `TextDataBunch` from tokens and labels. `kwargs` are passed to the dataloader creation.
[ "Create", "a", "TextDataBunch", "from", "tokens", "and", "labels", ".", "kwargs", "are", "passed", "to", "the", "dataloader", "creation", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L177-L187
train
fastai/fastai
fastai/text/data.py
TextDataBunch.from_df
def from_df(cls, path:PathOrStr, train_df:DataFrame, valid_df:DataFrame, test_df:Optional[DataFrame]=None, tokenizer:Tokenizer=None, vocab:Vocab=None, classes:Collection[str]=None, text_cols:IntsOrStrs=1, label_cols:IntsOrStrs=0, label_delim:str=None, chunksize:int=10000, max_vocab:int=6...
python
def from_df(cls, path:PathOrStr, train_df:DataFrame, valid_df:DataFrame, test_df:Optional[DataFrame]=None, tokenizer:Tokenizer=None, vocab:Vocab=None, classes:Collection[str]=None, text_cols:IntsOrStrs=1, label_cols:IntsOrStrs=0, label_delim:str=None, chunksize:int=10000, max_vocab:int=6...
[ "def", "from_df", "(", "cls", ",", "path", ":", "PathOrStr", ",", "train_df", ":", "DataFrame", ",", "valid_df", ":", "DataFrame", ",", "test_df", ":", "Optional", "[", "DataFrame", "]", "=", "None", ",", "tokenizer", ":", "Tokenizer", "=", "None", ",", ...
Create a `TextDataBunch` from DataFrames. `kwargs` are passed to the dataloader creation.
[ "Create", "a", "TextDataBunch", "from", "DataFrames", ".", "kwargs", "are", "passed", "to", "the", "dataloader", "creation", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L190-L206
train
fastai/fastai
fastai/text/data.py
TextDataBunch.from_csv
def from_csv(cls, path:PathOrStr, csv_name, valid_pct:float=0.2, test:Optional[str]=None, tokenizer:Tokenizer=None, vocab:Vocab=None, classes:Collection[str]=None, delimiter:str=None, header='infer', text_cols:IntsOrStrs=1, label_cols:IntsOrStrs=0, label_delim:str=None, ...
python
def from_csv(cls, path:PathOrStr, csv_name, valid_pct:float=0.2, test:Optional[str]=None, tokenizer:Tokenizer=None, vocab:Vocab=None, classes:Collection[str]=None, delimiter:str=None, header='infer', text_cols:IntsOrStrs=1, label_cols:IntsOrStrs=0, label_delim:str=None, ...
[ "def", "from_csv", "(", "cls", ",", "path", ":", "PathOrStr", ",", "csv_name", ",", "valid_pct", ":", "float", "=", "0.2", ",", "test", ":", "Optional", "[", "str", "]", "=", "None", ",", "tokenizer", ":", "Tokenizer", "=", "None", ",", "vocab", ":",...
Create a `TextDataBunch` from texts in csv files. `kwargs` are passed to the dataloader creation.
[ "Create", "a", "TextDataBunch", "from", "texts", "in", "csv", "files", ".", "kwargs", "are", "passed", "to", "the", "dataloader", "creation", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L209-L223
train
fastai/fastai
fastai/text/data.py
TextDataBunch.from_folder
def from_folder(cls, path:PathOrStr, train:str='train', valid:str='valid', test:Optional[str]=None, classes:Collection[Any]=None, tokenizer:Tokenizer=None, vocab:Vocab=None, chunksize:int=10000, max_vocab:int=60000, min_freq:int=2, mark_fields:bool=False, include_bos:bool=True, i...
python
def from_folder(cls, path:PathOrStr, train:str='train', valid:str='valid', test:Optional[str]=None, classes:Collection[Any]=None, tokenizer:Tokenizer=None, vocab:Vocab=None, chunksize:int=10000, max_vocab:int=60000, min_freq:int=2, mark_fields:bool=False, include_bos:bool=True, i...
[ "def", "from_folder", "(", "cls", ",", "path", ":", "PathOrStr", ",", "train", ":", "str", "=", "'train'", ",", "valid", ":", "str", "=", "'valid'", ",", "test", ":", "Optional", "[", "str", "]", "=", "None", ",", "classes", ":", "Collection", "[", ...
Create a `TextDataBunch` from text files in folders.
[ "Create", "a", "TextDataBunch", "from", "text", "files", "in", "folders", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L226-L237
train
fastai/fastai
fastai/text/data.py
TextLMDataBunch.create
def create(cls, train_ds, valid_ds, test_ds=None, path:PathOrStr='.', no_check:bool=False, bs=64, val_bs:int=None, num_workers:int=0, device:torch.device=None, collate_fn:Callable=data_collate, dl_tfms:Optional[Collection[Callable]]=None, bptt:int=70, backwards:bool=False, **dl_kwargs) -> ...
python
def create(cls, train_ds, valid_ds, test_ds=None, path:PathOrStr='.', no_check:bool=False, bs=64, val_bs:int=None, num_workers:int=0, device:torch.device=None, collate_fn:Callable=data_collate, dl_tfms:Optional[Collection[Callable]]=None, bptt:int=70, backwards:bool=False, **dl_kwargs) -> ...
[ "def", "create", "(", "cls", ",", "train_ds", ",", "valid_ds", ",", "test_ds", "=", "None", ",", "path", ":", "PathOrStr", "=", "'.'", ",", "no_check", ":", "bool", "=", "False", ",", "bs", "=", "64", ",", "val_bs", ":", "int", "=", "None", ",", ...
Create a `TextDataBunch` in `path` from the `datasets` for language modelling. Passes `**dl_kwargs` on to `DataLoader()`
[ "Create", "a", "TextDataBunch", "in", "path", "from", "the", "datasets", "for", "language", "modelling", ".", "Passes", "**", "dl_kwargs", "on", "to", "DataLoader", "()" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L242-L252
train
fastai/fastai
fastai/text/data.py
TextClasDataBunch.create
def create(cls, train_ds, valid_ds, test_ds=None, path:PathOrStr='.', bs:int=32, val_bs:int=None, pad_idx=1, pad_first=True, device:torch.device=None, no_check:bool=False, backwards:bool=False, **dl_kwargs) -> DataBunch: "Function that transform the `datasets` in a `DataBunch` for classification....
python
def create(cls, train_ds, valid_ds, test_ds=None, path:PathOrStr='.', bs:int=32, val_bs:int=None, pad_idx=1, pad_first=True, device:torch.device=None, no_check:bool=False, backwards:bool=False, **dl_kwargs) -> DataBunch: "Function that transform the `datasets` in a `DataBunch` for classification....
[ "def", "create", "(", "cls", ",", "train_ds", ",", "valid_ds", ",", "test_ds", "=", "None", ",", "path", ":", "PathOrStr", "=", "'.'", ",", "bs", ":", "int", "=", "32", ",", "val_bs", ":", "int", "=", "None", ",", "pad_idx", "=", "1", ",", "pad_f...
Function that transform the `datasets` in a `DataBunch` for classification. Passes `**dl_kwargs` on to `DataLoader()`
[ "Function", "that", "transform", "the", "datasets", "in", "a", "DataBunch", "for", "classification", ".", "Passes", "**", "dl_kwargs", "on", "to", "DataLoader", "()" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L257-L270
train
fastai/fastai
fastai/text/data.py
TextList.label_for_lm
def label_for_lm(self, **kwargs): "A special labelling method for language models." self.__class__ = LMTextList kwargs['label_cls'] = LMLabelList return self.label_const(0, **kwargs)
python
def label_for_lm(self, **kwargs): "A special labelling method for language models." self.__class__ = LMTextList kwargs['label_cls'] = LMLabelList return self.label_const(0, **kwargs)
[ "def", "label_for_lm", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__class__", "=", "LMTextList", "kwargs", "[", "'label_cls'", "]", "=", "LMLabelList", "return", "self", ".", "label_const", "(", "0", ",", "*", "*", "kwargs", ")" ]
A special labelling method for language models.
[ "A", "special", "labelling", "method", "for", "language", "models", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L330-L334
train
fastai/fastai
fastai/text/data.py
TextList.from_folder
def from_folder(cls, path:PathOrStr='.', extensions:Collection[str]=text_extensions, vocab:Vocab=None, processor:PreProcessor=None, **kwargs)->'TextList': "Get the list of files in `path` that have a text suffix. `recurse` determines if we search subfolders." processor = ifnone(proce...
python
def from_folder(cls, path:PathOrStr='.', extensions:Collection[str]=text_extensions, vocab:Vocab=None, processor:PreProcessor=None, **kwargs)->'TextList': "Get the list of files in `path` that have a text suffix. `recurse` determines if we search subfolders." processor = ifnone(proce...
[ "def", "from_folder", "(", "cls", ",", "path", ":", "PathOrStr", "=", "'.'", ",", "extensions", ":", "Collection", "[", "str", "]", "=", "text_extensions", ",", "vocab", ":", "Vocab", "=", "None", ",", "processor", ":", "PreProcessor", "=", "None", ",", ...
Get the list of files in `path` that have a text suffix. `recurse` determines if we search subfolders.
[ "Get", "the", "list", "of", "files", "in", "path", "that", "have", "a", "text", "suffix", ".", "recurse", "determines", "if", "we", "search", "subfolders", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L342-L346
train
fastai/fastai
fastai/text/data.py
TextList.show_xys
def show_xys(self, xs, ys, max_len:int=70)->None: "Show the `xs` (inputs) and `ys` (targets). `max_len` is the maximum number of tokens displayed." from IPython.display import display, HTML names = ['idx','text'] if self._is_lm else ['text','target'] items = [] for i, (x,y) in en...
python
def show_xys(self, xs, ys, max_len:int=70)->None: "Show the `xs` (inputs) and `ys` (targets). `max_len` is the maximum number of tokens displayed." from IPython.display import display, HTML names = ['idx','text'] if self._is_lm else ['text','target'] items = [] for i, (x,y) in en...
[ "def", "show_xys", "(", "self", ",", "xs", ",", "ys", ",", "max_len", ":", "int", "=", "70", ")", "->", "None", ":", "from", "IPython", ".", "display", "import", "display", ",", "HTML", "names", "=", "[", "'idx'", ",", "'text'", "]", "if", "self", ...
Show the `xs` (inputs) and `ys` (targets). `max_len` is the maximum number of tokens displayed.
[ "Show", "the", "xs", "(", "inputs", ")", "and", "ys", "(", "targets", ")", ".", "max_len", "is", "the", "maximum", "number", "of", "tokens", "displayed", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L348-L359
train
fastai/fastai
old/fastai/models/inceptionv4.py
inceptionv4
def inceptionv4(pretrained=True): r"""InceptionV4 model architecture from the `"Inception-v4, Inception-ResNet..." <https://arxiv.org/abs/1602.07261>`_ paper. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = InceptionV4() if pretrained: model...
python
def inceptionv4(pretrained=True): r"""InceptionV4 model architecture from the `"Inception-v4, Inception-ResNet..." <https://arxiv.org/abs/1602.07261>`_ paper. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = InceptionV4() if pretrained: model...
[ "def", "inceptionv4", "(", "pretrained", "=", "True", ")", ":", "model", "=", "InceptionV4", "(", ")", "if", "pretrained", ":", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "model_urls", "[", "'imagenet'", "]", ")", ")", "return...
r"""InceptionV4 model architecture from the `"Inception-v4, Inception-ResNet..." <https://arxiv.org/abs/1602.07261>`_ paper. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
[ "r", "InceptionV4", "model", "architecture", "from", "the", "Inception", "-", "v4", "Inception", "-", "ResNet", "...", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1602", ".", "07261", ">", "_", "paper", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/models/inceptionv4.py#L263-L273
train
fastai/fastai
old/fastai/conv_learner.py
ConvLearner.predict_array
def predict_array(self, arr): """ This over-ride is necessary because otherwise the learner method accesses the wrong model when it is called with precompute set to true Args: arr: a numpy array to be used as input to the model for prediction purposes Returns: ...
python
def predict_array(self, arr): """ This over-ride is necessary because otherwise the learner method accesses the wrong model when it is called with precompute set to true Args: arr: a numpy array to be used as input to the model for prediction purposes Returns: ...
[ "def", "predict_array", "(", "self", ",", "arr", ")", ":", "precompute", "=", "self", ".", "precompute", "self", ".", "precompute", "=", "False", "pred", "=", "super", "(", ")", ".", "predict_array", "(", "arr", ")", "self", ".", "precompute", "=", "pr...
This over-ride is necessary because otherwise the learner method accesses the wrong model when it is called with precompute set to true Args: arr: a numpy array to be used as input to the model for prediction purposes Returns: a numpy array containing the predictions fro...
[ "This", "over", "-", "ride", "is", "necessary", "because", "otherwise", "the", "learner", "method", "accesses", "the", "wrong", "model", "when", "it", "is", "called", "with", "precompute", "set", "to", "true" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/conv_learner.py#L211-L225
train
fastai/fastai
examples/train_cifar.py
main
def main( gpu:Param("GPU to run on", str)=None ): """Distrubuted training of CIFAR-10. Fastest speed is if you run as follows: python -m fastai.launch train_cifar.py""" gpu = setup_distrib(gpu) n_gpus = num_distrib() path = url2path(URLs.CIFAR) ds_tfms = ([*rand_pad(4, 32), flip_lr(p=0.5...
python
def main( gpu:Param("GPU to run on", str)=None ): """Distrubuted training of CIFAR-10. Fastest speed is if you run as follows: python -m fastai.launch train_cifar.py""" gpu = setup_distrib(gpu) n_gpus = num_distrib() path = url2path(URLs.CIFAR) ds_tfms = ([*rand_pad(4, 32), flip_lr(p=0.5...
[ "def", "main", "(", "gpu", ":", "Param", "(", "\"GPU to run on\"", ",", "str", ")", "=", "None", ")", ":", "gpu", "=", "setup_distrib", "(", "gpu", ")", "n_gpus", "=", "num_distrib", "(", ")", "path", "=", "url2path", "(", "URLs", ".", "CIFAR", ")", ...
Distrubuted training of CIFAR-10. Fastest speed is if you run as follows: python -m fastai.launch train_cifar.py
[ "Distrubuted", "training", "of", "CIFAR", "-", "10", ".", "Fastest", "speed", "is", "if", "you", "run", "as", "follows", ":", "python", "-", "m", "fastai", ".", "launch", "train_cifar", ".", "py" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/examples/train_cifar.py#L8-L23
train
fastai/fastai
setup.py
DepsCommand.initialize_options
def initialize_options(self): """Set default values for options.""" self.dep_groups = '' self.dep_quote = False self.dep_conda = False
python
def initialize_options(self): """Set default values for options.""" self.dep_groups = '' self.dep_quote = False self.dep_conda = False
[ "def", "initialize_options", "(", "self", ")", ":", "self", ".", "dep_groups", "=", "''", "self", ".", "dep_quote", "=", "False", "self", ".", "dep_conda", "=", "False" ]
Set default values for options.
[ "Set", "default", "values", "for", "options", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/setup.py#L32-L36
train
fastai/fastai
setup.py
DepsCommand.run
def run(self): """Run command.""" wanted_groups = self.parse() deps = [] invalid_groups = [] for grp in wanted_groups: if grp in dep_groups: deps.extend(dep_groups[grp]) else: invalid_groups.append(grp) if invalid_groups or not wa...
python
def run(self): """Run command.""" wanted_groups = self.parse() deps = [] invalid_groups = [] for grp in wanted_groups: if grp in dep_groups: deps.extend(dep_groups[grp]) else: invalid_groups.append(grp) if invalid_groups or not wa...
[ "def", "run", "(", "self", ")", ":", "wanted_groups", "=", "self", ".", "parse", "(", ")", "deps", "=", "[", "]", "invalid_groups", "=", "[", "]", "for", "grp", "in", "wanted_groups", ":", "if", "grp", "in", "dep_groups", ":", "deps", ".", "extend", ...
Run command.
[ "Run", "command", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/setup.py#L46-L75
train
fastai/fastai
old/fastai/models/unet.py
get_sfs_idxs
def get_sfs_idxs(sfs, last=True): """ Return the saved feature indexes that will be concatenated Inputs: sfs (list): saved features by hook function, in other words intermediate activations last (bool): whether to concatenate only last different activation, or all from the encoder model ...
python
def get_sfs_idxs(sfs, last=True): """ Return the saved feature indexes that will be concatenated Inputs: sfs (list): saved features by hook function, in other words intermediate activations last (bool): whether to concatenate only last different activation, or all from the encoder model ...
[ "def", "get_sfs_idxs", "(", "sfs", ",", "last", "=", "True", ")", ":", "if", "last", ":", "feature_szs", "=", "[", "sfs_feats", ".", "features", ".", "size", "(", ")", "[", "-", "1", "]", "for", "sfs_feats", "in", "sfs", "]", "sfs_idxs", "=", "list...
Return the saved feature indexes that will be concatenated Inputs: sfs (list): saved features by hook function, in other words intermediate activations last (bool): whether to concatenate only last different activation, or all from the encoder model
[ "Return", "the", "saved", "feature", "indexes", "that", "will", "be", "concatenated", "Inputs", ":", "sfs", "(", "list", ")", ":", "saved", "features", "by", "hook", "function", "in", "other", "words", "intermediate", "activations", "last", "(", "bool", ")",...
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/models/unet.py#L7-L19
train
fastai/fastai
fastai/callbacks/hooks.py
hook_output
def hook_output (module:nn.Module, detach:bool=True, grad:bool=False)->Hook: "Return a `Hook` that stores activations of `module` in `self.stored`" return Hook(module, _hook_inner, detach=detach, is_forward=not grad)
python
def hook_output (module:nn.Module, detach:bool=True, grad:bool=False)->Hook: "Return a `Hook` that stores activations of `module` in `self.stored`" return Hook(module, _hook_inner, detach=detach, is_forward=not grad)
[ "def", "hook_output", "(", "module", ":", "nn", ".", "Module", ",", "detach", ":", "bool", "=", "True", ",", "grad", ":", "bool", "=", "False", ")", "->", "Hook", ":", "return", "Hook", "(", "module", ",", "_hook_inner", ",", "detach", "=", "detach",...
Return a `Hook` that stores activations of `module` in `self.stored`
[ "Return", "a", "Hook", "that", "stores", "activations", "of", "module", "in", "self", ".", "stored" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L54-L56
train
fastai/fastai
fastai/callbacks/hooks.py
hook_outputs
def hook_outputs(modules:Collection[nn.Module], detach:bool=True, grad:bool=False)->Hooks: "Return `Hooks` that store activations of all `modules` in `self.stored`" return Hooks(modules, _hook_inner, detach=detach, is_forward=not grad)
python
def hook_outputs(modules:Collection[nn.Module], detach:bool=True, grad:bool=False)->Hooks: "Return `Hooks` that store activations of all `modules` in `self.stored`" return Hooks(modules, _hook_inner, detach=detach, is_forward=not grad)
[ "def", "hook_outputs", "(", "modules", ":", "Collection", "[", "nn", ".", "Module", "]", ",", "detach", ":", "bool", "=", "True", ",", "grad", ":", "bool", "=", "False", ")", "->", "Hooks", ":", "return", "Hooks", "(", "modules", ",", "_hook_inner", ...
Return `Hooks` that store activations of all `modules` in `self.stored`
[ "Return", "Hooks", "that", "store", "activations", "of", "all", "modules", "in", "self", ".", "stored" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L58-L60
train
fastai/fastai
fastai/callbacks/hooks.py
dummy_batch
def dummy_batch(m: nn.Module, size:tuple=(64,64))->Tensor: "Create a dummy batch to go through `m` with `size`." ch_in = in_channels(m) return one_param(m).new(1, ch_in, *size).requires_grad_(False).uniform_(-1.,1.)
python
def dummy_batch(m: nn.Module, size:tuple=(64,64))->Tensor: "Create a dummy batch to go through `m` with `size`." ch_in = in_channels(m) return one_param(m).new(1, ch_in, *size).requires_grad_(False).uniform_(-1.,1.)
[ "def", "dummy_batch", "(", "m", ":", "nn", ".", "Module", ",", "size", ":", "tuple", "=", "(", "64", ",", "64", ")", ")", "->", "Tensor", ":", "ch_in", "=", "in_channels", "(", "m", ")", "return", "one_param", "(", "m", ")", ".", "new", "(", "1...
Create a dummy batch to go through `m` with `size`.
[ "Create", "a", "dummy", "batch", "to", "go", "through", "m", "with", "size", "." ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L101-L104
train