partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
ModelImageSet.get_list_from_model
Factory method to convert a batch of model images to a list of ModelImageSet.
fastai/callbacks/tensorboard.py
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 orig_px, real_px, gen in zip(x,y,preds): orig, real = Image(px=orig_px), Image(px=real_px) image_set = ModelImageSet(orig=orig, real=real, gen=gen) image_sets.append(image_set) return image_sets
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 orig_px, real_px, gen in zip(x,y,preds): orig, real = Image(px=orig_px), Image(px=real_px) image_set = ModelImageSet(orig=orig, real=real, gen=gen) image_sets.append(image_set) return image_sets
[ "Factory", "method", "to", "convert", "a", "batch", "of", "model", "images", "to", "a", "list", "of", "ModelImageSet", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L248-L257
[ "def", "get_list_from_model", "(", "learn", ":", "Learner", ",", "ds_type", ":", "DatasetType", ",", "batch", ":", "Tuple", ")", "->", "[", "]", ":", "image_sets", "=", "[", "]", "x", ",", "y", "=", "batch", "[", "0", "]", ",", "batch", "[", "1", "]", "preds", "=", "learn", ".", "pred_batch", "(", "ds_type", "=", "ds_type", ",", "batch", "=", "(", "x", ",", "y", ")", ",", "reconstruct", "=", "True", ")", "for", "orig_px", ",", "real_px", ",", "gen", "in", "zip", "(", "x", ",", "y", ",", "preds", ")", ":", "orig", ",", "real", "=", "Image", "(", "px", "=", "orig_px", ")", ",", "Image", "(", "px", "=", "real_px", ")", "image_set", "=", "ModelImageSet", "(", "orig", "=", "orig", ",", "real", "=", "real", ",", "gen", "=", "gen", ")", "image_sets", ".", "append", "(", "image_set", ")", "return", "image_sets" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
HistogramTBRequest._write_histogram
Writes single model histogram to Tensorboard.
fastai/callbacks/tensorboard.py
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: "Writes single model histogram to Tensorboard." tag = self.name + '/weights/' + param_name self.tbwriter.add_histogram(tag=tag, values=values, global_step=self.iteration)
[ "Writes", "single", "model", "histogram", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L268-L271
[ "def", "_write_histogram", "(", "self", ",", "param_name", ":", "str", ",", "values", ")", "->", "None", ":", "tag", "=", "self", ".", "name", "+", "'/weights/'", "+", "param_name", "self", ".", "tbwriter", ".", "add_histogram", "(", "tag", "=", "tag", ",", "values", "=", "values", ",", "global_step", "=", "self", ".", "iteration", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
HistogramTBRequest.write
Writes model histograms to Tensorboard.
fastai/callbacks/tensorboard.py
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: "Writes model histograms to Tensorboard." for param_name, values in self.params: self._write_histogram(param_name=param_name, values=values)
[ "Writes", "model", "histograms", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L273-L275
[ "def", "write", "(", "self", ")", "->", "None", ":", "for", "param_name", ",", "values", "in", "self", ".", "params", ":", "self", ".", "_write_histogram", "(", "param_name", "=", "param_name", ",", "values", "=", "values", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
HistogramTBWriter.write
Writes model histograms to Tensorboard.
fastai/callbacks/tensorboard.py
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: "Writes model histograms to Tensorboard." request = HistogramTBRequest(model=model, iteration=iteration, tbwriter=tbwriter, name=name) asyncTBWriter.request_write(request)
[ "Writes", "model", "histograms", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L282-L285
[ "def", "write", "(", "self", ",", "model", ":", "nn", ".", "Module", ",", "iteration", ":", "int", ",", "tbwriter", ":", "SummaryWriter", ",", "name", ":", "str", "=", "'model'", ")", "->", "None", ":", "request", "=", "HistogramTBRequest", "(", "model", "=", "model", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", "tbwriter", ",", "name", "=", "name", ")", "asyncTBWriter", ".", "request_write", "(", "request", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ModelStatsTBRequest._add_gradient_scalar
Writes a single scalar value for a gradient statistic to Tensorboard.
fastai/callbacks/tensorboard.py
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: "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)
[ "Writes", "a", "single", "scalar", "value", "for", "a", "gradient", "statistic", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L294-L297
[ "def", "_add_gradient_scalar", "(", "self", ",", "name", ":", "str", ",", "scalar_value", ")", "->", "None", ":", "tag", "=", "self", ".", "name", "+", "'/gradients/'", "+", "name", "self", ".", "tbwriter", ".", "add_scalar", "(", "tag", "=", "tag", ",", "scalar_value", "=", "scalar_value", ",", "global_step", "=", "self", ".", "iteration", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ModelStatsTBRequest._write_avg_norm
Writes the average norm of the gradients to Tensorboard.
fastai/callbacks/tensorboard.py
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: "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)
[ "Writes", "the", "average", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L299-L302
[ "def", "_write_avg_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "avg_norm", "=", "sum", "(", "norms", ")", "/", "len", "(", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'avg_norm'", ",", "scalar_value", "=", "avg_norm", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ModelStatsTBRequest._write_median_norm
Writes the median norm of the gradients to Tensorboard.
fastai/callbacks/tensorboard.py
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: "Writes the median norm of the gradients to Tensorboard." median_norm = statistics.median(norms) self._add_gradient_scalar('median_norm', scalar_value=median_norm)
[ "Writes", "the", "median", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L304-L307
[ "def", "_write_median_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "median_norm", "=", "statistics", ".", "median", "(", "norms", ")", "self", ".", "_add_gradient_scalar", "(", "'median_norm'", ",", "scalar_value", "=", "median_norm", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ModelStatsTBRequest._write_max_norm
Writes the maximum norm of the gradients to Tensorboard.
fastai/callbacks/tensorboard.py
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: "Writes the maximum norm of the gradients to Tensorboard." max_norm = max(norms) self._add_gradient_scalar('max_norm', scalar_value=max_norm)
[ "Writes", "the", "maximum", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L309-L312
[ "def", "_write_max_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "max_norm", "=", "max", "(", "norms", ")", "self", ".", "_add_gradient_scalar", "(", "'max_norm'", ",", "scalar_value", "=", "max_norm", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ModelStatsTBRequest._write_min_norm
Writes the minimum norm of the gradients to Tensorboard.
fastai/callbacks/tensorboard.py
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: "Writes the minimum norm of the gradients to Tensorboard." min_norm = min(norms) self._add_gradient_scalar('min_norm', scalar_value=min_norm)
[ "Writes", "the", "minimum", "norm", "of", "the", "gradients", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L314-L317
[ "def", "_write_min_norm", "(", "self", ",", "norms", ":", "[", "]", ")", "->", "None", ":", "min_norm", "=", "min", "(", "norms", ")", "self", ".", "_add_gradient_scalar", "(", "'min_norm'", ",", "scalar_value", "=", "min_norm", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ModelStatsTBRequest._write_num_zeros
Writes the number of zeroes in the gradients to Tensorboard.
fastai/callbacks/tensorboard.py
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: "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)
[ "Writes", "the", "number", "of", "zeroes", "in", "the", "gradients", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L319-L323
[ "def", "_write_num_zeros", "(", "self", ")", "->", "None", ":", "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", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ModelStatsTBRequest._write_avg_gradient
Writes the average of the gradients to Tensorboard.
fastai/callbacks/tensorboard.py
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: "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)
[ "Writes", "the", "average", "of", "the", "gradients", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L325-L328
[ "def", "_write_avg_gradient", "(", "self", ")", "->", "None", ":", "avg_gradient", "=", "sum", "(", "x", ".", "data", ".", "mean", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "/", "len", "(", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'avg_gradient'", ",", "scalar_value", "=", "avg_gradient", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ModelStatsTBRequest._write_median_gradient
Writes the median of the gradients to Tensorboard.
fastai/callbacks/tensorboard.py
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: "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)
[ "Writes", "the", "median", "of", "the", "gradients", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L330-L333
[ "def", "_write_median_gradient", "(", "self", ")", "->", "None", ":", "median_gradient", "=", "statistics", ".", "median", "(", "x", ".", "data", ".", "median", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'median_gradient'", ",", "scalar_value", "=", "median_gradient", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ModelStatsTBRequest._write_max_gradient
Writes the maximum of the gradients to Tensorboard.
fastai/callbacks/tensorboard.py
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: "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)
[ "Writes", "the", "maximum", "of", "the", "gradients", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L335-L338
[ "def", "_write_max_gradient", "(", "self", ")", "->", "None", ":", "max_gradient", "=", "max", "(", "x", ".", "data", ".", "max", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'max_gradient'", ",", "scalar_value", "=", "max_gradient", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ModelStatsTBRequest._write_min_gradient
Writes the minimum of the gradients to Tensorboard.
fastai/callbacks/tensorboard.py
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: "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)
[ "Writes", "the", "minimum", "of", "the", "gradients", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L340-L343
[ "def", "_write_min_gradient", "(", "self", ")", "->", "None", ":", "min_gradient", "=", "min", "(", "x", ".", "data", ".", "min", "(", ")", "for", "x", "in", "self", ".", "gradients", ")", "self", ".", "_add_gradient_scalar", "(", "'min_gradient'", ",", "scalar_value", "=", "min_gradient", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ModelStatsTBRequest.write
Writes model gradient statistics to Tensorboard.
fastai/callbacks/tensorboard.py
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) self._write_min_norm(norms=norms) self._write_num_zeros() self._write_avg_gradient() self._write_median_gradient() self._write_max_gradient() self._write_min_gradient()
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) self._write_min_norm(norms=norms) self._write_num_zeros() self._write_avg_gradient() self._write_median_gradient() self._write_max_gradient() self._write_min_gradient()
[ "Writes", "model", "gradient", "statistics", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L345-L357
[ "def", "write", "(", "self", ")", "->", "None", ":", "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", ")", "self", ".", "_write_min_norm", "(", "norms", "=", "norms", ")", "self", ".", "_write_num_zeros", "(", ")", "self", ".", "_write_avg_gradient", "(", ")", "self", ".", "_write_median_gradient", "(", ")", "self", ".", "_write_max_gradient", "(", ")", "self", ".", "_write_min_gradient", "(", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageTBRequest._write_images
Writes list of images as tensors to Tensorboard.
fastai/callbacks/tensorboard.py
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: "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)
[ "Writes", "list", "of", "images", "as", "tensors", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L373-L376
[ "def", "_write_images", "(", "self", ",", "name", ":", "str", ",", "images", ":", "[", "Tensor", "]", ")", "->", "None", ":", "tag", "=", "self", ".", "ds_type", ".", "name", "+", "' '", "+", "name", "self", ".", "tbwriter", ".", "add_image", "(", "tag", "=", "tag", ",", "img_tensor", "=", "vutils", ".", "make_grid", "(", "images", ",", "normalize", "=", "True", ")", ",", "global_step", "=", "self", ".", "iteration", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageTBRequest._get_image_tensors
Gets list of image tensors from lists of Image objects, as a tuple of original, generated and real(target) images.
fastai/callbacks/tensorboard.py
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(image_set.orig.px) gen_images.append(image_set.gen.px) real_images.append(image_set.real.px) return orig_images, gen_images, real_images
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(image_set.orig.px) gen_images.append(image_set.gen.px) real_images.append(image_set.real.px) return orig_images, gen_images, real_images
[ "Gets", "list", "of", "image", "tensors", "from", "lists", "of", "Image", "objects", "as", "a", "tuple", "of", "original", "generated", "and", "real", "(", "target", ")", "images", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L378-L385
[ "def", "_get_image_tensors", "(", "self", ")", "->", "(", "[", "Tensor", "]", ",", "[", "Tensor", "]", ",", "[", "Tensor", "]", ")", ":", "orig_images", ",", "gen_images", ",", "real_images", "=", "[", "]", ",", "[", "]", ",", "[", "]", "for", "image_set", "in", "self", ".", "image_sets", ":", "orig_images", ".", "append", "(", "image_set", ".", "orig", ".", "px", ")", "gen_images", ".", "append", "(", "image_set", ".", "gen", ".", "px", ")", "real_images", ".", "append", "(", "image_set", ".", "real", ".", "px", ")", "return", "orig_images", ",", "gen_images", ",", "real_images" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageTBRequest.write
Writes original, generated and real(target) images to Tensorboard.
fastai/callbacks/tensorboard.py
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._write_images(name='real images', images=real_images)
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._write_images(name='real images', images=real_images)
[ "Writes", "original", "generated", "and", "real", "(", "target", ")", "images", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L387-L392
[ "def", "write", "(", "self", ")", "->", "None", ":", "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", ".", "_write_images", "(", "name", "=", "'real images'", ",", "images", "=", "real_images", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageTBWriter.write
Writes training and validation batch images to Tensorboard.
fastai/callbacks/tensorboard.py
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) self._write_for_dstype(learn=learn, batch=trn_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Train)
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) self._write_for_dstype(learn=learn, batch=trn_batch, iteration=iteration, tbwriter=tbwriter, ds_type=DatasetType.Train)
[ "Writes", "training", "and", "validation", "batch", "images", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L399-L402
[ "def", "write", "(", "self", ",", "learn", ":", "Learner", ",", "trn_batch", ":", "Tuple", ",", "val_batch", ":", "Tuple", ",", "iteration", ":", "int", ",", "tbwriter", ":", "SummaryWriter", ")", "->", "None", ":", "self", ".", "_write_for_dstype", "(", "learn", "=", "learn", ",", "batch", "=", "val_batch", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", "tbwriter", ",", "ds_type", "=", "DatasetType", ".", "Valid", ")", "self", ".", "_write_for_dstype", "(", "learn", "=", "learn", ",", "batch", "=", "trn_batch", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", "tbwriter", ",", "ds_type", "=", "DatasetType", ".", "Train", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageTBWriter._write_for_dstype
Writes batch images of specified DatasetType to Tensorboard.
fastai/callbacks/tensorboard.py
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) asyncTBWriter.request_write(request)
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) asyncTBWriter.request_write(request)
[ "Writes", "batch", "images", "of", "specified", "DatasetType", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L404-L407
[ "def", "_write_for_dstype", "(", "self", ",", "learn", ":", "Learner", ",", "batch", ":", "Tuple", ",", "iteration", ":", "int", ",", "tbwriter", ":", "SummaryWriter", ",", "ds_type", ":", "DatasetType", ")", "->", "None", ":", "request", "=", "ImageTBRequest", "(", "learn", "=", "learn", ",", "batch", "=", "batch", ",", "iteration", "=", "iteration", ",", "tbwriter", "=", "tbwriter", ",", "ds_type", "=", "ds_type", ")", "asyncTBWriter", ".", "request_write", "(", "request", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
GraphTBRequest.write
Writes single model graph to Tensorboard.
fastai/callbacks/tensorboard.py
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: "Writes single model graph to Tensorboard." self.tbwriter.add_graph(model=self.model, input_to_model=self.input_to_model)
[ "Writes", "single", "model", "graph", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L415-L417
[ "def", "write", "(", "self", ")", "->", "None", ":", "self", ".", "tbwriter", ".", "add_graph", "(", "model", "=", "self", ".", "model", ",", "input_to_model", "=", "self", ".", "input_to_model", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
GraphTBWriter.write
Writes model graph to Tensorboard.
fastai/callbacks/tensorboard.py
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: "Writes model graph to Tensorboard." request = GraphTBRequest(model=model, tbwriter=tbwriter, input_to_model=input_to_model) asyncTBWriter.request_write(request)
[ "Writes", "model", "graph", "to", "Tensorboard", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L421-L424
[ "def", "write", "(", "self", ",", "model", ":", "nn", ".", "Module", ",", "tbwriter", ":", "SummaryWriter", ",", "input_to_model", ":", "torch", ".", "Tensor", ")", "->", "None", ":", "request", "=", "GraphTBRequest", "(", "model", "=", "model", ",", "tbwriter", "=", "tbwriter", ",", "input_to_model", "=", "input_to_model", ")", "asyncTBWriter", ".", "request_write", "(", "request", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
fix_batchnorm
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 compute the correct batch norm statistics. Before performing inference with the SWA model, we perform a single pass over the training data to calculate an accurate running mean and variance for each batch norm layer.
old/fastai/swa.py
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 itself, and therefore has no opportunity to compute the correct batch norm statistics. Before performing inference with the SWA model, we perform a single pass over the training data to calculate an accurate running mean and variance for each batch norm layer. """ bn_modules = [] swa_model.apply(lambda module: collect_bn_modules(module, bn_modules)) if not bn_modules: return swa_model.train() for module in bn_modules: module.running_mean = torch.zeros_like(module.running_mean) module.running_var = torch.ones_like(module.running_var) momenta = [m.momentum for m in bn_modules] inputs_seen = 0 for (*x,y) in iter(train_dl): xs = V(x) batch_size = xs[0].size(0) momentum = batch_size / (inputs_seen + batch_size) for module in bn_modules: module.momentum = momentum res = swa_model(*xs) inputs_seen += batch_size for module, momentum in zip(bn_modules, momenta): module.momentum = momentum
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 itself, and therefore has no opportunity to compute the correct batch norm statistics. Before performing inference with the SWA model, we perform a single pass over the training data to calculate an accurate running mean and variance for each batch norm layer. """ bn_modules = [] swa_model.apply(lambda module: collect_bn_modules(module, bn_modules)) if not bn_modules: return swa_model.train() for module in bn_modules: module.running_mean = torch.zeros_like(module.running_mean) module.running_var = torch.ones_like(module.running_var) momenta = [m.momentum for m in bn_modules] inputs_seen = 0 for (*x,y) in iter(train_dl): xs = V(x) batch_size = xs[0].size(0) momentum = batch_size / (inputs_seen + batch_size) for module in bn_modules: module.momentum = momentum res = swa_model(*xs) inputs_seen += batch_size for module, momentum in zip(bn_modules, momenta): module.momentum = momentum
[ "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", "compute", "the", "correct", "batch", "norm", "statistics", ".", "Before", "performing", "inference", "with", "the", "SWA", "model", "we", "perform", "a", "single", "pass", "over", "the", "training", "data", "to", "calculate", "an", "accurate", "running", "mean", "and", "variance", "for", "each", "batch", "norm", "layer", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/swa.py#L45-L83
[ "def", "fix_batchnorm", "(", "swa_model", ",", "train_dl", ")", ":", "bn_modules", "=", "[", "]", "swa_model", ".", "apply", "(", "lambda", "module", ":", "collect_bn_modules", "(", "module", ",", "bn_modules", ")", ")", "if", "not", "bn_modules", ":", "return", "swa_model", ".", "train", "(", ")", "for", "module", "in", "bn_modules", ":", "module", ".", "running_mean", "=", "torch", ".", "zeros_like", "(", "module", ".", "running_mean", ")", "module", ".", "running_var", "=", "torch", ".", "ones_like", "(", "module", ".", "running_var", ")", "momenta", "=", "[", "m", ".", "momentum", "for", "m", "in", "bn_modules", "]", "inputs_seen", "=", "0", "for", "(", "*", "x", ",", "y", ")", "in", "iter", "(", "train_dl", ")", ":", "xs", "=", "V", "(", "x", ")", "batch_size", "=", "xs", "[", "0", "]", ".", "size", "(", "0", ")", "momentum", "=", "batch_size", "/", "(", "inputs_seen", "+", "batch_size", ")", "for", "module", "in", "bn_modules", ":", "module", ".", "momentum", "=", "momentum", "res", "=", "swa_model", "(", "*", "xs", ")", "inputs_seen", "+=", "batch_size", "for", "module", ",", "momentum", "in", "zip", "(", "bn_modules", ",", "momenta", ")", ":", "module", ".", "momentum", "=", "momentum" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
repackage_var
Wraps h in new Variables, to detach them from their history.
old/fastai/lm_rnn.py
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): """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)
[ "Wraps", "h", "in", "new", "Variables", "to", "detach", "them", "from", "their", "history", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/lm_rnn.py#L20-L23
[ "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", ")", "else", ":", "return", "Variable", "(", "h", ".", "data", ")", "if", "type", "(", "h", ")", "==", "Variable", "else", "tuple", "(", "repackage_var", "(", "v", ")", "for", "v", "in", "h", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
get_language_model
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 LinearDecoder layer. The SequentialRNN layer is the native torch's Sequential wrapper that puts the RNN_Encoder and LinearDecoder layers sequentially in the model. Args: n_tok (int): number of unique vocabulary words (or tokens) in the source dataset emb_sz (int): the embedding size to use to encode each token n_hid (int): number of hidden activation per LSTM layer n_layers (int): number of LSTM layers to use in the architecture pad_token (int): the int value used for padding text. dropouth (float): dropout to apply to the activations going from one LSTM layer to another dropouti (float): dropout to apply to the input layer. dropoute (float): dropout to apply to the embedding layer. wdrop (float): dropout used for a LSTM's internal (or hidden) recurrent weights. tie_weights (bool): decide if the weights of the embedding matrix in the RNN encoder should be tied to the weights of the LinearDecoder layer. qrnn (bool): decide if the model is composed of LSTMS (False) or QRNNs (True). bias (bool): decide if the decoder should have a bias layer or not. Returns: A SequentialRNN model
old/fastai/lm_rnn.py
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 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 LinearDecoder layer. The SequentialRNN layer is the native torch's Sequential wrapper that puts the RNN_Encoder and LinearDecoder layers sequentially in the model. Args: n_tok (int): number of unique vocabulary words (or tokens) in the source dataset emb_sz (int): the embedding size to use to encode each token n_hid (int): number of hidden activation per LSTM layer n_layers (int): number of LSTM layers to use in the architecture pad_token (int): the int value used for padding text. dropouth (float): dropout to apply to the activations going from one LSTM layer to another dropouti (float): dropout to apply to the input layer. dropoute (float): dropout to apply to the embedding layer. wdrop (float): dropout used for a LSTM's internal (or hidden) recurrent weights. tie_weights (bool): decide if the weights of the embedding matrix in the RNN encoder should be tied to the weights of the LinearDecoder layer. qrnn (bool): decide if the model is composed of LSTMS (False) or QRNNs (True). bias (bool): decide if the decoder should have a bias layer or not. Returns: A SequentialRNN model """ rnn_enc = RNN_Encoder(n_tok, emb_sz, n_hid=n_hid, n_layers=n_layers, pad_token=pad_token, dropouth=dropouth, dropouti=dropouti, dropoute=dropoute, wdrop=wdrop, qrnn=qrnn) enc = rnn_enc.encoder if tie_weights else None return SequentialRNN(rnn_enc, LinearDecoder(n_tok, emb_sz, dropout, tie_encoder=enc, bias=bias))
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 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 LinearDecoder layer. The SequentialRNN layer is the native torch's Sequential wrapper that puts the RNN_Encoder and LinearDecoder layers sequentially in the model. Args: n_tok (int): number of unique vocabulary words (or tokens) in the source dataset emb_sz (int): the embedding size to use to encode each token n_hid (int): number of hidden activation per LSTM layer n_layers (int): number of LSTM layers to use in the architecture pad_token (int): the int value used for padding text. dropouth (float): dropout to apply to the activations going from one LSTM layer to another dropouti (float): dropout to apply to the input layer. dropoute (float): dropout to apply to the embedding layer. wdrop (float): dropout used for a LSTM's internal (or hidden) recurrent weights. tie_weights (bool): decide if the weights of the embedding matrix in the RNN encoder should be tied to the weights of the LinearDecoder layer. qrnn (bool): decide if the model is composed of LSTMS (False) or QRNNs (True). bias (bool): decide if the decoder should have a bias layer or not. Returns: A SequentialRNN model """ rnn_enc = RNN_Encoder(n_tok, emb_sz, n_hid=n_hid, n_layers=n_layers, pad_token=pad_token, dropouth=dropouth, dropouti=dropouti, dropoute=dropoute, wdrop=wdrop, qrnn=qrnn) enc = rnn_enc.encoder if tie_weights else None return SequentialRNN(rnn_enc, LinearDecoder(n_tok, emb_sz, dropout, tie_encoder=enc, bias=bias))
[ "Returns", "a", "SequentialRNN", "model", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/lm_rnn.py#L204-L238
[ "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", ")", ":", "rnn_enc", "=", "RNN_Encoder", "(", "n_tok", ",", "emb_sz", ",", "n_hid", "=", "n_hid", ",", "n_layers", "=", "n_layers", ",", "pad_token", "=", "pad_token", ",", "dropouth", "=", "dropouth", ",", "dropouti", "=", "dropouti", ",", "dropoute", "=", "dropoute", ",", "wdrop", "=", "wdrop", ",", "qrnn", "=", "qrnn", ")", "enc", "=", "rnn_enc", ".", "encoder", "if", "tie_weights", "else", "None", "return", "SequentialRNN", "(", "rnn_enc", ",", "LinearDecoder", "(", "n_tok", ",", "emb_sz", ",", "dropout", ",", "tie_encoder", "=", "enc", ",", "bias", "=", "bias", ")", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
RNN_Encoder.forward
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 of tensors evaluated from each RNN layer using dropouth,
old/fastai/lm_rnn.py
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 without using dropouth, list of tensors evaluated from each RNN layer using dropouth, """ sl,bs = input.size() if bs!=self.bs: self.bs=bs self.reset() with set_grad_enabled(self.training): emb = self.encoder_with_dropout(input, dropout=self.dropoute if self.training else 0) emb = self.dropouti(emb) raw_output = emb new_hidden,raw_outputs,outputs = [],[],[] for l, (rnn,drop) in enumerate(zip(self.rnns, self.dropouths)): current_input = raw_output with warnings.catch_warnings(): warnings.simplefilter("ignore") raw_output, new_h = rnn(raw_output, self.hidden[l]) new_hidden.append(new_h) raw_outputs.append(raw_output) if l != self.n_layers - 1: raw_output = drop(raw_output) outputs.append(raw_output) self.hidden = repackage_var(new_hidden) return raw_outputs, outputs
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 without using dropouth, list of tensors evaluated from each RNN layer using dropouth, """ sl,bs = input.size() if bs!=self.bs: self.bs=bs self.reset() with set_grad_enabled(self.training): emb = self.encoder_with_dropout(input, dropout=self.dropoute if self.training else 0) emb = self.dropouti(emb) raw_output = emb new_hidden,raw_outputs,outputs = [],[],[] for l, (rnn,drop) in enumerate(zip(self.rnns, self.dropouths)): current_input = raw_output with warnings.catch_warnings(): warnings.simplefilter("ignore") raw_output, new_h = rnn(raw_output, self.hidden[l]) new_hidden.append(new_h) raw_outputs.append(raw_output) if l != self.n_layers - 1: raw_output = drop(raw_output) outputs.append(raw_output) self.hidden = repackage_var(new_hidden) return raw_outputs, outputs
[ "Invoked", "during", "the", "forward", "propagation", "of", "the", "RNN_Encoder", "module", ".", "Args", ":", "input", "(", "Tensor", ")", ":", "input", "of", "shape", "(", "sentence", "length", "x", "batch_size", ")" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/lm_rnn.py#L84-L113
[ "def", "forward", "(", "self", ",", "input", ")", ":", "sl", ",", "bs", "=", "input", ".", "size", "(", ")", "if", "bs", "!=", "self", ".", "bs", ":", "self", ".", "bs", "=", "bs", "self", ".", "reset", "(", ")", "with", "set_grad_enabled", "(", "self", ".", "training", ")", ":", "emb", "=", "self", ".", "encoder_with_dropout", "(", "input", ",", "dropout", "=", "self", ".", "dropoute", "if", "self", ".", "training", "else", "0", ")", "emb", "=", "self", ".", "dropouti", "(", "emb", ")", "raw_output", "=", "emb", "new_hidden", ",", "raw_outputs", ",", "outputs", "=", "[", "]", ",", "[", "]", ",", "[", "]", "for", "l", ",", "(", "rnn", ",", "drop", ")", "in", "enumerate", "(", "zip", "(", "self", ".", "rnns", ",", "self", ".", "dropouths", ")", ")", ":", "current_input", "=", "raw_output", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "raw_output", ",", "new_h", "=", "rnn", "(", "raw_output", ",", "self", ".", "hidden", "[", "l", "]", ")", "new_hidden", ".", "append", "(", "new_h", ")", "raw_outputs", ".", "append", "(", "raw_output", ")", "if", "l", "!=", "self", ".", "n_layers", "-", "1", ":", "raw_output", "=", "drop", "(", "raw_output", ")", "outputs", ".", "append", "(", "raw_output", ")", "self", ".", "hidden", "=", "repackage_var", "(", "new_hidden", ")", "return", "raw_outputs", ",", "outputs" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
replace_rep
Replace repetitions at the character level in `t`.
fastai/text/transform.py
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: "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)
[ "Replace", "repetitions", "at", "the", "character", "level", "in", "t", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L42-L48
[ "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} '", "re_rep", "=", "re", ".", "compile", "(", "r'(\\S)(\\1{3,})'", ")", "return", "re_rep", ".", "sub", "(", "_replace_rep", ",", "t", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
replace_wrep
Replace word repetitions in `t`.
fastai/text/transform.py
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: "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)
[ "Replace", "word", "repetitions", "in", "t", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L50-L56
[ "def", "replace_wrep", "(", "t", ":", "str", ")", "->", "str", ":", "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", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
fix_html
List of replacements from html strings in `x`.
fastai/text/transform.py
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('\\"', '"').replace('<unk>',UNK).replace(' @.@ ','.').replace( ' @-@ ','-').replace(' @,@ ',',').replace('\\', ' \\ ') return re1.sub(' ', html.unescape(x))
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('\\"', '"').replace('<unk>',UNK).replace(' @.@ ','.').replace( ' @-@ ','-').replace(' @,@ ',',').replace('\\', ' \\ ') return re1.sub(' ', html.unescape(x))
[ "List", "of", "replacements", "from", "html", "strings", "in", "x", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L58-L65
[ "def", "fix_html", "(", "x", ":", "str", ")", "->", "str", ":", "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", "(", "'\\\\\"'", ",", "'\"'", ")", ".", "replace", "(", "'<unk>'", ",", "UNK", ")", ".", "replace", "(", "' @.@ '", ",", "'.'", ")", ".", "replace", "(", "' @-@ '", ",", "'-'", ")", ".", "replace", "(", "' @,@ '", ",", "','", ")", ".", "replace", "(", "'\\\\'", ",", "' \\\\ '", ")", "return", "re1", ".", "sub", "(", "' '", ",", "html", ".", "unescape", "(", "x", ")", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
replace_all_caps
Replace tokens in ALL CAPS in `x` by their lower version and add `TK_UP` before.
fastai/text/transform.py
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]: "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
[ "Replace", "tokens", "in", "ALL", "CAPS", "in", "x", "by", "their", "lower", "version", "and", "add", "TK_UP", "before", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L67-L73
[ "def", "replace_all_caps", "(", "x", ":", "Collection", "[", "str", "]", ")", "->", "Collection", "[", "str", "]", ":", "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" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
deal_caps
Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before.
fastai/text/transform.py
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()) return res
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()) return res
[ "Replace", "all", "Capitalized", "tokens", "in", "x", "by", "their", "lower", "version", "and", "add", "TK_MAJ", "before", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L75-L82
[ "def", "deal_caps", "(", "x", ":", "Collection", "[", "str", "]", ")", "->", "Collection", "[", "str", "]", ":", "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", "(", ")", ")", "return", "res" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Tokenizer.process_text
Process one text `t` with tokenizer `tok`.
fastai/text/transform.py
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]: "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
[ "Process", "one", "text", "t", "with", "tokenizer", "tok", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L103-L108
[ "def", "process_text", "(", "self", ",", "t", ":", "str", ",", "tok", ":", "BaseTokenizer", ")", "->", "List", "[", "str", "]", ":", "for", "rule", "in", "self", ".", "pre_rules", ":", "t", "=", "rule", "(", "t", ")", "toks", "=", "tok", ".", "tokenizer", "(", "t", ")", "for", "rule", "in", "self", ".", "post_rules", ":", "toks", "=", "rule", "(", "toks", ")", "return", "toks" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Tokenizer._process_all_1
Process a list of `texts` in one process.
fastai/text/transform.py
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]]: "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]
[ "Process", "a", "list", "of", "texts", "in", "one", "process", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L110-L114
[ "def", "_process_all_1", "(", "self", ",", "texts", ":", "Collection", "[", "str", "]", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "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", "]" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Tokenizer.process_all
Process a list of `texts`.
fastai/text/transform.py
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]]: "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)), [])
[ "Process", "a", "list", "of", "texts", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L116-L120
[ "def", "process_all", "(", "self", ",", "texts", ":", "Collection", "[", "str", "]", ")", "->", "List", "[", "List", "[", "str", "]", "]", ":", "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", ")", ")", ",", "[", "]", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Vocab.numericalize
Convert a list of tokens `t` to their ids.
fastai/text/transform.py
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]: "Convert a list of tokens `t` to their ids." return [self.stoi[w] for w in t]
[ "Convert", "a", "list", "of", "tokens", "t", "to", "their", "ids", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L128-L130
[ "def", "numericalize", "(", "self", ",", "t", ":", "Collection", "[", "str", "]", ")", "->", "List", "[", "int", "]", ":", "return", "[", "self", ".", "stoi", "[", "w", "]", "for", "w", "in", "t", "]" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Vocab.textify
Convert a list of `nums` to their tokens.
fastai/text/transform.py
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]: "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]
[ "Convert", "a", "list", "of", "nums", "to", "their", "tokens", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L132-L134
[ "def", "textify", "(", "self", ",", "nums", ":", "Collection", "[", "int", "]", ",", "sep", "=", "' '", ")", "->", "List", "[", "str", "]", ":", "return", "sep", ".", "join", "(", "[", "self", ".", "itos", "[", "i", "]", "for", "i", "in", "nums", "]", ")", "if", "sep", "is", "not", "None", "else", "[", "self", ".", "itos", "[", "i", "]", "for", "i", "in", "nums", "]" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Vocab.create
Create a vocabulary from a set of `tokens`.
fastai/text/transform.py
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 o in itos: itos.remove(o) itos.insert(0, o) return cls(itos)
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 o in itos: itos.remove(o) itos.insert(0, o) return cls(itos)
[ "Create", "a", "vocabulary", "from", "a", "set", "of", "tokens", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L148-L155
[ "def", "create", "(", "cls", ",", "tokens", ":", "Tokens", ",", "max_vocab", ":", "int", ",", "min_freq", ":", "int", ")", "->", "'Vocab'", ":", "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", "o", "in", "itos", ":", "itos", ".", "remove", "(", "o", ")", "itos", ".", "insert", "(", "0", ",", "o", ")", "return", "cls", "(", "itos", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Vocab.load
Load the `Vocab` contained in `path`
fastai/text/transform.py
def load(cls, path): "Load the `Vocab` contained in `path`" itos = pickle.load(open(path, 'rb')) return cls(itos)
def load(cls, path): "Load the `Vocab` contained in `path`" itos = pickle.load(open(path, 'rb')) return cls(itos)
[ "Load", "the", "Vocab", "contained", "in", "path" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/transform.py#L158-L161
[ "def", "load", "(", "cls", ",", "path", ")", ":", "itos", "=", "pickle", ".", "load", "(", "open", "(", "path", ",", "'rb'", ")", ")", "return", "cls", "(", "itos", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LossRecorder.plot_loss
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.
old/fastai/sgdr.py
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.switch_backend('agg') plt.plot(self.iterations[n_skip:-n_skip_end], self.losses[n_skip:-n_skip_end]) if not in_ipynb(): plt.savefig(os.path.join(self.save_path, 'loss_plot.png')) np.save(os.path.join(self.save_path, 'losses.npy'), self.losses[10:])
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.switch_backend('agg') plt.plot(self.iterations[n_skip:-n_skip_end], self.losses[n_skip:-n_skip_end]) if not in_ipynb(): plt.savefig(os.path.join(self.save_path, 'loss_plot.png')) np.save(os.path.join(self.save_path, 'losses.npy'), self.losses[10:])
[ "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", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/sgdr.py#L100-L109
[ "def", "plot_loss", "(", "self", ",", "n_skip", "=", "10", ",", "n_skip_end", "=", "5", ")", ":", "if", "not", "in_ipynb", "(", ")", ":", "plt", ".", "switch_backend", "(", "'agg'", ")", "plt", ".", "plot", "(", "self", ".", "iterations", "[", "n_skip", ":", "-", "n_skip_end", "]", ",", "self", ".", "losses", "[", "n_skip", ":", "-", "n_skip_end", "]", ")", "if", "not", "in_ipynb", "(", ")", ":", "plt", ".", "savefig", "(", "os", ".", "path", ".", "join", "(", "self", ".", "save_path", ",", "'loss_plot.png'", ")", ")", "np", ".", "save", "(", "os", ".", "path", ".", "join", "(", "self", ".", "save_path", ",", "'losses.npy'", ")", ",", "self", ".", "losses", "[", "10", ":", "]", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LossRecorder.plot_lr
Plots learning rate in jupyter notebook or console, depending on the enviroment of the learner.
old/fastai/sgdr.py
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].set_xlabel('iterations') axs[0].set_ylabel('learning rate') axs[1].set_ylabel('momentum') axs[0].plot(self.iterations,self.lrs) axs[1].plot(self.iterations,self.momentums) else: plt.xlabel("iterations") plt.ylabel("learning rate") plt.plot(self.iterations, self.lrs) if not in_ipynb(): plt.savefig(os.path.join(self.save_path, 'lr_plot.png'))
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].set_xlabel('iterations') axs[0].set_ylabel('learning rate') axs[1].set_ylabel('momentum') axs[0].plot(self.iterations,self.lrs) axs[1].plot(self.iterations,self.momentums) else: plt.xlabel("iterations") plt.ylabel("learning rate") plt.plot(self.iterations, self.lrs) if not in_ipynb(): plt.savefig(os.path.join(self.save_path, 'lr_plot.png'))
[ "Plots", "learning", "rate", "in", "jupyter", "notebook", "or", "console", "depending", "on", "the", "enviroment", "of", "the", "learner", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/sgdr.py#L111-L127
[ "def", "plot_lr", "(", "self", ")", ":", "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", "]", ".", "set_xlabel", "(", "'iterations'", ")", "axs", "[", "0", "]", ".", "set_ylabel", "(", "'learning rate'", ")", "axs", "[", "1", "]", ".", "set_ylabel", "(", "'momentum'", ")", "axs", "[", "0", "]", ".", "plot", "(", "self", ".", "iterations", ",", "self", ".", "lrs", ")", "axs", "[", "1", "]", ".", "plot", "(", "self", ".", "iterations", ",", "self", ".", "momentums", ")", "else", ":", "plt", ".", "xlabel", "(", "\"iterations\"", ")", "plt", ".", "ylabel", "(", "\"learning rate\"", ")", "plt", ".", "plot", "(", "self", ".", "iterations", ",", "self", ".", "lrs", ")", "if", "not", "in_ipynb", "(", ")", ":", "plt", ".", "savefig", "(", "os", ".", "path", ".", "join", "(", "self", ".", "save_path", ",", "'lr_plot.png'", ")", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LR_Finder.plot
Plots the loss function with respect to learning rate, in log scale.
old/fastai/sgdr.py
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)]) plt.xscale('log')
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)]) plt.xscale('log')
[ "Plots", "the", "loss", "function", "with", "respect", "to", "learning", "rate", "in", "log", "scale", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/sgdr.py#L190-L197
[ "def", "plot", "(", "self", ",", "n_skip", "=", "10", ",", "n_skip_end", "=", "5", ")", ":", "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", ")", "]", ")", "plt", ".", "xscale", "(", "'log'", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
OptimScheduler.plot_lr
Plots the lr rate/momentum schedule
old/fastai/sgdr.py
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_backend('agg') np_plts = 2 if show_moms else 1 fig, axs = plt.subplots(1,np_plts,figsize=(6*np_plts,4)) if not show_moms: axs = [axs] for i in range(np_plts): axs[i].set_xlabel('iterations') axs[0].set_ylabel('learning rate') axs[0].plot(self.iterations,self.lrs) if show_moms: axs[1].set_ylabel('momentum') axs[1].plot(self.iterations,self.momentums) if show_text: for i, phase in enumerate(self.phases): text = phase.opt_fn.__name__ if phase.wds is not None: text+='\nwds='+str(phase.wds) if phase.beta is not None: text+='\nbeta='+str(phase.beta) for k in range(np_plts): if i < len(self.phases)-1: draw_line(axs[k], phase_limits[i+1]) draw_text(axs[k], (phase_limits[i]+phase_limits[i+1])/2, text) if not in_ipynb(): plt.savefig(os.path.join(self.save_path, 'lr_plot.png'))
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_backend('agg') np_plts = 2 if show_moms else 1 fig, axs = plt.subplots(1,np_plts,figsize=(6*np_plts,4)) if not show_moms: axs = [axs] for i in range(np_plts): axs[i].set_xlabel('iterations') axs[0].set_ylabel('learning rate') axs[0].plot(self.iterations,self.lrs) if show_moms: axs[1].set_ylabel('momentum') axs[1].plot(self.iterations,self.momentums) if show_text: for i, phase in enumerate(self.phases): text = phase.opt_fn.__name__ if phase.wds is not None: text+='\nwds='+str(phase.wds) if phase.beta is not None: text+='\nbeta='+str(phase.beta) for k in range(np_plts): if i < len(self.phases)-1: draw_line(axs[k], phase_limits[i+1]) draw_text(axs[k], (phase_limits[i]+phase_limits[i+1])/2, text) if not in_ipynb(): plt.savefig(os.path.join(self.save_path, 'lr_plot.png'))
[ "Plots", "the", "lr", "rate", "/", "momentum", "schedule" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/sgdr.py#L557-L583
[ "def", "plot_lr", "(", "self", ",", "show_text", "=", "True", ",", "show_moms", "=", "True", ")", ":", "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_backend", "(", "'agg'", ")", "np_plts", "=", "2", "if", "show_moms", "else", "1", "fig", ",", "axs", "=", "plt", ".", "subplots", "(", "1", ",", "np_plts", ",", "figsize", "=", "(", "6", "*", "np_plts", ",", "4", ")", ")", "if", "not", "show_moms", ":", "axs", "=", "[", "axs", "]", "for", "i", "in", "range", "(", "np_plts", ")", ":", "axs", "[", "i", "]", ".", "set_xlabel", "(", "'iterations'", ")", "axs", "[", "0", "]", ".", "set_ylabel", "(", "'learning rate'", ")", "axs", "[", "0", "]", ".", "plot", "(", "self", ".", "iterations", ",", "self", ".", "lrs", ")", "if", "show_moms", ":", "axs", "[", "1", "]", ".", "set_ylabel", "(", "'momentum'", ")", "axs", "[", "1", "]", ".", "plot", "(", "self", ".", "iterations", ",", "self", ".", "momentums", ")", "if", "show_text", ":", "for", "i", ",", "phase", "in", "enumerate", "(", "self", ".", "phases", ")", ":", "text", "=", "phase", ".", "opt_fn", ".", "__name__", "if", "phase", ".", "wds", "is", "not", "None", ":", "text", "+=", "'\\nwds='", "+", "str", "(", "phase", ".", "wds", ")", "if", "phase", ".", "beta", "is", "not", "None", ":", "text", "+=", "'\\nbeta='", "+", "str", "(", "phase", ".", "beta", ")", "for", "k", "in", "range", "(", "np_plts", ")", ":", "if", "i", "<", "len", "(", "self", ".", "phases", ")", "-", "1", ":", "draw_line", "(", "axs", "[", "k", "]", ",", "phase_limits", "[", "i", "+", "1", "]", ")", "draw_text", "(", "axs", "[", "k", "]", ",", "(", "phase_limits", "[", "i", "]", "+", "phase_limits", "[", "i", "+", "1", "]", ")", "/", "2", ",", "text", ")", "if", "not", "in_ipynb", "(", ")", ":", "plt", ".", "savefig", "(", "os", ".", "path", ".", "join", "(", "self", ".", "save_path", ",", "'lr_plot.png'", ")", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
main
Distributed training of Imagenette.
examples/train_imagenette.py
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, eps: Param("epsilon", float)=1e-6, epochs: Param("Number of epochs", int)=5, bs: Param("Batch size", int)=256, mixup: Param("Mixup", float)=0., opt: Param("Optimizer (adam,rms,sgd)", str)='adam', arch: Param("Architecture (xresnet34, xresnet50, presnet34, presnet50)", str)='xresnet50', dump: Param("Print model; don't train", int)=0, ): "Distributed training of Imagenette." gpu = setup_distrib(gpu) if gpu is None: bs *= torch.cuda.device_count() if opt=='adam' : opt_func = partial(optim.Adam, betas=(mom,alpha), eps=eps) elif opt=='rms' : opt_func = partial(optim.RMSprop, alpha=alpha, eps=eps) elif opt=='sgd' : opt_func = partial(optim.SGD, momentum=mom) data = get_data(size, woof, bs) bs_rat = bs/256 if gpu is not None: bs_rat *= num_distrib() if not gpu: print(f'lr: {lr}; eff_lr: {lr*bs_rat}; size: {size}; alpha: {alpha}; mom: {mom}; eps: {eps}') lr *= bs_rat m = globals()[arch] learn = (Learner(data, m(c_out=10), wd=1e-2, opt_func=opt_func, metrics=[accuracy,top_k_accuracy], bn_wd=False, true_wd=True, loss_func = LabelSmoothingCrossEntropy()) ) if dump: print(learn.model); exit() if mixup: learn = learn.mixup(alpha=mixup) learn = learn.to_fp16(dynamic=True) if gpu is None: learn.to_parallel() elif num_distrib()>1: learn.to_distributed(gpu) # Requires `-m fastai.launch` learn.fit_one_cycle(epochs, lr, div_factor=10, pct_start=0.3)
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, eps: Param("epsilon", float)=1e-6, epochs: Param("Number of epochs", int)=5, bs: Param("Batch size", int)=256, mixup: Param("Mixup", float)=0., opt: Param("Optimizer (adam,rms,sgd)", str)='adam', arch: Param("Architecture (xresnet34, xresnet50, presnet34, presnet50)", str)='xresnet50', dump: Param("Print model; don't train", int)=0, ): "Distributed training of Imagenette." gpu = setup_distrib(gpu) if gpu is None: bs *= torch.cuda.device_count() if opt=='adam' : opt_func = partial(optim.Adam, betas=(mom,alpha), eps=eps) elif opt=='rms' : opt_func = partial(optim.RMSprop, alpha=alpha, eps=eps) elif opt=='sgd' : opt_func = partial(optim.SGD, momentum=mom) data = get_data(size, woof, bs) bs_rat = bs/256 if gpu is not None: bs_rat *= num_distrib() if not gpu: print(f'lr: {lr}; eff_lr: {lr*bs_rat}; size: {size}; alpha: {alpha}; mom: {mom}; eps: {eps}') lr *= bs_rat m = globals()[arch] learn = (Learner(data, m(c_out=10), wd=1e-2, opt_func=opt_func, metrics=[accuracy,top_k_accuracy], bn_wd=False, true_wd=True, loss_func = LabelSmoothingCrossEntropy()) ) if dump: print(learn.model); exit() if mixup: learn = learn.mixup(alpha=mixup) learn = learn.to_fp16(dynamic=True) if gpu is None: learn.to_parallel() elif num_distrib()>1: learn.to_distributed(gpu) # Requires `-m fastai.launch` learn.fit_one_cycle(epochs, lr, div_factor=10, pct_start=0.3)
[ "Distributed", "training", "of", "Imagenette", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/examples/train_imagenette.py#L30-L71
[ "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", ",", "eps", ":", "Param", "(", "\"epsilon\"", ",", "float", ")", "=", "1e-6", ",", "epochs", ":", "Param", "(", "\"Number of epochs\"", ",", "int", ")", "=", "5", ",", "bs", ":", "Param", "(", "\"Batch size\"", ",", "int", ")", "=", "256", ",", "mixup", ":", "Param", "(", "\"Mixup\"", ",", "float", ")", "=", "0.", ",", "opt", ":", "Param", "(", "\"Optimizer (adam,rms,sgd)\"", ",", "str", ")", "=", "'adam'", ",", "arch", ":", "Param", "(", "\"Architecture (xresnet34, xresnet50, presnet34, presnet50)\"", ",", "str", ")", "=", "'xresnet50'", ",", "dump", ":", "Param", "(", "\"Print model; don't train\"", ",", "int", ")", "=", "0", ",", ")", ":", "gpu", "=", "setup_distrib", "(", "gpu", ")", "if", "gpu", "is", "None", ":", "bs", "*=", "torch", ".", "cuda", ".", "device_count", "(", ")", "if", "opt", "==", "'adam'", ":", "opt_func", "=", "partial", "(", "optim", ".", "Adam", ",", "betas", "=", "(", "mom", ",", "alpha", ")", ",", "eps", "=", "eps", ")", "elif", "opt", "==", "'rms'", ":", "opt_func", "=", "partial", "(", "optim", ".", "RMSprop", ",", "alpha", "=", "alpha", ",", "eps", "=", "eps", ")", "elif", "opt", "==", "'sgd'", ":", "opt_func", "=", "partial", "(", "optim", ".", "SGD", ",", "momentum", "=", "mom", ")", "data", "=", "get_data", "(", "size", ",", "woof", ",", "bs", ")", "bs_rat", "=", "bs", "/", "256", "if", "gpu", "is", "not", "None", ":", "bs_rat", "*=", "num_distrib", "(", ")", "if", "not", "gpu", ":", "print", "(", "f'lr: {lr}; eff_lr: {lr*bs_rat}; size: {size}; alpha: {alpha}; mom: {mom}; eps: {eps}'", ")", "lr", "*=", "bs_rat", "m", "=", "globals", "(", ")", "[", "arch", "]", "learn", "=", "(", "Learner", "(", "data", ",", "m", "(", "c_out", "=", "10", ")", ",", "wd", "=", "1e-2", ",", "opt_func", "=", "opt_func", ",", "metrics", "=", "[", "accuracy", ",", "top_k_accuracy", "]", ",", "bn_wd", "=", "False", ",", "true_wd", "=", "True", ",", "loss_func", "=", "LabelSmoothingCrossEntropy", "(", ")", ")", ")", "if", "dump", ":", "print", "(", "learn", ".", "model", ")", "exit", "(", ")", "if", "mixup", ":", "learn", "=", "learn", ".", "mixup", "(", "alpha", "=", "mixup", ")", "learn", "=", "learn", ".", "to_fp16", "(", "dynamic", "=", "True", ")", "if", "gpu", "is", "None", ":", "learn", ".", "to_parallel", "(", ")", "elif", "num_distrib", "(", ")", ">", "1", ":", "learn", ".", "to_distributed", "(", "gpu", ")", "# Requires `-m fastai.launch`", "learn", ".", "fit_one_cycle", "(", "epochs", ",", "lr", ",", "div_factor", "=", "10", ",", "pct_start", "=", "0.3", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TerminateOnNaNCallback.on_batch_end
Test if `last_loss` is NaN and interrupts training.
fastai/callbacks/tracker.py
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 loss, terminating training.') return {'stop_epoch': True, 'stop_training': True, 'skip_validate': True}
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 loss, terminating training.') return {'stop_epoch': True, 'stop_training': True, 'skip_validate': True}
[ "Test", "if", "last_loss", "is", "NaN", "and", "interrupts", "training", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L16-L21
[ "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", "torch", ".", "isnan", "(", "last_loss", ")", ":", "print", "(", "f'Epoch/Batch ({epoch}/{num_batch}): Invalid loss, terminating training.'", ")", "return", "{", "'stop_epoch'", ":", "True", ",", "'stop_training'", ":", "True", ",", "'skip_validate'", ":", "True", "}" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TrackerCallback.on_train_begin
Initializes the best value.
fastai/callbacks/tracker.py
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: "Initializes the best value." self.best = float('inf') if self.operator == np.less else -float('inf')
[ "Initializes", "the", "best", "value", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L35-L37
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "best", "=", "float", "(", "'inf'", ")", "if", "self", ".", "operator", "==", "np", ".", "less", "else", "-", "float", "(", "'inf'", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TrackerCallback.get_monitor_value
Pick the monitored value.
fastai/callbacks/tracker.py
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(), 'valid_loss':self.learn.recorder.val_losses[-1]} if values['valid_loss'] is None: return if self.learn.recorder.metrics: for m, n in zip(self.learn.recorder.metrics[-1],self.learn.recorder.names[3:-1]): values[n] = m if values.get(self.monitor) is None: warn(f'{self.__class__} conditioned on metric `{self.monitor}` which is not available. Available metrics are: {", ".join(map(str, self.learn.recorder.names[1:-1]))}') return values.get(self.monitor)
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(), 'valid_loss':self.learn.recorder.val_losses[-1]} if values['valid_loss'] is None: return if self.learn.recorder.metrics: for m, n in zip(self.learn.recorder.metrics[-1],self.learn.recorder.names[3:-1]): values[n] = m if values.get(self.monitor) is None: warn(f'{self.__class__} conditioned on metric `{self.monitor}` which is not available. Available metrics are: {", ".join(map(str, self.learn.recorder.names[1:-1]))}') return values.get(self.monitor)
[ "Pick", "the", "monitored", "value", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L39-L51
[ "def", "get_monitor_value", "(", "self", ")", ":", "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", "(", ")", ",", "'valid_loss'", ":", "self", ".", "learn", ".", "recorder", ".", "val_losses", "[", "-", "1", "]", "}", "if", "values", "[", "'valid_loss'", "]", "is", "None", ":", "return", "if", "self", ".", "learn", ".", "recorder", ".", "metrics", ":", "for", "m", ",", "n", "in", "zip", "(", "self", ".", "learn", ".", "recorder", ".", "metrics", "[", "-", "1", "]", ",", "self", ".", "learn", ".", "recorder", ".", "names", "[", "3", ":", "-", "1", "]", ")", ":", "values", "[", "n", "]", "=", "m", "if", "values", ".", "get", "(", "self", ".", "monitor", ")", "is", "None", ":", "warn", "(", "f'{self.__class__} conditioned on metric `{self.monitor}` which is not available. Available metrics are: {\", \".join(map(str, self.learn.recorder.names[1:-1]))}'", ")", "return", "values", ".", "get", "(", "self", ".", "monitor", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
SaveModelCallback.on_epoch_end
Compare the value monitored to its best score and maybe save the model.
fastai/callbacks/tracker.py
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 None and self.operator(current, self.best): print(f'Better model found at epoch {epoch} with {self.monitor} value: {current}.') self.best = current self.learn.save(f'{self.name}')
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 None and self.operator(current, self.best): print(f'Better model found at epoch {epoch} with {self.monitor} value: {current}.') self.best = current self.learn.save(f'{self.name}')
[ "Compare", "the", "value", "monitored", "to", "its", "best", "score", "and", "maybe", "save", "the", "model", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L93-L101
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ":", "int", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "every", "==", "\"epoch\"", ":", "self", ".", "learn", ".", "save", "(", "f'{self.name}_{epoch}'", ")", "else", ":", "#every=\"improvement\"", "current", "=", "self", ".", "get_monitor_value", "(", ")", "if", "current", "is", "not", "None", "and", "self", ".", "operator", "(", "current", ",", "self", ".", "best", ")", ":", "print", "(", "f'Better model found at epoch {epoch} with {self.monitor} value: {current}.'", ")", "self", ".", "best", "=", "current", "self", ".", "learn", ".", "save", "(", "f'{self.name}'", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
SaveModelCallback.on_train_end
Load the best model.
fastai/callbacks/tracker.py
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): "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)
[ "Load", "the", "best", "model", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L103-L106
[ "def", "on_train_end", "(", "self", ",", "*", "*", "kwargs", ")", ":", "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", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ReduceLROnPlateauCallback.on_train_begin
Initialize inner arguments.
fastai/callbacks/tracker.py
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: "Initialize inner arguments." self.wait, self.opt = 0, self.learn.opt super().on_train_begin(**kwargs)
[ "Initialize", "inner", "arguments", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L116-L119
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "wait", ",", "self", ".", "opt", "=", "0", ",", "self", ".", "learn", ".", "opt", "super", "(", ")", ".", "on_train_begin", "(", "*", "*", "kwargs", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ReduceLROnPlateauCallback.on_epoch_end
Compare the value monitored to its best and maybe reduce lr.
fastai/callbacks/tracker.py
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: self.wait += 1 if self.wait > self.patience: self.opt.lr *= self.factor self.wait = 0 print(f'Epoch {epoch}: reducing lr to {self.opt.lr}')
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: self.wait += 1 if self.wait > self.patience: self.opt.lr *= self.factor self.wait = 0 print(f'Epoch {epoch}: reducing lr to {self.opt.lr}')
[ "Compare", "the", "value", "monitored", "to", "its", "best", "and", "maybe", "reduce", "lr", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tracker.py#L121-L131
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "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", ":", "self", ".", "wait", "+=", "1", "if", "self", ".", "wait", ">", "self", ".", "patience", ":", "self", ".", "opt", ".", "lr", "*=", "self", ".", "factor", "self", ".", "wait", "=", "0", "print", "(", "f'Epoch {epoch}: reducing lr to {self.opt.lr}'", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
convert_nb
Convert a notebook `fname` to html file in `dest_path`.
fastai/gen_doc/convert2html.py
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_state_elem(nb['cells']) fname = Path(fname).absolute() dest_name = fname.with_suffix('.html').name meta = nb['metadata'] meta_jekyll = meta['jekyll'] if 'jekyll' in meta else {'title': fname.with_suffix('').name} meta_jekyll['nb_path'] = f'{fname.parent.name}/{fname.name}' with open(f'{dest_path}/{dest_name}','w') as f: f.write(exporter.from_notebook_node(nb, resources=meta_jekyll)[0])
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_state_elem(nb['cells']) fname = Path(fname).absolute() dest_name = fname.with_suffix('.html').name meta = nb['metadata'] meta_jekyll = meta['jekyll'] if 'jekyll' in meta else {'title': fname.with_suffix('').name} meta_jekyll['nb_path'] = f'{fname.parent.name}/{fname.name}' with open(f'{dest_path}/{dest_name}','w') as f: f.write(exporter.from_notebook_node(nb, resources=meta_jekyll)[0])
[ "Convert", "a", "notebook", "fname", "to", "html", "file", "in", "dest_path", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/convert2html.py#L21-L33
[ "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'", "]", "=", "remove_undoc_cells", "(", "nb", "[", "'cells'", "]", ")", "nb", "[", "'cells'", "]", "=", "remove_code_cell_jupyter_widget_state_elem", "(", "nb", "[", "'cells'", "]", ")", "fname", "=", "Path", "(", "fname", ")", ".", "absolute", "(", ")", "dest_name", "=", "fname", ".", "with_suffix", "(", "'.html'", ")", ".", "name", "meta", "=", "nb", "[", "'metadata'", "]", "meta_jekyll", "=", "meta", "[", "'jekyll'", "]", "if", "'jekyll'", "in", "meta", "else", "{", "'title'", ":", "fname", ".", "with_suffix", "(", "''", ")", ".", "name", "}", "meta_jekyll", "[", "'nb_path'", "]", "=", "f'{fname.parent.name}/{fname.name}'", "with", "open", "(", "f'{dest_path}/{dest_name}'", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "exporter", ".", "from_notebook_node", "(", "nb", ",", "resources", "=", "meta_jekyll", ")", "[", "0", "]", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
convert_all
Convert modified notebooks in `folder` to html pages in `dest_path`.
fastai/gen_doc/convert2html.py
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').name if not force_all and fname_out.exists(): in_mod = os.path.getmtime(fname) out_mod = os.path.getmtime(fname_out) if in_mod < out_mod: continue print(f"converting: {fname} => {fname_out}") changed_cnt += 1 convert_nb(fname, dest_path=dest_path) if not changed_cnt: print("No notebooks were modified")
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').name if not force_all and fname_out.exists(): in_mod = os.path.getmtime(fname) out_mod = os.path.getmtime(fname_out) if in_mod < out_mod: continue print(f"converting: {fname} => {fname_out}") changed_cnt += 1 convert_nb(fname, dest_path=dest_path) if not changed_cnt: print("No notebooks were modified")
[ "Convert", "modified", "notebooks", "in", "folder", "to", "html", "pages", "in", "dest_path", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/gen_doc/convert2html.py#L35-L51
[ "def", "convert_all", "(", "folder", ",", "dest_path", "=", "'.'", ",", "force_all", "=", "False", ")", ":", "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'", ")", ".", "name", "if", "not", "force_all", "and", "fname_out", ".", "exists", "(", ")", ":", "in_mod", "=", "os", ".", "path", ".", "getmtime", "(", "fname", ")", "out_mod", "=", "os", ".", "path", ".", "getmtime", "(", "fname_out", ")", "if", "in_mod", "<", "out_mod", ":", "continue", "print", "(", "f\"converting: {fname} => {fname_out}\"", ")", "changed_cnt", "+=", "1", "convert_nb", "(", "fname", ",", "dest_path", "=", "dest_path", ")", "if", "not", "changed_cnt", ":", "print", "(", "\"No notebooks were modified\"", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
pad_collate
Function that collect samples and adds padding. Flips token order if needed
fastai/text/data.py
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(samples), max_len).long() + pad_idx if backwards: pad_first = not pad_first for i,s in enumerate(samples): if pad_first: res[i,-len(s[0]):] = LongTensor(s[0]) else: res[i,:len(s[0]):] = LongTensor(s[0]) if backwards: res = res.flip(1) return res, tensor(np.array([s[1] for s in samples]))
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(samples), max_len).long() + pad_idx if backwards: pad_first = not pad_first for i,s in enumerate(samples): if pad_first: res[i,-len(s[0]):] = LongTensor(s[0]) else: res[i,:len(s[0]):] = LongTensor(s[0]) if backwards: res = res.flip(1) return res, tensor(np.array([s[1] for s in samples]))
[ "Function", "that", "collect", "samples", "and", "adds", "padding", ".", "Flips", "token", "order", "if", "needed" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L128-L138
[ "def", "pad_collate", "(", "samples", ":", "BatchSamples", ",", "pad_idx", ":", "int", "=", "1", ",", "pad_first", ":", "bool", "=", "True", ",", "backwards", ":", "bool", "=", "False", ")", "->", "Tuple", "[", "LongTensor", ",", "LongTensor", "]", ":", "samples", "=", "to_data", "(", "samples", ")", "max_len", "=", "max", "(", "[", "len", "(", "s", "[", "0", "]", ")", "for", "s", "in", "samples", "]", ")", "res", "=", "torch", ".", "zeros", "(", "len", "(", "samples", ")", ",", "max_len", ")", ".", "long", "(", ")", "+", "pad_idx", "if", "backwards", ":", "pad_first", "=", "not", "pad_first", "for", "i", ",", "s", "in", "enumerate", "(", "samples", ")", ":", "if", "pad_first", ":", "res", "[", "i", ",", "-", "len", "(", "s", "[", "0", "]", ")", ":", "]", "=", "LongTensor", "(", "s", "[", "0", "]", ")", "else", ":", "res", "[", "i", ",", ":", "len", "(", "s", "[", "0", "]", ")", ":", "]", "=", "LongTensor", "(", "s", "[", "0", "]", ")", "if", "backwards", ":", "res", "=", "res", ".", "flip", "(", "1", ")", "return", "res", ",", "tensor", "(", "np", ".", "array", "(", "[", "s", "[", "1", "]", "for", "s", "in", "samples", "]", ")", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
open_text
Read the text in `fn`.
fastai/text/data.py
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'): "Read the text in `fn`." with open(fn,'r', encoding = enc) as f: return ''.join(f.readlines())
[ "Read", "the", "text", "in", "fn", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L272-L274
[ "def", "open_text", "(", "fn", ":", "PathOrStr", ",", "enc", "=", "'utf-8'", ")", ":", "with", "open", "(", "fn", ",", "'r'", ",", "encoding", "=", "enc", ")", "as", "f", ":", "return", "''", ".", "join", "(", "f", ".", "readlines", "(", ")", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LanguageModelPreLoader.allocate_buffers
Create the ragged array that will be filled when we ask for items.
fastai/text/data.py
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.int64) self.batch_x, self.batch_y = self.batch[:,0:self.bptt], self.batch[:,1:self.bptt+1] #ro: index of the text we're at inside our datasets for the various batches self.ro = np.zeros(self.bs, dtype=np.int64) #ri: index of the token we're at inside our current text for the various batches self.ri = np.zeros(self.bs, dtype=np.int)
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.int64) self.batch_x, self.batch_y = self.batch[:,0:self.bptt], self.batch[:,1:self.bptt+1] #ro: index of the text we're at inside our datasets for the various batches self.ro = np.zeros(self.bs, dtype=np.int64) #ri: index of the token we're at inside our current text for the various batches self.ri = np.zeros(self.bs, dtype=np.int)
[ "Create", "the", "ragged", "array", "that", "will", "be", "filled", "when", "we", "ask", "for", "items", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L42-L51
[ "def", "allocate_buffers", "(", "self", ")", ":", "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", ".", "int64", ")", "self", ".", "batch_x", ",", "self", ".", "batch_y", "=", "self", ".", "batch", "[", ":", ",", "0", ":", "self", ".", "bptt", "]", ",", "self", ".", "batch", "[", ":", ",", "1", ":", "self", ".", "bptt", "+", "1", "]", "#ro: index of the text we're at inside our datasets for the various batches", "self", ".", "ro", "=", "np", ".", "zeros", "(", "self", ".", "bs", ",", "dtype", "=", "np", ".", "int64", ")", "#ri: index of the token we're at inside our current text for the various batches", "self", ".", "ri", "=", "np", ".", "zeros", "(", "self", ".", "bs", ",", "dtype", "=", "np", ".", "int", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LanguageModelPreLoader.fill_row
Fill the row with tokens from the ragged array. --OBS-- overlap != 1 has not been implemented
fastai/text/data.py
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[ix] if forward: ri = 0 if ibuf else ri n = min(lengths[ix] - ri, row.size - ibuf) row[ibuf:ibuf+n] = rag[ri:ri+n] else: ri = lengths[ix] if ibuf else ri n = min(ri, row.size - ibuf) row[ibuf:ibuf+n] = rag[ri-n:ri][::-1] ibuf += n return ro, ri + ((n-overlap) if forward else -(n-overlap))
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[ix] if forward: ri = 0 if ibuf else ri n = min(lengths[ix] - ri, row.size - ibuf) row[ibuf:ibuf+n] = rag[ri:ri+n] else: ri = lengths[ix] if ibuf else ri n = min(ri, row.size - ibuf) row[ibuf:ibuf+n] = rag[ri-n:ri][::-1] ibuf += n return ro, ri + ((n-overlap) if forward else -(n-overlap))
[ "Fill", "the", "row", "with", "tokens", "from", "the", "ragged", "array", ".", "--", "OBS", "--", "overlap", "!", "=", "1", "has", "not", "been", "implemented" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L80-L97
[ "def", "fill_row", "(", "self", ",", "forward", ",", "items", ",", "idx", ",", "row", ",", "ro", ",", "ri", ",", "overlap", ",", "lengths", ")", ":", "ibuf", "=", "n", "=", "0", "ro", "-=", "1", "while", "ibuf", "<", "row", ".", "size", ":", "ro", "+=", "1", "ix", "=", "idx", "[", "ro", "]", "rag", "=", "items", "[", "ix", "]", "if", "forward", ":", "ri", "=", "0", "if", "ibuf", "else", "ri", "n", "=", "min", "(", "lengths", "[", "ix", "]", "-", "ri", ",", "row", ".", "size", "-", "ibuf", ")", "row", "[", "ibuf", ":", "ibuf", "+", "n", "]", "=", "rag", "[", "ri", ":", "ri", "+", "n", "]", "else", ":", "ri", "=", "lengths", "[", "ix", "]", "if", "ibuf", "else", "ri", "n", "=", "min", "(", "ri", ",", "row", ".", "size", "-", "ibuf", ")", "row", "[", "ibuf", ":", "ibuf", "+", "n", "]", "=", "rag", "[", "ri", "-", "n", ":", "ri", "]", "[", ":", ":", "-", "1", "]", "ibuf", "+=", "n", "return", "ro", ",", "ri", "+", "(", "(", "n", "-", "overlap", ")", "if", "forward", "else", "-", "(", "n", "-", "overlap", ")", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TextDataBunch.from_ids
Create a `TextDataBunch` from ids, labels and a `vocab`. `kwargs` are passed to the dataloader creation.
fastai/text/data.py
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]=None, processor:PreProcessor=None, **kwargs) -> DataBunch: "Create a `TextDataBunch` from ids, labels and a `vocab`. `kwargs` are passed to the dataloader creation." src = ItemLists(path, TextList(train_ids, vocab, path=path, processor=[]), TextList(valid_ids, vocab, path=path, processor=[])) src = src.label_for_lm() if cls==TextLMDataBunch else src.label_from_lists(train_lbls, valid_lbls, classes=classes, processor=[]) if not is1d(train_lbls): src.train.y.one_hot,src.valid.y.one_hot = True,True if test_ids is not None: src.add_test(TextList(test_ids, vocab, path=path), label=train_lbls[0]) src.valid.x.processor = ifnone(processor, [TokenizeProcessor(), NumericalizeProcessor(vocab=vocab)]) return src.databunch(**kwargs)
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]=None, processor:PreProcessor=None, **kwargs) -> DataBunch: "Create a `TextDataBunch` from ids, labels and a `vocab`. `kwargs` are passed to the dataloader creation." src = ItemLists(path, TextList(train_ids, vocab, path=path, processor=[]), TextList(valid_ids, vocab, path=path, processor=[])) src = src.label_for_lm() if cls==TextLMDataBunch else src.label_from_lists(train_lbls, valid_lbls, classes=classes, processor=[]) if not is1d(train_lbls): src.train.y.one_hot,src.valid.y.one_hot = True,True if test_ids is not None: src.add_test(TextList(test_ids, vocab, path=path), label=train_lbls[0]) src.valid.x.processor = ifnone(processor, [TokenizeProcessor(), NumericalizeProcessor(vocab=vocab)]) return src.databunch(**kwargs)
[ "Create", "a", "TextDataBunch", "from", "ids", "labels", "and", "a", "vocab", ".", "kwargs", "are", "passed", "to", "the", "dataloader", "creation", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L150-L161
[ "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", "]", "=", "None", ",", "processor", ":", "PreProcessor", "=", "None", ",", "*", "*", "kwargs", ")", "->", "DataBunch", ":", "src", "=", "ItemLists", "(", "path", ",", "TextList", "(", "train_ids", ",", "vocab", ",", "path", "=", "path", ",", "processor", "=", "[", "]", ")", ",", "TextList", "(", "valid_ids", ",", "vocab", ",", "path", "=", "path", ",", "processor", "=", "[", "]", ")", ")", "src", "=", "src", ".", "label_for_lm", "(", ")", "if", "cls", "==", "TextLMDataBunch", "else", "src", ".", "label_from_lists", "(", "train_lbls", ",", "valid_lbls", ",", "classes", "=", "classes", ",", "processor", "=", "[", "]", ")", "if", "not", "is1d", "(", "train_lbls", ")", ":", "src", ".", "train", ".", "y", ".", "one_hot", ",", "src", ".", "valid", ".", "y", ".", "one_hot", "=", "True", ",", "True", "if", "test_ids", "is", "not", "None", ":", "src", ".", "add_test", "(", "TextList", "(", "test_ids", ",", "vocab", ",", "path", "=", "path", ")", ",", "label", "=", "train_lbls", "[", "0", "]", ")", "src", ".", "valid", ".", "x", ".", "processor", "=", "ifnone", "(", "processor", ",", "[", "TokenizeProcessor", "(", ")", ",", "NumericalizeProcessor", "(", "vocab", "=", "vocab", ")", "]", ")", "return", "src", ".", "databunch", "(", "*", "*", "kwargs", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TextDataBunch.load
Load a `TextDataBunch` from `path/cache_name`. `kwargs` are passed to the dataloader creation.
fastai/text/data.py
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. Use `load_data` for data saved with v1.0.44 or later.""", DeprecationWarning) cache_path = Path(path)/cache_name vocab = Vocab(pickle.load(open(cache_path/'itos.pkl','rb'))) train_ids,train_lbls = np.load(cache_path/f'train_ids.npy'), np.load(cache_path/f'train_lbl.npy') valid_ids,valid_lbls = np.load(cache_path/f'valid_ids.npy'), np.load(cache_path/f'valid_lbl.npy') test_ids = np.load(cache_path/f'test_ids.npy') if os.path.isfile(cache_path/f'test_ids.npy') else None classes = loadtxt_str(cache_path/'classes.txt') if os.path.isfile(cache_path/'classes.txt') else None return cls.from_ids(path, vocab, train_ids, valid_ids, test_ids, train_lbls, valid_lbls, classes, processor, **kwargs)
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. Use `load_data` for data saved with v1.0.44 or later.""", DeprecationWarning) cache_path = Path(path)/cache_name vocab = Vocab(pickle.load(open(cache_path/'itos.pkl','rb'))) train_ids,train_lbls = np.load(cache_path/f'train_ids.npy'), np.load(cache_path/f'train_lbl.npy') valid_ids,valid_lbls = np.load(cache_path/f'valid_ids.npy'), np.load(cache_path/f'valid_lbl.npy') test_ids = np.load(cache_path/f'test_ids.npy') if os.path.isfile(cache_path/f'test_ids.npy') else None classes = loadtxt_str(cache_path/'classes.txt') if os.path.isfile(cache_path/'classes.txt') else None return cls.from_ids(path, vocab, train_ids, valid_ids, test_ids, train_lbls, valid_lbls, classes, processor, **kwargs)
[ "Load", "a", "TextDataBunch", "from", "path", "/", "cache_name", ".", "kwargs", "are", "passed", "to", "the", "dataloader", "creation", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L164-L174
[ "def", "load", "(", "cls", ",", "path", ":", "PathOrStr", ",", "cache_name", ":", "PathOrStr", "=", "'tmp'", ",", "processor", ":", "PreProcessor", "=", "None", ",", "*", "*", "kwargs", ")", ":", "warn", "(", "\"\"\"This method is deprecated and only kept to load data serialized in v1.0.43 or earlier.\n Use `load_data` for data saved with v1.0.44 or later.\"\"\"", ",", "DeprecationWarning", ")", "cache_path", "=", "Path", "(", "path", ")", "/", "cache_name", "vocab", "=", "Vocab", "(", "pickle", ".", "load", "(", "open", "(", "cache_path", "/", "'itos.pkl'", ",", "'rb'", ")", ")", ")", "train_ids", ",", "train_lbls", "=", "np", ".", "load", "(", "cache_path", "/", "f'train_ids.npy'", ")", ",", "np", ".", "load", "(", "cache_path", "/", "f'train_lbl.npy'", ")", "valid_ids", ",", "valid_lbls", "=", "np", ".", "load", "(", "cache_path", "/", "f'valid_ids.npy'", ")", ",", "np", ".", "load", "(", "cache_path", "/", "f'valid_lbl.npy'", ")", "test_ids", "=", "np", ".", "load", "(", "cache_path", "/", "f'test_ids.npy'", ")", "if", "os", ".", "path", ".", "isfile", "(", "cache_path", "/", "f'test_ids.npy'", ")", "else", "None", "classes", "=", "loadtxt_str", "(", "cache_path", "/", "'classes.txt'", ")", "if", "os", ".", "path", ".", "isfile", "(", "cache_path", "/", "'classes.txt'", ")", "else", "None", "return", "cls", ".", "from_ids", "(", "path", ",", "vocab", ",", "train_ids", ",", "valid_ids", ",", "test_ids", ",", "train_lbls", ",", "valid_lbls", ",", "classes", ",", "processor", ",", "*", "*", "kwargs", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TextDataBunch.from_tokens
Create a `TextDataBunch` from tokens and labels. `kwargs` are passed to the dataloader creation.
fastai/text/data.py
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_vocab:int=60000, min_freq:int=3, **kwargs) -> DataBunch: "Create a `TextDataBunch` from tokens and labels. `kwargs` are passed to the dataloader creation." processor = NumericalizeProcessor(vocab=vocab, max_vocab=max_vocab, min_freq=min_freq) src = ItemLists(path, TextList(trn_tok, path=path, processor=processor), TextList(val_tok, path=path, processor=processor)) src = src.label_for_lm() if cls==TextLMDataBunch else src.label_from_lists(trn_lbls, val_lbls, classes=classes) if tst_tok is not None: src.add_test(TextList(tst_tok, path=path)) return src.databunch(**kwargs)
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_vocab:int=60000, min_freq:int=3, **kwargs) -> DataBunch: "Create a `TextDataBunch` from tokens and labels. `kwargs` are passed to the dataloader creation." processor = NumericalizeProcessor(vocab=vocab, max_vocab=max_vocab, min_freq=min_freq) src = ItemLists(path, TextList(trn_tok, path=path, processor=processor), TextList(val_tok, path=path, processor=processor)) src = src.label_for_lm() if cls==TextLMDataBunch else src.label_from_lists(trn_lbls, val_lbls, classes=classes) if tst_tok is not None: src.add_test(TextList(tst_tok, path=path)) return src.databunch(**kwargs)
[ "Create", "a", "TextDataBunch", "from", "tokens", "and", "labels", ".", "kwargs", "are", "passed", "to", "the", "dataloader", "creation", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L177-L187
[ "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_vocab", ":", "int", "=", "60000", ",", "min_freq", ":", "int", "=", "3", ",", "*", "*", "kwargs", ")", "->", "DataBunch", ":", "processor", "=", "NumericalizeProcessor", "(", "vocab", "=", "vocab", ",", "max_vocab", "=", "max_vocab", ",", "min_freq", "=", "min_freq", ")", "src", "=", "ItemLists", "(", "path", ",", "TextList", "(", "trn_tok", ",", "path", "=", "path", ",", "processor", "=", "processor", ")", ",", "TextList", "(", "val_tok", ",", "path", "=", "path", ",", "processor", "=", "processor", ")", ")", "src", "=", "src", ".", "label_for_lm", "(", ")", "if", "cls", "==", "TextLMDataBunch", "else", "src", ".", "label_from_lists", "(", "trn_lbls", ",", "val_lbls", ",", "classes", "=", "classes", ")", "if", "tst_tok", "is", "not", "None", ":", "src", ".", "add_test", "(", "TextList", "(", "tst_tok", ",", "path", "=", "path", ")", ")", "return", "src", ".", "databunch", "(", "*", "*", "kwargs", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TextDataBunch.from_df
Create a `TextDataBunch` from DataFrames. `kwargs` are passed to the dataloader creation.
fastai/text/data.py
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=60000, min_freq:int=2, mark_fields:bool=False, include_bos:bool=True, include_eos:bool=False, **kwargs) -> DataBunch: "Create a `TextDataBunch` from DataFrames. `kwargs` are passed to the dataloader creation." processor = _get_processor(tokenizer=tokenizer, vocab=vocab, chunksize=chunksize, max_vocab=max_vocab, min_freq=min_freq, mark_fields=mark_fields, include_bos=include_bos, include_eos=include_eos) if classes is None and is_listy(label_cols) and len(label_cols) > 1: classes = label_cols src = ItemLists(path, TextList.from_df(train_df, path, cols=text_cols, processor=processor), TextList.from_df(valid_df, path, cols=text_cols, processor=processor)) if cls==TextLMDataBunch: src = src.label_for_lm() else: if label_delim is not None: src = src.label_from_df(cols=label_cols, classes=classes, label_delim=label_delim) else: src = src.label_from_df(cols=label_cols, classes=classes) if test_df is not None: src.add_test(TextList.from_df(test_df, path, cols=text_cols)) return src.databunch(**kwargs)
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=60000, min_freq:int=2, mark_fields:bool=False, include_bos:bool=True, include_eos:bool=False, **kwargs) -> DataBunch: "Create a `TextDataBunch` from DataFrames. `kwargs` are passed to the dataloader creation." processor = _get_processor(tokenizer=tokenizer, vocab=vocab, chunksize=chunksize, max_vocab=max_vocab, min_freq=min_freq, mark_fields=mark_fields, include_bos=include_bos, include_eos=include_eos) if classes is None and is_listy(label_cols) and len(label_cols) > 1: classes = label_cols src = ItemLists(path, TextList.from_df(train_df, path, cols=text_cols, processor=processor), TextList.from_df(valid_df, path, cols=text_cols, processor=processor)) if cls==TextLMDataBunch: src = src.label_for_lm() else: if label_delim is not None: src = src.label_from_df(cols=label_cols, classes=classes, label_delim=label_delim) else: src = src.label_from_df(cols=label_cols, classes=classes) if test_df is not None: src.add_test(TextList.from_df(test_df, path, cols=text_cols)) return src.databunch(**kwargs)
[ "Create", "a", "TextDataBunch", "from", "DataFrames", ".", "kwargs", "are", "passed", "to", "the", "dataloader", "creation", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L190-L206
[ "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", "=", "60000", ",", "min_freq", ":", "int", "=", "2", ",", "mark_fields", ":", "bool", "=", "False", ",", "include_bos", ":", "bool", "=", "True", ",", "include_eos", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", "->", "DataBunch", ":", "processor", "=", "_get_processor", "(", "tokenizer", "=", "tokenizer", ",", "vocab", "=", "vocab", ",", "chunksize", "=", "chunksize", ",", "max_vocab", "=", "max_vocab", ",", "min_freq", "=", "min_freq", ",", "mark_fields", "=", "mark_fields", ",", "include_bos", "=", "include_bos", ",", "include_eos", "=", "include_eos", ")", "if", "classes", "is", "None", "and", "is_listy", "(", "label_cols", ")", "and", "len", "(", "label_cols", ")", ">", "1", ":", "classes", "=", "label_cols", "src", "=", "ItemLists", "(", "path", ",", "TextList", ".", "from_df", "(", "train_df", ",", "path", ",", "cols", "=", "text_cols", ",", "processor", "=", "processor", ")", ",", "TextList", ".", "from_df", "(", "valid_df", ",", "path", ",", "cols", "=", "text_cols", ",", "processor", "=", "processor", ")", ")", "if", "cls", "==", "TextLMDataBunch", ":", "src", "=", "src", ".", "label_for_lm", "(", ")", "else", ":", "if", "label_delim", "is", "not", "None", ":", "src", "=", "src", ".", "label_from_df", "(", "cols", "=", "label_cols", ",", "classes", "=", "classes", ",", "label_delim", "=", "label_delim", ")", "else", ":", "src", "=", "src", ".", "label_from_df", "(", "cols", "=", "label_cols", ",", "classes", "=", "classes", ")", "if", "test_df", "is", "not", "None", ":", "src", ".", "add_test", "(", "TextList", ".", "from_df", "(", "test_df", ",", "path", ",", "cols", "=", "text_cols", ")", ")", "return", "src", ".", "databunch", "(", "*", "*", "kwargs", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TextDataBunch.from_csv
Create a `TextDataBunch` from texts in csv files. `kwargs` are passed to the dataloader creation.
fastai/text/data.py
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, chunksize:int=10000, max_vocab:int=60000, min_freq:int=2, mark_fields:bool=False, include_bos:bool=True, include_eos:bool=False, **kwargs) -> DataBunch: "Create a `TextDataBunch` from texts in csv files. `kwargs` are passed to the dataloader creation." df = pd.read_csv(Path(path)/csv_name, header=header, delimiter=delimiter) df = df.iloc[np.random.permutation(len(df))] cut = int(valid_pct * len(df)) + 1 train_df, valid_df = df[cut:], df[:cut] test_df = None if test is None else pd.read_csv(Path(path)/test, header=header, delimiter=delimiter) return cls.from_df(path, train_df, valid_df, test_df, tokenizer=tokenizer, vocab=vocab, classes=classes, text_cols=text_cols, label_cols=label_cols, label_delim=label_delim, chunksize=chunksize, max_vocab=max_vocab, min_freq=min_freq, mark_fields=mark_fields, include_bos=include_bos, include_eos=include_eos, **kwargs)
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, chunksize:int=10000, max_vocab:int=60000, min_freq:int=2, mark_fields:bool=False, include_bos:bool=True, include_eos:bool=False, **kwargs) -> DataBunch: "Create a `TextDataBunch` from texts in csv files. `kwargs` are passed to the dataloader creation." df = pd.read_csv(Path(path)/csv_name, header=header, delimiter=delimiter) df = df.iloc[np.random.permutation(len(df))] cut = int(valid_pct * len(df)) + 1 train_df, valid_df = df[cut:], df[:cut] test_df = None if test is None else pd.read_csv(Path(path)/test, header=header, delimiter=delimiter) return cls.from_df(path, train_df, valid_df, test_df, tokenizer=tokenizer, vocab=vocab, classes=classes, text_cols=text_cols, label_cols=label_cols, label_delim=label_delim, chunksize=chunksize, max_vocab=max_vocab, min_freq=min_freq, mark_fields=mark_fields, include_bos=include_bos, include_eos=include_eos, **kwargs)
[ "Create", "a", "TextDataBunch", "from", "texts", "in", "csv", "files", ".", "kwargs", "are", "passed", "to", "the", "dataloader", "creation", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L209-L223
[ "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", ",", "chunksize", ":", "int", "=", "10000", ",", "max_vocab", ":", "int", "=", "60000", ",", "min_freq", ":", "int", "=", "2", ",", "mark_fields", ":", "bool", "=", "False", ",", "include_bos", ":", "bool", "=", "True", ",", "include_eos", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", "->", "DataBunch", ":", "df", "=", "pd", ".", "read_csv", "(", "Path", "(", "path", ")", "/", "csv_name", ",", "header", "=", "header", ",", "delimiter", "=", "delimiter", ")", "df", "=", "df", ".", "iloc", "[", "np", ".", "random", ".", "permutation", "(", "len", "(", "df", ")", ")", "]", "cut", "=", "int", "(", "valid_pct", "*", "len", "(", "df", ")", ")", "+", "1", "train_df", ",", "valid_df", "=", "df", "[", "cut", ":", "]", ",", "df", "[", ":", "cut", "]", "test_df", "=", "None", "if", "test", "is", "None", "else", "pd", ".", "read_csv", "(", "Path", "(", "path", ")", "/", "test", ",", "header", "=", "header", ",", "delimiter", "=", "delimiter", ")", "return", "cls", ".", "from_df", "(", "path", ",", "train_df", ",", "valid_df", ",", "test_df", ",", "tokenizer", "=", "tokenizer", ",", "vocab", "=", "vocab", ",", "classes", "=", "classes", ",", "text_cols", "=", "text_cols", ",", "label_cols", "=", "label_cols", ",", "label_delim", "=", "label_delim", ",", "chunksize", "=", "chunksize", ",", "max_vocab", "=", "max_vocab", ",", "min_freq", "=", "min_freq", ",", "mark_fields", "=", "mark_fields", ",", "include_bos", "=", "include_bos", ",", "include_eos", "=", "include_eos", ",", "*", "*", "kwargs", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TextDataBunch.from_folder
Create a `TextDataBunch` from text files in folders.
fastai/text/data.py
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, include_eos:bool=False, **kwargs): "Create a `TextDataBunch` from text files in folders." path = Path(path).absolute() processor = [OpenFileProcessor()] + _get_processor(tokenizer=tokenizer, vocab=vocab, chunksize=chunksize, max_vocab=max_vocab, min_freq=min_freq, mark_fields=mark_fields, include_bos=include_bos, include_eos=include_eos) src = (TextList.from_folder(path, processor=processor) .split_by_folder(train=train, valid=valid)) src = src.label_for_lm() if cls==TextLMDataBunch else src.label_from_folder(classes=classes) if test is not None: src.add_test_folder(path/test) return src.databunch(**kwargs)
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, include_eos:bool=False, **kwargs): "Create a `TextDataBunch` from text files in folders." path = Path(path).absolute() processor = [OpenFileProcessor()] + _get_processor(tokenizer=tokenizer, vocab=vocab, chunksize=chunksize, max_vocab=max_vocab, min_freq=min_freq, mark_fields=mark_fields, include_bos=include_bos, include_eos=include_eos) src = (TextList.from_folder(path, processor=processor) .split_by_folder(train=train, valid=valid)) src = src.label_for_lm() if cls==TextLMDataBunch else src.label_from_folder(classes=classes) if test is not None: src.add_test_folder(path/test) return src.databunch(**kwargs)
[ "Create", "a", "TextDataBunch", "from", "text", "files", "in", "folders", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L226-L237
[ "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", ",", "include_eos", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", ":", "path", "=", "Path", "(", "path", ")", ".", "absolute", "(", ")", "processor", "=", "[", "OpenFileProcessor", "(", ")", "]", "+", "_get_processor", "(", "tokenizer", "=", "tokenizer", ",", "vocab", "=", "vocab", ",", "chunksize", "=", "chunksize", ",", "max_vocab", "=", "max_vocab", ",", "min_freq", "=", "min_freq", ",", "mark_fields", "=", "mark_fields", ",", "include_bos", "=", "include_bos", ",", "include_eos", "=", "include_eos", ")", "src", "=", "(", "TextList", ".", "from_folder", "(", "path", ",", "processor", "=", "processor", ")", ".", "split_by_folder", "(", "train", "=", "train", ",", "valid", "=", "valid", ")", ")", "src", "=", "src", ".", "label_for_lm", "(", ")", "if", "cls", "==", "TextLMDataBunch", "else", "src", ".", "label_from_folder", "(", "classes", "=", "classes", ")", "if", "test", "is", "not", "None", ":", "src", ".", "add_test_folder", "(", "path", "/", "test", ")", "return", "src", ".", "databunch", "(", "*", "*", "kwargs", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TextLMDataBunch.create
Create a `TextDataBunch` in `path` from the `datasets` for language modelling. Passes `**dl_kwargs` on to `DataLoader()`
fastai/text/data.py
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) -> DataBunch: "Create a `TextDataBunch` in `path` from the `datasets` for language modelling. Passes `**dl_kwargs` on to `DataLoader()`" datasets = cls._init_ds(train_ds, valid_ds, test_ds) val_bs = ifnone(val_bs, bs) datasets = [LanguageModelPreLoader(ds, shuffle=(i==0), bs=(bs if i==0 else val_bs), bptt=bptt, backwards=backwards) for i,ds in enumerate(datasets)] val_bs = bs dls = [DataLoader(d, b, shuffle=False, **dl_kwargs) for d,b in zip(datasets, (bs,val_bs,val_bs,val_bs)) if d is not None] return cls(*dls, path=path, device=device, dl_tfms=dl_tfms, collate_fn=collate_fn, no_check=no_check)
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) -> DataBunch: "Create a `TextDataBunch` in `path` from the `datasets` for language modelling. Passes `**dl_kwargs` on to `DataLoader()`" datasets = cls._init_ds(train_ds, valid_ds, test_ds) val_bs = ifnone(val_bs, bs) datasets = [LanguageModelPreLoader(ds, shuffle=(i==0), bs=(bs if i==0 else val_bs), bptt=bptt, backwards=backwards) for i,ds in enumerate(datasets)] val_bs = bs dls = [DataLoader(d, b, shuffle=False, **dl_kwargs) for d,b in zip(datasets, (bs,val_bs,val_bs,val_bs)) if d is not None] return cls(*dls, path=path, device=device, dl_tfms=dl_tfms, collate_fn=collate_fn, no_check=no_check)
[ "Create", "a", "TextDataBunch", "in", "path", "from", "the", "datasets", "for", "language", "modelling", ".", "Passes", "**", "dl_kwargs", "on", "to", "DataLoader", "()" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L242-L252
[ "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", ")", "->", "DataBunch", ":", "datasets", "=", "cls", ".", "_init_ds", "(", "train_ds", ",", "valid_ds", ",", "test_ds", ")", "val_bs", "=", "ifnone", "(", "val_bs", ",", "bs", ")", "datasets", "=", "[", "LanguageModelPreLoader", "(", "ds", ",", "shuffle", "=", "(", "i", "==", "0", ")", ",", "bs", "=", "(", "bs", "if", "i", "==", "0", "else", "val_bs", ")", ",", "bptt", "=", "bptt", ",", "backwards", "=", "backwards", ")", "for", "i", ",", "ds", "in", "enumerate", "(", "datasets", ")", "]", "val_bs", "=", "bs", "dls", "=", "[", "DataLoader", "(", "d", ",", "b", ",", "shuffle", "=", "False", ",", "*", "*", "dl_kwargs", ")", "for", "d", ",", "b", "in", "zip", "(", "datasets", ",", "(", "bs", ",", "val_bs", ",", "val_bs", ",", "val_bs", ")", ")", "if", "d", "is", "not", "None", "]", "return", "cls", "(", "*", "dls", ",", "path", "=", "path", ",", "device", "=", "device", ",", "dl_tfms", "=", "dl_tfms", ",", "collate_fn", "=", "collate_fn", ",", "no_check", "=", "no_check", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TextClasDataBunch.create
Function that transform the `datasets` in a `DataBunch` for classification. Passes `**dl_kwargs` on to `DataLoader()`
fastai/text/data.py
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. Passes `**dl_kwargs` on to `DataLoader()`" datasets = cls._init_ds(train_ds, valid_ds, test_ds) val_bs = ifnone(val_bs, bs) collate_fn = partial(pad_collate, pad_idx=pad_idx, pad_first=pad_first, backwards=backwards) train_sampler = SortishSampler(datasets[0].x, key=lambda t: len(datasets[0][t][0].data), bs=bs) train_dl = DataLoader(datasets[0], batch_size=bs, sampler=train_sampler, drop_last=True, **dl_kwargs) dataloaders = [train_dl] for ds in datasets[1:]: lengths = [len(t) for t in ds.x.items] sampler = SortSampler(ds.x, key=lengths.__getitem__) dataloaders.append(DataLoader(ds, batch_size=val_bs, sampler=sampler, **dl_kwargs)) return cls(*dataloaders, path=path, device=device, collate_fn=collate_fn, no_check=no_check)
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. Passes `**dl_kwargs` on to `DataLoader()`" datasets = cls._init_ds(train_ds, valid_ds, test_ds) val_bs = ifnone(val_bs, bs) collate_fn = partial(pad_collate, pad_idx=pad_idx, pad_first=pad_first, backwards=backwards) train_sampler = SortishSampler(datasets[0].x, key=lambda t: len(datasets[0][t][0].data), bs=bs) train_dl = DataLoader(datasets[0], batch_size=bs, sampler=train_sampler, drop_last=True, **dl_kwargs) dataloaders = [train_dl] for ds in datasets[1:]: lengths = [len(t) for t in ds.x.items] sampler = SortSampler(ds.x, key=lengths.__getitem__) dataloaders.append(DataLoader(ds, batch_size=val_bs, sampler=sampler, **dl_kwargs)) return cls(*dataloaders, path=path, device=device, collate_fn=collate_fn, no_check=no_check)
[ "Function", "that", "transform", "the", "datasets", "in", "a", "DataBunch", "for", "classification", ".", "Passes", "**", "dl_kwargs", "on", "to", "DataLoader", "()" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L257-L270
[ "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", ":", "datasets", "=", "cls", ".", "_init_ds", "(", "train_ds", ",", "valid_ds", ",", "test_ds", ")", "val_bs", "=", "ifnone", "(", "val_bs", ",", "bs", ")", "collate_fn", "=", "partial", "(", "pad_collate", ",", "pad_idx", "=", "pad_idx", ",", "pad_first", "=", "pad_first", ",", "backwards", "=", "backwards", ")", "train_sampler", "=", "SortishSampler", "(", "datasets", "[", "0", "]", ".", "x", ",", "key", "=", "lambda", "t", ":", "len", "(", "datasets", "[", "0", "]", "[", "t", "]", "[", "0", "]", ".", "data", ")", ",", "bs", "=", "bs", ")", "train_dl", "=", "DataLoader", "(", "datasets", "[", "0", "]", ",", "batch_size", "=", "bs", ",", "sampler", "=", "train_sampler", ",", "drop_last", "=", "True", ",", "*", "*", "dl_kwargs", ")", "dataloaders", "=", "[", "train_dl", "]", "for", "ds", "in", "datasets", "[", "1", ":", "]", ":", "lengths", "=", "[", "len", "(", "t", ")", "for", "t", "in", "ds", ".", "x", ".", "items", "]", "sampler", "=", "SortSampler", "(", "ds", ".", "x", ",", "key", "=", "lengths", ".", "__getitem__", ")", "dataloaders", ".", "append", "(", "DataLoader", "(", "ds", ",", "batch_size", "=", "val_bs", ",", "sampler", "=", "sampler", ",", "*", "*", "dl_kwargs", ")", ")", "return", "cls", "(", "*", "dataloaders", ",", "path", "=", "path", ",", "device", "=", "device", ",", "collate_fn", "=", "collate_fn", ",", "no_check", "=", "no_check", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TextList.label_for_lm
A special labelling method for language models.
fastai/text/data.py
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): "A special labelling method for language models." self.__class__ = LMTextList kwargs['label_cls'] = LMLabelList return self.label_const(0, **kwargs)
[ "A", "special", "labelling", "method", "for", "language", "models", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L330-L334
[ "def", "label_for_lm", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__class__", "=", "LMTextList", "kwargs", "[", "'label_cls'", "]", "=", "LMLabelList", "return", "self", ".", "label_const", "(", "0", ",", "*", "*", "kwargs", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TextList.from_folder
Get the list of files in `path` that have a text suffix. `recurse` determines if we search subfolders.
fastai/text/data.py
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(processor, [OpenFileProcessor(), TokenizeProcessor(), NumericalizeProcessor(vocab=vocab)]) return super().from_folder(path=path, extensions=extensions, processor=processor, **kwargs)
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(processor, [OpenFileProcessor(), TokenizeProcessor(), NumericalizeProcessor(vocab=vocab)]) return super().from_folder(path=path, extensions=extensions, processor=processor, **kwargs)
[ "Get", "the", "list", "of", "files", "in", "path", "that", "have", "a", "text", "suffix", ".", "recurse", "determines", "if", "we", "search", "subfolders", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L342-L346
[ "def", "from_folder", "(", "cls", ",", "path", ":", "PathOrStr", "=", "'.'", ",", "extensions", ":", "Collection", "[", "str", "]", "=", "text_extensions", ",", "vocab", ":", "Vocab", "=", "None", ",", "processor", ":", "PreProcessor", "=", "None", ",", "*", "*", "kwargs", ")", "->", "'TextList'", ":", "processor", "=", "ifnone", "(", "processor", ",", "[", "OpenFileProcessor", "(", ")", ",", "TokenizeProcessor", "(", ")", ",", "NumericalizeProcessor", "(", "vocab", "=", "vocab", ")", "]", ")", "return", "super", "(", ")", ".", "from_folder", "(", "path", "=", "path", ",", "extensions", "=", "extensions", ",", "processor", "=", "processor", ",", "*", "*", "kwargs", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
TextList.show_xys
Show the `xs` (inputs) and `ys` (targets). `max_len` is the maximum number of tokens displayed.
fastai/text/data.py
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 enumerate(zip(xs,ys)): txt_x = ' '.join(x.text.split(' ')[:max_len]) if max_len is not None else x.text items.append([i, txt_x] if self._is_lm else [txt_x, y]) items = np.array(items) df = pd.DataFrame({n:items[:,i] for i,n in enumerate(names)}, columns=names) with pd.option_context('display.max_colwidth', -1): display(HTML(df.to_html(index=False)))
def show_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 enumerate(zip(xs,ys)): txt_x = ' '.join(x.text.split(' ')[:max_len]) if max_len is not None else x.text items.append([i, txt_x] if self._is_lm else [txt_x, y]) items = np.array(items) df = pd.DataFrame({n:items[:,i] for i,n in enumerate(names)}, columns=names) with pd.option_context('display.max_colwidth', -1): display(HTML(df.to_html(index=False)))
[ "Show", "the", "xs", "(", "inputs", ")", "and", "ys", "(", "targets", ")", ".", "max_len", "is", "the", "maximum", "number", "of", "tokens", "displayed", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/text/data.py#L348-L359
[ "def", "show_xys", "(", "self", ",", "xs", ",", "ys", ",", "max_len", ":", "int", "=", "70", ")", "->", "None", ":", "from", "IPython", ".", "display", "import", "display", ",", "HTML", "names", "=", "[", "'idx'", ",", "'text'", "]", "if", "self", ".", "_is_lm", "else", "[", "'text'", ",", "'target'", "]", "items", "=", "[", "]", "for", "i", ",", "(", "x", ",", "y", ")", "in", "enumerate", "(", "zip", "(", "xs", ",", "ys", ")", ")", ":", "txt_x", "=", "' '", ".", "join", "(", "x", ".", "text", ".", "split", "(", "' '", ")", "[", ":", "max_len", "]", ")", "if", "max_len", "is", "not", "None", "else", "x", ".", "text", "items", ".", "append", "(", "[", "i", ",", "txt_x", "]", "if", "self", ".", "_is_lm", "else", "[", "txt_x", ",", "y", "]", ")", "items", "=", "np", ".", "array", "(", "items", ")", "df", "=", "pd", ".", "DataFrame", "(", "{", "n", ":", "items", "[", ":", ",", "i", "]", "for", "i", ",", "n", "in", "enumerate", "(", "names", ")", "}", ",", "columns", "=", "names", ")", "with", "pd", ".", "option_context", "(", "'display.max_colwidth'", ",", "-", "1", ")", ":", "display", "(", "HTML", "(", "df", ".", "to_html", "(", "index", "=", "False", ")", ")", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
inceptionv4
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
old/fastai/models/inceptionv4.py
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.load_state_dict(model_zoo.load_url(model_urls['imagenet'])) return model
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.load_state_dict(model_zoo.load_url(model_urls['imagenet'])) return model
[ "r", "InceptionV4", "model", "architecture", "from", "the", "Inception", "-", "v4", "Inception", "-", "ResNet", "...", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1602", ".", "07261", ">", "_", "paper", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/models/inceptionv4.py#L263-L273
[ "def", "inceptionv4", "(", "pretrained", "=", "True", ")", ":", "model", "=", "InceptionV4", "(", ")", "if", "pretrained", ":", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "model_urls", "[", "'imagenet'", "]", ")", ")", "return", "model" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ConvLearner.predict_array
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 from the model
old/fastai/conv_learner.py
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: a numpy array containing the predictions from the model """ precompute = self.precompute self.precompute = False pred = super().predict_array(arr) self.precompute = precompute return pred
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: a numpy array containing the predictions from the model """ precompute = self.precompute self.precompute = False pred = super().predict_array(arr) self.precompute = precompute return pred
[ "This", "over", "-", "ride", "is", "necessary", "because", "otherwise", "the", "learner", "method", "accesses", "the", "wrong", "model", "when", "it", "is", "called", "with", "precompute", "set", "to", "true" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/conv_learner.py#L211-L225
[ "def", "predict_array", "(", "self", ",", "arr", ")", ":", "precompute", "=", "self", ".", "precompute", "self", ".", "precompute", "=", "False", "pred", "=", "super", "(", ")", ".", "predict_array", "(", "arr", ")", "self", ".", "precompute", "=", "precompute", "return", "pred" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
main
Distrubuted training of CIFAR-10. Fastest speed is if you run as follows: python -m fastai.launch train_cifar.py
examples/train_cifar.py
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)], []) workers = min(16, num_cpus()//n_gpus) data = ImageDataBunch.from_folder(path, valid='test', ds_tfms=ds_tfms, bs=512//n_gpus, num_workers=workers).normalize(cifar_stats) learn = Learner(data, wrn_22(), metrics=accuracy) if gpu is None: learn.model = nn.DataParallel(learn.model) else: learn.to_distributed(gpu) learn.to_fp16() learn.fit_one_cycle(35, 3e-3, wd=0.4)
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)], []) workers = min(16, num_cpus()//n_gpus) data = ImageDataBunch.from_folder(path, valid='test', ds_tfms=ds_tfms, bs=512//n_gpus, num_workers=workers).normalize(cifar_stats) learn = Learner(data, wrn_22(), metrics=accuracy) if gpu is None: learn.model = nn.DataParallel(learn.model) else: learn.to_distributed(gpu) learn.to_fp16() learn.fit_one_cycle(35, 3e-3, wd=0.4)
[ "Distrubuted", "training", "of", "CIFAR", "-", "10", ".", "Fastest", "speed", "is", "if", "you", "run", "as", "follows", ":", "python", "-", "m", "fastai", ".", "launch", "train_cifar", ".", "py" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/examples/train_cifar.py#L8-L23
[ "def", "main", "(", "gpu", ":", "Param", "(", "\"GPU to run on\"", ",", "str", ")", "=", "None", ")", ":", "gpu", "=", "setup_distrib", "(", "gpu", ")", "n_gpus", "=", "num_distrib", "(", ")", "path", "=", "url2path", "(", "URLs", ".", "CIFAR", ")", "ds_tfms", "=", "(", "[", "*", "rand_pad", "(", "4", ",", "32", ")", ",", "flip_lr", "(", "p", "=", "0.5", ")", "]", ",", "[", "]", ")", "workers", "=", "min", "(", "16", ",", "num_cpus", "(", ")", "//", "n_gpus", ")", "data", "=", "ImageDataBunch", ".", "from_folder", "(", "path", ",", "valid", "=", "'test'", ",", "ds_tfms", "=", "ds_tfms", ",", "bs", "=", "512", "//", "n_gpus", ",", "num_workers", "=", "workers", ")", ".", "normalize", "(", "cifar_stats", ")", "learn", "=", "Learner", "(", "data", ",", "wrn_22", "(", ")", ",", "metrics", "=", "accuracy", ")", "if", "gpu", "is", "None", ":", "learn", ".", "model", "=", "nn", ".", "DataParallel", "(", "learn", ".", "model", ")", "else", ":", "learn", ".", "to_distributed", "(", "gpu", ")", "learn", ".", "to_fp16", "(", ")", "learn", ".", "fit_one_cycle", "(", "35", ",", "3e-3", ",", "wd", "=", "0.4", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
DepsCommand.initialize_options
Set default values for options.
setup.py
def initialize_options(self): """Set default values for options.""" self.dep_groups = '' self.dep_quote = False self.dep_conda = False
def initialize_options(self): """Set default values for options.""" self.dep_groups = '' self.dep_quote = False self.dep_conda = False
[ "Set", "default", "values", "for", "options", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/setup.py#L32-L36
[ "def", "initialize_options", "(", "self", ")", ":", "self", ".", "dep_groups", "=", "''", "self", ".", "dep_quote", "=", "False", "self", ".", "dep_conda", "=", "False" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
DepsCommand.run
Run command.
setup.py
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 wanted_groups: print("Available dependency groups:", ", ".join(sorted(dep_groups.keys()))) if invalid_groups: print(f"Error: Invalid group name(s): {', '.join(invalid_groups)}") exit(1) else: # prepare for shell word splitting (no whitespace in items) deps = [re.sub(" ", "", x, 0) for x in sorted(set(deps))] if self.dep_conda: for i in range(len(deps)): # strip pip-specific syntax deps[i] = re.sub(r';.*', '', deps[i]) # rename mismatching package names deps[i] = re.sub(r'^torch>', 'pytorch>', deps[i]) if self.dep_quote: # for manual copy-n-paste (assuming no " in vars) print(" ".join(map(lambda x: f'"{x}"', deps))) else: # if fed directly to `pip install` via backticks/$() don't quote print(" ".join(deps))
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 wanted_groups: print("Available dependency groups:", ", ".join(sorted(dep_groups.keys()))) if invalid_groups: print(f"Error: Invalid group name(s): {', '.join(invalid_groups)}") exit(1) else: # prepare for shell word splitting (no whitespace in items) deps = [re.sub(" ", "", x, 0) for x in sorted(set(deps))] if self.dep_conda: for i in range(len(deps)): # strip pip-specific syntax deps[i] = re.sub(r';.*', '', deps[i]) # rename mismatching package names deps[i] = re.sub(r'^torch>', 'pytorch>', deps[i]) if self.dep_quote: # for manual copy-n-paste (assuming no " in vars) print(" ".join(map(lambda x: f'"{x}"', deps))) else: # if fed directly to `pip install` via backticks/$() don't quote print(" ".join(deps))
[ "Run", "command", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/setup.py#L46-L75
[ "def", "run", "(", "self", ")", ":", "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", "wanted_groups", ":", "print", "(", "\"Available dependency groups:\"", ",", "\", \"", ".", "join", "(", "sorted", "(", "dep_groups", ".", "keys", "(", ")", ")", ")", ")", "if", "invalid_groups", ":", "print", "(", "f\"Error: Invalid group name(s): {', '.join(invalid_groups)}\"", ")", "exit", "(", "1", ")", "else", ":", "# prepare for shell word splitting (no whitespace in items)", "deps", "=", "[", "re", ".", "sub", "(", "\" \"", ",", "\"\"", ",", "x", ",", "0", ")", "for", "x", "in", "sorted", "(", "set", "(", "deps", ")", ")", "]", "if", "self", ".", "dep_conda", ":", "for", "i", "in", "range", "(", "len", "(", "deps", ")", ")", ":", "# strip pip-specific syntax", "deps", "[", "i", "]", "=", "re", ".", "sub", "(", "r';.*'", ",", "''", ",", "deps", "[", "i", "]", ")", "# rename mismatching package names", "deps", "[", "i", "]", "=", "re", ".", "sub", "(", "r'^torch>'", ",", "'pytorch>'", ",", "deps", "[", "i", "]", ")", "if", "self", ".", "dep_quote", ":", "# for manual copy-n-paste (assuming no \" in vars)", "print", "(", "\" \"", ".", "join", "(", "map", "(", "lambda", "x", ":", "f'\"{x}\"'", ",", "deps", ")", ")", ")", "else", ":", "# if fed directly to `pip install` via backticks/$() don't quote", "print", "(", "\" \"", ".", "join", "(", "deps", ")", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
get_sfs_idxs
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
old/fastai/models/unet.py
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 """ if last: feature_szs = [sfs_feats.features.size()[-1] for sfs_feats in sfs] sfs_idxs = list(np.where(np.array(feature_szs[:-1]) != np.array(feature_szs[1:]))[0]) if feature_szs[0] != feature_szs[1]: sfs_idxs = [0] + sfs_idxs else: sfs_idxs = list(range(len(sfs))) return 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 """ if last: feature_szs = [sfs_feats.features.size()[-1] for sfs_feats in sfs] sfs_idxs = list(np.where(np.array(feature_szs[:-1]) != np.array(feature_szs[1:]))[0]) if feature_szs[0] != feature_szs[1]: sfs_idxs = [0] + sfs_idxs else: sfs_idxs = list(range(len(sfs))) return sfs_idxs
[ "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" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/models/unet.py#L7-L19
[ "def", "get_sfs_idxs", "(", "sfs", ",", "last", "=", "True", ")", ":", "if", "last", ":", "feature_szs", "=", "[", "sfs_feats", ".", "features", ".", "size", "(", ")", "[", "-", "1", "]", "for", "sfs_feats", "in", "sfs", "]", "sfs_idxs", "=", "list", "(", "np", ".", "where", "(", "np", ".", "array", "(", "feature_szs", "[", ":", "-", "1", "]", ")", "!=", "np", ".", "array", "(", "feature_szs", "[", "1", ":", "]", ")", ")", "[", "0", "]", ")", "if", "feature_szs", "[", "0", "]", "!=", "feature_szs", "[", "1", "]", ":", "sfs_idxs", "=", "[", "0", "]", "+", "sfs_idxs", "else", ":", "sfs_idxs", "=", "list", "(", "range", "(", "len", "(", "sfs", ")", ")", ")", "return", "sfs_idxs" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
hook_output
Return a `Hook` that stores activations of `module` in `self.stored`
fastai/callbacks/hooks.py
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 a `Hook` that stores activations of `module` in `self.stored`" return Hook(module, _hook_inner, detach=detach, is_forward=not grad)
[ "Return", "a", "Hook", "that", "stores", "activations", "of", "module", "in", "self", ".", "stored" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L54-L56
[ "def", "hook_output", "(", "module", ":", "nn", ".", "Module", ",", "detach", ":", "bool", "=", "True", ",", "grad", ":", "bool", "=", "False", ")", "->", "Hook", ":", "return", "Hook", "(", "module", ",", "_hook_inner", ",", "detach", "=", "detach", ",", "is_forward", "=", "not", "grad", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
hook_outputs
Return `Hooks` that store activations of all `modules` in `self.stored`
fastai/callbacks/hooks.py
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` that store activations of all `modules` in `self.stored`" return Hooks(modules, _hook_inner, detach=detach, is_forward=not grad)
[ "Return", "Hooks", "that", "store", "activations", "of", "all", "modules", "in", "self", ".", "stored" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L58-L60
[ "def", "hook_outputs", "(", "modules", ":", "Collection", "[", "nn", ".", "Module", "]", ",", "detach", ":", "bool", "=", "True", ",", "grad", ":", "bool", "=", "False", ")", "->", "Hooks", ":", "return", "Hooks", "(", "modules", ",", "_hook_inner", ",", "detach", "=", "detach", ",", "is_forward", "=", "not", "grad", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
dummy_batch
Create a dummy batch to go through `m` with `size`.
fastai/callbacks/hooks.py
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: "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.)
[ "Create", "a", "dummy", "batch", "to", "go", "through", "m", "with", "size", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L101-L104
[ "def", "dummy_batch", "(", "m", ":", "nn", ".", "Module", ",", "size", ":", "tuple", "=", "(", "64", ",", "64", ")", ")", "->", "Tensor", ":", "ch_in", "=", "in_channels", "(", "m", ")", "return", "one_param", "(", "m", ")", ".", "new", "(", "1", ",", "ch_in", ",", "*", "size", ")", ".", "requires_grad_", "(", "False", ")", ".", "uniform_", "(", "-", "1.", ",", "1.", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
dummy_eval
Pass a `dummy_batch` in evaluation mode in `m` with `size`.
fastai/callbacks/hooks.py
def dummy_eval(m:nn.Module, size:tuple=(64,64)): "Pass a `dummy_batch` in evaluation mode in `m` with `size`." return m.eval()(dummy_batch(m, size))
def dummy_eval(m:nn.Module, size:tuple=(64,64)): "Pass a `dummy_batch` in evaluation mode in `m` with `size`." return m.eval()(dummy_batch(m, size))
[ "Pass", "a", "dummy_batch", "in", "evaluation", "mode", "in", "m", "with", "size", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L106-L108
[ "def", "dummy_eval", "(", "m", ":", "nn", ".", "Module", ",", "size", ":", "tuple", "=", "(", "64", ",", "64", ")", ")", ":", "return", "m", ".", "eval", "(", ")", "(", "dummy_batch", "(", "m", ",", "size", ")", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
model_sizes
Pass a dummy input through the model `m` to get the various sizes of activations.
fastai/callbacks/hooks.py
def model_sizes(m:nn.Module, size:tuple=(64,64))->Tuple[Sizes,Tensor,Hooks]: "Pass a dummy input through the model `m` to get the various sizes of activations." with hook_outputs(m) as hooks: x = dummy_eval(m, size) return [o.stored.shape for o in hooks]
def model_sizes(m:nn.Module, size:tuple=(64,64))->Tuple[Sizes,Tensor,Hooks]: "Pass a dummy input through the model `m` to get the various sizes of activations." with hook_outputs(m) as hooks: x = dummy_eval(m, size) return [o.stored.shape for o in hooks]
[ "Pass", "a", "dummy", "input", "through", "the", "model", "m", "to", "get", "the", "various", "sizes", "of", "activations", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L110-L114
[ "def", "model_sizes", "(", "m", ":", "nn", ".", "Module", ",", "size", ":", "tuple", "=", "(", "64", ",", "64", ")", ")", "->", "Tuple", "[", "Sizes", ",", "Tensor", ",", "Hooks", "]", ":", "with", "hook_outputs", "(", "m", ")", "as", "hooks", ":", "x", "=", "dummy_eval", "(", "m", ",", "size", ")", "return", "[", "o", ".", "stored", ".", "shape", "for", "o", "in", "hooks", "]" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
num_features_model
Return the number of output features for `model`.
fastai/callbacks/hooks.py
def num_features_model(m:nn.Module)->int: "Return the number of output features for `model`." sz = 64 while True: try: return model_sizes(m, size=(sz,sz))[-1][1] except Exception as e: sz *= 2 if sz > 2048: raise
def num_features_model(m:nn.Module)->int: "Return the number of output features for `model`." sz = 64 while True: try: return model_sizes(m, size=(sz,sz))[-1][1] except Exception as e: sz *= 2 if sz > 2048: raise
[ "Return", "the", "number", "of", "output", "features", "for", "model", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L116-L123
[ "def", "num_features_model", "(", "m", ":", "nn", ".", "Module", ")", "->", "int", ":", "sz", "=", "64", "while", "True", ":", "try", ":", "return", "model_sizes", "(", "m", ",", "size", "=", "(", "sz", ",", "sz", ")", ")", "[", "-", "1", "]", "[", "1", "]", "except", "Exception", "as", "e", ":", "sz", "*=", "2", "if", "sz", ">", "2048", ":", "raise" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
params_size
Pass a dummy input through the model to get the various sizes. Returns (res,x,hooks) if `full`
fastai/callbacks/hooks.py
def params_size(m: Union[nn.Module,Learner], size: tuple = (3, 64, 64))->Tuple[Sizes, Tensor, Hooks]: "Pass a dummy input through the model to get the various sizes. Returns (res,x,hooks) if `full`" if isinstance(m, Learner): if m.data.is_empty: raise Exception("This is an empty `Learner` and `Learner.summary` requires some data to pass through the model.") ds_type = DatasetType.Train if m.data.train_dl else (DatasetType.Valid if m.data.valid_dl else DatasetType.Test) x = m.data.one_batch(ds_type=ds_type, detach=False, denorm=False)[0] x = [o[:1] for o in x] if is_listy(x) else x[:1] m = m.model elif isinstance(m, nn.Module): x = next(m.parameters()).new(1, *size) else: raise TypeError('You should either pass in a Learner or nn.Module') with hook_outputs(flatten_model(m)) as hook_o: with hook_params(flatten_model(m))as hook_p: x = m.eval()(*x) if is_listy(x) else m.eval()(x) output_size = [((o.stored.shape[1:]) if o.stored is not None else None) for o in hook_o] params = [(o.stored if o.stored is not None else (None,None)) for o in hook_p] params, trainables = map(list,zip(*params)) return output_size, params, trainables
def params_size(m: Union[nn.Module,Learner], size: tuple = (3, 64, 64))->Tuple[Sizes, Tensor, Hooks]: "Pass a dummy input through the model to get the various sizes. Returns (res,x,hooks) if `full`" if isinstance(m, Learner): if m.data.is_empty: raise Exception("This is an empty `Learner` and `Learner.summary` requires some data to pass through the model.") ds_type = DatasetType.Train if m.data.train_dl else (DatasetType.Valid if m.data.valid_dl else DatasetType.Test) x = m.data.one_batch(ds_type=ds_type, detach=False, denorm=False)[0] x = [o[:1] for o in x] if is_listy(x) else x[:1] m = m.model elif isinstance(m, nn.Module): x = next(m.parameters()).new(1, *size) else: raise TypeError('You should either pass in a Learner or nn.Module') with hook_outputs(flatten_model(m)) as hook_o: with hook_params(flatten_model(m))as hook_p: x = m.eval()(*x) if is_listy(x) else m.eval()(x) output_size = [((o.stored.shape[1:]) if o.stored is not None else None) for o in hook_o] params = [(o.stored if o.stored is not None else (None,None)) for o in hook_p] params, trainables = map(list,zip(*params)) return output_size, params, trainables
[ "Pass", "a", "dummy", "input", "through", "the", "model", "to", "get", "the", "various", "sizes", ".", "Returns", "(", "res", "x", "hooks", ")", "if", "full" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L136-L153
[ "def", "params_size", "(", "m", ":", "Union", "[", "nn", ".", "Module", ",", "Learner", "]", ",", "size", ":", "tuple", "=", "(", "3", ",", "64", ",", "64", ")", ")", "->", "Tuple", "[", "Sizes", ",", "Tensor", ",", "Hooks", "]", ":", "if", "isinstance", "(", "m", ",", "Learner", ")", ":", "if", "m", ".", "data", ".", "is_empty", ":", "raise", "Exception", "(", "\"This is an empty `Learner` and `Learner.summary` requires some data to pass through the model.\"", ")", "ds_type", "=", "DatasetType", ".", "Train", "if", "m", ".", "data", ".", "train_dl", "else", "(", "DatasetType", ".", "Valid", "if", "m", ".", "data", ".", "valid_dl", "else", "DatasetType", ".", "Test", ")", "x", "=", "m", ".", "data", ".", "one_batch", "(", "ds_type", "=", "ds_type", ",", "detach", "=", "False", ",", "denorm", "=", "False", ")", "[", "0", "]", "x", "=", "[", "o", "[", ":", "1", "]", "for", "o", "in", "x", "]", "if", "is_listy", "(", "x", ")", "else", "x", "[", ":", "1", "]", "m", "=", "m", ".", "model", "elif", "isinstance", "(", "m", ",", "nn", ".", "Module", ")", ":", "x", "=", "next", "(", "m", ".", "parameters", "(", ")", ")", ".", "new", "(", "1", ",", "*", "size", ")", "else", ":", "raise", "TypeError", "(", "'You should either pass in a Learner or nn.Module'", ")", "with", "hook_outputs", "(", "flatten_model", "(", "m", ")", ")", "as", "hook_o", ":", "with", "hook_params", "(", "flatten_model", "(", "m", ")", ")", "as", "hook_p", ":", "x", "=", "m", ".", "eval", "(", ")", "(", "*", "x", ")", "if", "is_listy", "(", "x", ")", "else", "m", ".", "eval", "(", ")", "(", "x", ")", "output_size", "=", "[", "(", "(", "o", ".", "stored", ".", "shape", "[", "1", ":", "]", ")", "if", "o", ".", "stored", "is", "not", "None", "else", "None", ")", "for", "o", "in", "hook_o", "]", "params", "=", "[", "(", "o", ".", "stored", "if", "o", ".", "stored", "is", "not", "None", "else", "(", "None", ",", "None", ")", ")", "for", "o", "in", "hook_p", "]", "params", ",", "trainables", "=", "map", "(", "list", ",", "zip", "(", "*", "params", ")", ")", "return", "output_size", ",", "params", ",", "trainables" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
model_summary
Print a summary of `m` using a output text width of `n` chars
fastai/callbacks/hooks.py
def model_summary(m:Learner, n:int=70): "Print a summary of `m` using a output text width of `n` chars" info = layers_info(m) header = ["Layer (type)", "Output Shape", "Param #", "Trainable"] res = "=" * n + "\n" res += f"{header[0]:<20} {header[1]:<20} {header[2]:<10} {header[3]:<10}\n" res += "=" * n + "\n" total_params = 0 total_trainable_params = 0 for layer, size, params, trainable in info: if size is None: continue total_params += int(params) total_trainable_params += int(params) * trainable size, trainable = str(list(size)), str(trainable) res += f"{layer:<20} {size:<20} {int(params):<10,} {trainable:<10}\n" res += "_" * n + "\n" res += f"\nTotal params: {total_params:,}\n" res += f"Total trainable params: {total_trainable_params:,}\n" res += f"Total non-trainable params: {total_params - total_trainable_params:,}\n" return PrettyString(res)
def model_summary(m:Learner, n:int=70): "Print a summary of `m` using a output text width of `n` chars" info = layers_info(m) header = ["Layer (type)", "Output Shape", "Param #", "Trainable"] res = "=" * n + "\n" res += f"{header[0]:<20} {header[1]:<20} {header[2]:<10} {header[3]:<10}\n" res += "=" * n + "\n" total_params = 0 total_trainable_params = 0 for layer, size, params, trainable in info: if size is None: continue total_params += int(params) total_trainable_params += int(params) * trainable size, trainable = str(list(size)), str(trainable) res += f"{layer:<20} {size:<20} {int(params):<10,} {trainable:<10}\n" res += "_" * n + "\n" res += f"\nTotal params: {total_params:,}\n" res += f"Total trainable params: {total_trainable_params:,}\n" res += f"Total non-trainable params: {total_params - total_trainable_params:,}\n" return PrettyString(res)
[ "Print", "a", "summary", "of", "m", "using", "a", "output", "text", "width", "of", "n", "chars" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L165-L184
[ "def", "model_summary", "(", "m", ":", "Learner", ",", "n", ":", "int", "=", "70", ")", ":", "info", "=", "layers_info", "(", "m", ")", "header", "=", "[", "\"Layer (type)\"", ",", "\"Output Shape\"", ",", "\"Param #\"", ",", "\"Trainable\"", "]", "res", "=", "\"=\"", "*", "n", "+", "\"\\n\"", "res", "+=", "f\"{header[0]:<20} {header[1]:<20} {header[2]:<10} {header[3]:<10}\\n\"", "res", "+=", "\"=\"", "*", "n", "+", "\"\\n\"", "total_params", "=", "0", "total_trainable_params", "=", "0", "for", "layer", ",", "size", ",", "params", ",", "trainable", "in", "info", ":", "if", "size", "is", "None", ":", "continue", "total_params", "+=", "int", "(", "params", ")", "total_trainable_params", "+=", "int", "(", "params", ")", "*", "trainable", "size", ",", "trainable", "=", "str", "(", "list", "(", "size", ")", ")", ",", "str", "(", "trainable", ")", "res", "+=", "f\"{layer:<20} {size:<20} {int(params):<10,} {trainable:<10}\\n\"", "res", "+=", "\"_\"", "*", "n", "+", "\"\\n\"", "res", "+=", "f\"\\nTotal params: {total_params:,}\\n\"", "res", "+=", "f\"Total trainable params: {total_trainable_params:,}\\n\"", "res", "+=", "f\"Total non-trainable params: {total_params - total_trainable_params:,}\\n\"", "return", "PrettyString", "(", "res", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Hook.hook_fn
Applies `hook_func` to `module`, `input`, `output`.
fastai/callbacks/hooks.py
def hook_fn(self, module:nn.Module, input:Tensors, output:Tensors): "Applies `hook_func` to `module`, `input`, `output`." if self.detach: input = (o.detach() for o in input ) if is_listy(input ) else input.detach() output = (o.detach() for o in output) if is_listy(output) else output.detach() self.stored = self.hook_func(module, input, output)
def hook_fn(self, module:nn.Module, input:Tensors, output:Tensors): "Applies `hook_func` to `module`, `input`, `output`." if self.detach: input = (o.detach() for o in input ) if is_listy(input ) else input.detach() output = (o.detach() for o in output) if is_listy(output) else output.detach() self.stored = self.hook_func(module, input, output)
[ "Applies", "hook_func", "to", "module", "input", "output", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L18-L23
[ "def", "hook_fn", "(", "self", ",", "module", ":", "nn", ".", "Module", ",", "input", ":", "Tensors", ",", "output", ":", "Tensors", ")", ":", "if", "self", ".", "detach", ":", "input", "=", "(", "o", ".", "detach", "(", ")", "for", "o", "in", "input", ")", "if", "is_listy", "(", "input", ")", "else", "input", ".", "detach", "(", ")", "output", "=", "(", "o", ".", "detach", "(", ")", "for", "o", "in", "output", ")", "if", "is_listy", "(", "output", ")", "else", "output", ".", "detach", "(", ")", "self", ".", "stored", "=", "self", ".", "hook_func", "(", "module", ",", "input", ",", "output", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
Hook.remove
Remove the hook from the model.
fastai/callbacks/hooks.py
def remove(self): "Remove the hook from the model." if not self.removed: self.hook.remove() self.removed=True
def remove(self): "Remove the hook from the model." if not self.removed: self.hook.remove() self.removed=True
[ "Remove", "the", "hook", "from", "the", "model", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L25-L29
[ "def", "remove", "(", "self", ")", ":", "if", "not", "self", ".", "removed", ":", "self", ".", "hook", ".", "remove", "(", ")", "self", ".", "removed", "=", "True" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
HookCallback.on_train_begin
Register the `Hooks` on `self.modules`.
fastai/callbacks/hooks.py
def on_train_begin(self, **kwargs): "Register the `Hooks` on `self.modules`." if not self.modules: self.modules = [m for m in flatten_model(self.learn.model) if hasattr(m, 'weight')] self.hooks = Hooks(self.modules, self.hook)
def on_train_begin(self, **kwargs): "Register the `Hooks` on `self.modules`." if not self.modules: self.modules = [m for m in flatten_model(self.learn.model) if hasattr(m, 'weight')] self.hooks = Hooks(self.modules, self.hook)
[ "Register", "the", "Hooks", "on", "self", ".", "modules", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L68-L73
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "modules", ":", "self", ".", "modules", "=", "[", "m", "for", "m", "in", "flatten_model", "(", "self", ".", "learn", ".", "model", ")", "if", "hasattr", "(", "m", ",", "'weight'", ")", "]", "self", ".", "hooks", "=", "Hooks", "(", "self", ".", "modules", ",", "self", ".", "hook", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ActivationStats.hook
Take the mean and std of `o`.
fastai/callbacks/hooks.py
def hook(self, m:nn.Module, i:Tensors, o:Tensors)->Tuple[Rank0Tensor,Rank0Tensor]: "Take the mean and std of `o`." return o.mean().item(),o.std().item()
def hook(self, m:nn.Module, i:Tensors, o:Tensors)->Tuple[Rank0Tensor,Rank0Tensor]: "Take the mean and std of `o`." return o.mean().item(),o.std().item()
[ "Take", "the", "mean", "and", "std", "of", "o", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L91-L93
[ "def", "hook", "(", "self", ",", "m", ":", "nn", ".", "Module", ",", "i", ":", "Tensors", ",", "o", ":", "Tensors", ")", "->", "Tuple", "[", "Rank0Tensor", ",", "Rank0Tensor", "]", ":", "return", "o", ".", "mean", "(", ")", ".", "item", "(", ")", ",", "o", ".", "std", "(", ")", ".", "item", "(", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ActivationStats.on_batch_end
Take the stored results and puts it in `self.stats`
fastai/callbacks/hooks.py
def on_batch_end(self, train, **kwargs): "Take the stored results and puts it in `self.stats`" if train: self.stats.append(self.hooks.stored)
def on_batch_end(self, train, **kwargs): "Take the stored results and puts it in `self.stats`" if train: self.stats.append(self.hooks.stored)
[ "Take", "the", "stored", "results", "and", "puts", "it", "in", "self", ".", "stats" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/hooks.py#L94-L96
[ "def", "on_batch_end", "(", "self", ",", "train", ",", "*", "*", "kwargs", ")", ":", "if", "train", ":", "self", ".", "stats", ".", "append", "(", "self", ".", "hooks", ".", "stored", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
plots_from_files
Plots images given image files. Arguments: im_paths (list): list of paths figsize (tuple): figure size rows (int): number of rows titles (list): list of titles maintitle (string): main title
old/fastai/plots.py
def plots_from_files(imspaths, figsize=(10,5), rows=1, titles=None, maintitle=None): """Plots images given image files. Arguments: im_paths (list): list of paths figsize (tuple): figure size rows (int): number of rows titles (list): list of titles maintitle (string): main title """ f = plt.figure(figsize=figsize) if maintitle is not None: plt.suptitle(maintitle, fontsize=16) for i in range(len(imspaths)): sp = f.add_subplot(rows, ceildiv(len(imspaths), rows), i+1) sp.axis('Off') if titles is not None: sp.set_title(titles[i], fontsize=16) img = plt.imread(imspaths[i]) plt.imshow(img)
def plots_from_files(imspaths, figsize=(10,5), rows=1, titles=None, maintitle=None): """Plots images given image files. Arguments: im_paths (list): list of paths figsize (tuple): figure size rows (int): number of rows titles (list): list of titles maintitle (string): main title """ f = plt.figure(figsize=figsize) if maintitle is not None: plt.suptitle(maintitle, fontsize=16) for i in range(len(imspaths)): sp = f.add_subplot(rows, ceildiv(len(imspaths), rows), i+1) sp.axis('Off') if titles is not None: sp.set_title(titles[i], fontsize=16) img = plt.imread(imspaths[i]) plt.imshow(img)
[ "Plots", "images", "given", "image", "files", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/plots.py#L22-L39
[ "def", "plots_from_files", "(", "imspaths", ",", "figsize", "=", "(", "10", ",", "5", ")", ",", "rows", "=", "1", ",", "titles", "=", "None", ",", "maintitle", "=", "None", ")", ":", "f", "=", "plt", ".", "figure", "(", "figsize", "=", "figsize", ")", "if", "maintitle", "is", "not", "None", ":", "plt", ".", "suptitle", "(", "maintitle", ",", "fontsize", "=", "16", ")", "for", "i", "in", "range", "(", "len", "(", "imspaths", ")", ")", ":", "sp", "=", "f", ".", "add_subplot", "(", "rows", ",", "ceildiv", "(", "len", "(", "imspaths", ")", ",", "rows", ")", ",", "i", "+", "1", ")", "sp", ".", "axis", "(", "'Off'", ")", "if", "titles", "is", "not", "None", ":", "sp", ".", "set_title", "(", "titles", "[", "i", "]", ",", "fontsize", "=", "16", ")", "img", "=", "plt", ".", "imread", "(", "imspaths", "[", "i", "]", ")", "plt", ".", "imshow", "(", "img", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageModelResults.plot_val_with_title
Displays the images and their probabilities of belonging to a certain class Arguments: idxs (numpy.ndarray): indexes of the image samples from the dataset y (int): the selected class Returns: Plots the images in n rows [rows = n]
old/fastai/plots.py
def plot_val_with_title(self, idxs, y): """ Displays the images and their probabilities of belonging to a certain class Arguments: idxs (numpy.ndarray): indexes of the image samples from the dataset y (int): the selected class Returns: Plots the images in n rows [rows = n] """ # if there are any samples to be displayed if len(idxs) > 0: imgs = np.stack([self.ds[x][0] for x in idxs]) title_probs = [self.probs[x,y] for x in idxs] return plots(self.ds.denorm(imgs), rows=1, titles=title_probs) # if idxs is empty return false else: return False;
def plot_val_with_title(self, idxs, y): """ Displays the images and their probabilities of belonging to a certain class Arguments: idxs (numpy.ndarray): indexes of the image samples from the dataset y (int): the selected class Returns: Plots the images in n rows [rows = n] """ # if there are any samples to be displayed if len(idxs) > 0: imgs = np.stack([self.ds[x][0] for x in idxs]) title_probs = [self.probs[x,y] for x in idxs] return plots(self.ds.denorm(imgs), rows=1, titles=title_probs) # if idxs is empty return false else: return False;
[ "Displays", "the", "images", "and", "their", "probabilities", "of", "belonging", "to", "a", "certain", "class" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/plots.py#L99-L117
[ "def", "plot_val_with_title", "(", "self", ",", "idxs", ",", "y", ")", ":", "# if there are any samples to be displayed", "if", "len", "(", "idxs", ")", ">", "0", ":", "imgs", "=", "np", ".", "stack", "(", "[", "self", ".", "ds", "[", "x", "]", "[", "0", "]", "for", "x", "in", "idxs", "]", ")", "title_probs", "=", "[", "self", ".", "probs", "[", "x", ",", "y", "]", "for", "x", "in", "idxs", "]", "return", "plots", "(", "self", ".", "ds", ".", "denorm", "(", "imgs", ")", ",", "rows", "=", "1", ",", "titles", "=", "title_probs", ")", "# if idxs is empty return false", "else", ":", "return", "False" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageModelResults.most_by_mask
Extracts the first 4 most correct/incorrect indexes from the ordered list of probabilities Arguments: mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False everywhere else y (int): the selected class mult (int): sets the ordering; -1 descending, 1 ascending Returns: idxs (ndarray): An array of indexes of length 4
old/fastai/plots.py
def most_by_mask(self, mask, y, mult): """ Extracts the first 4 most correct/incorrect indexes from the ordered list of probabilities Arguments: mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False everywhere else y (int): the selected class mult (int): sets the ordering; -1 descending, 1 ascending Returns: idxs (ndarray): An array of indexes of length 4 """ idxs = np.where(mask)[0] cnt = min(4, len(idxs)) return idxs[np.argsort(mult * self.probs[idxs,y])[:cnt]]
def most_by_mask(self, mask, y, mult): """ Extracts the first 4 most correct/incorrect indexes from the ordered list of probabilities Arguments: mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False everywhere else y (int): the selected class mult (int): sets the ordering; -1 descending, 1 ascending Returns: idxs (ndarray): An array of indexes of length 4 """ idxs = np.where(mask)[0] cnt = min(4, len(idxs)) return idxs[np.argsort(mult * self.probs[idxs,y])[:cnt]]
[ "Extracts", "the", "first", "4", "most", "correct", "/", "incorrect", "indexes", "from", "the", "ordered", "list", "of", "probabilities" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/plots.py#L119-L132
[ "def", "most_by_mask", "(", "self", ",", "mask", ",", "y", ",", "mult", ")", ":", "idxs", "=", "np", ".", "where", "(", "mask", ")", "[", "0", "]", "cnt", "=", "min", "(", "4", ",", "len", "(", "idxs", ")", ")", "return", "idxs", "[", "np", ".", "argsort", "(", "mult", "*", "self", ".", "probs", "[", "idxs", ",", "y", "]", ")", "[", ":", "cnt", "]", "]" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageModelResults.most_uncertain_by_mask
Extracts the first 4 most uncertain indexes from the ordered list of probabilities Arguments: mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False everywhere else y (int): the selected class Returns: idxs (ndarray): An array of indexes of length 4
old/fastai/plots.py
def most_uncertain_by_mask(self, mask, y): """ Extracts the first 4 most uncertain indexes from the ordered list of probabilities Arguments: mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False everywhere else y (int): the selected class Returns: idxs (ndarray): An array of indexes of length 4 """ idxs = np.where(mask)[0] # the most uncertain samples will have abs(probs-1/num_classes) close to 0; return idxs[np.argsort(np.abs(self.probs[idxs,y]-(1/self.num_classes)))[:4]]
def most_uncertain_by_mask(self, mask, y): """ Extracts the first 4 most uncertain indexes from the ordered list of probabilities Arguments: mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False everywhere else y (int): the selected class Returns: idxs (ndarray): An array of indexes of length 4 """ idxs = np.where(mask)[0] # the most uncertain samples will have abs(probs-1/num_classes) close to 0; return idxs[np.argsort(np.abs(self.probs[idxs,y]-(1/self.num_classes)))[:4]]
[ "Extracts", "the", "first", "4", "most", "uncertain", "indexes", "from", "the", "ordered", "list", "of", "probabilities" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/plots.py#L134-L146
[ "def", "most_uncertain_by_mask", "(", "self", ",", "mask", ",", "y", ")", ":", "idxs", "=", "np", ".", "where", "(", "mask", ")", "[", "0", "]", "# the most uncertain samples will have abs(probs-1/num_classes) close to 0;", "return", "idxs", "[", "np", ".", "argsort", "(", "np", ".", "abs", "(", "self", ".", "probs", "[", "idxs", ",", "y", "]", "-", "(", "1", "/", "self", ".", "num_classes", ")", ")", ")", "[", ":", "4", "]", "]" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageModelResults.most_by_correct
Extracts the predicted classes which correspond to the selected class (y) and to the specific case (prediction is correct - is_true=True, prediction is wrong - is_true=False) Arguments: y (int): the selected class is_correct (boolean): a boolean flag (True, False) which specify the what to look for. Ex: True - most correct samples, False - most incorrect samples Returns: idxs (numpy.ndarray): An array of indexes (numpy.ndarray)
old/fastai/plots.py
def most_by_correct(self, y, is_correct): """ Extracts the predicted classes which correspond to the selected class (y) and to the specific case (prediction is correct - is_true=True, prediction is wrong - is_true=False) Arguments: y (int): the selected class is_correct (boolean): a boolean flag (True, False) which specify the what to look for. Ex: True - most correct samples, False - most incorrect samples Returns: idxs (numpy.ndarray): An array of indexes (numpy.ndarray) """ # mult=-1 when the is_correct flag is true -> when we want to display the most correct classes we will make a descending sorting (argsort) because we want that the biggest probabilities to be displayed first. # When is_correct is false, we want to display the most incorrect classes, so we want an ascending sorting since our interest is in the smallest probabilities. mult = -1 if is_correct==True else 1 return self.most_by_mask(((self.preds == self.ds.y)==is_correct) & (self.ds.y == y), y, mult)
def most_by_correct(self, y, is_correct): """ Extracts the predicted classes which correspond to the selected class (y) and to the specific case (prediction is correct - is_true=True, prediction is wrong - is_true=False) Arguments: y (int): the selected class is_correct (boolean): a boolean flag (True, False) which specify the what to look for. Ex: True - most correct samples, False - most incorrect samples Returns: idxs (numpy.ndarray): An array of indexes (numpy.ndarray) """ # mult=-1 when the is_correct flag is true -> when we want to display the most correct classes we will make a descending sorting (argsort) because we want that the biggest probabilities to be displayed first. # When is_correct is false, we want to display the most incorrect classes, so we want an ascending sorting since our interest is in the smallest probabilities. mult = -1 if is_correct==True else 1 return self.most_by_mask(((self.preds == self.ds.y)==is_correct) & (self.ds.y == y), y, mult)
[ "Extracts", "the", "predicted", "classes", "which", "correspond", "to", "the", "selected", "class", "(", "y", ")", "and", "to", "the", "specific", "case", "(", "prediction", "is", "correct", "-", "is_true", "=", "True", "prediction", "is", "wrong", "-", "is_true", "=", "False", ")" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/plots.py#L148-L162
[ "def", "most_by_correct", "(", "self", ",", "y", ",", "is_correct", ")", ":", "# mult=-1 when the is_correct flag is true -> when we want to display the most correct classes we will make a descending sorting (argsort) because we want that the biggest probabilities to be displayed first.", "# When is_correct is false, we want to display the most incorrect classes, so we want an ascending sorting since our interest is in the smallest probabilities.", "mult", "=", "-", "1", "if", "is_correct", "==", "True", "else", "1", "return", "self", ".", "most_by_mask", "(", "(", "(", "self", ".", "preds", "==", "self", ".", "ds", ".", "y", ")", "==", "is_correct", ")", "&", "(", "self", ".", "ds", ".", "y", "==", "y", ")", ",", "y", ",", "mult", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageModelResults.plot_by_correct
Plots the images which correspond to the selected class (y) and to the specific case (prediction is correct - is_true=True, prediction is wrong - is_true=False) Arguments: y (int): the selected class is_correct (boolean): a boolean flag (True, False) which specify the what to look for. Ex: True - most correct samples, False - most incorrect samples
old/fastai/plots.py
def plot_by_correct(self, y, is_correct): """ Plots the images which correspond to the selected class (y) and to the specific case (prediction is correct - is_true=True, prediction is wrong - is_true=False) Arguments: y (int): the selected class is_correct (boolean): a boolean flag (True, False) which specify the what to look for. Ex: True - most correct samples, False - most incorrect samples """ return self.plot_val_with_title(self.most_by_correct(y, is_correct), y)
def plot_by_correct(self, y, is_correct): """ Plots the images which correspond to the selected class (y) and to the specific case (prediction is correct - is_true=True, prediction is wrong - is_true=False) Arguments: y (int): the selected class is_correct (boolean): a boolean flag (True, False) which specify the what to look for. Ex: True - most correct samples, False - most incorrect samples """ return self.plot_val_with_title(self.most_by_correct(y, is_correct), y)
[ "Plots", "the", "images", "which", "correspond", "to", "the", "selected", "class", "(", "y", ")", "and", "to", "the", "specific", "case", "(", "prediction", "is", "correct", "-", "is_true", "=", "True", "prediction", "is", "wrong", "-", "is_true", "=", "False", ")" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/plots.py#L164-L171
[ "def", "plot_by_correct", "(", "self", ",", "y", ",", "is_correct", ")", ":", "return", "self", ".", "plot_val_with_title", "(", "self", ".", "most_by_correct", "(", "y", ",", "is_correct", ")", ",", "y", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
ImageModelResults.most_by_uncertain
Extracts the predicted classes which correspond to the selected class (y) and have probabilities nearest to 1/number_of_classes (eg. 0.5 for 2 classes, 0.33 for 3 classes) for the selected class. Arguments: y (int): the selected class Returns: idxs (numpy.ndarray): An array of indexes (numpy.ndarray)
old/fastai/plots.py
def most_by_uncertain(self, y): """ Extracts the predicted classes which correspond to the selected class (y) and have probabilities nearest to 1/number_of_classes (eg. 0.5 for 2 classes, 0.33 for 3 classes) for the selected class. Arguments: y (int): the selected class Returns: idxs (numpy.ndarray): An array of indexes (numpy.ndarray) """ return self.most_uncertain_by_mask((self.ds.y == y), y)
def most_by_uncertain(self, y): """ Extracts the predicted classes which correspond to the selected class (y) and have probabilities nearest to 1/number_of_classes (eg. 0.5 for 2 classes, 0.33 for 3 classes) for the selected class. Arguments: y (int): the selected class Returns: idxs (numpy.ndarray): An array of indexes (numpy.ndarray) """ return self.most_uncertain_by_mask((self.ds.y == y), y)
[ "Extracts", "the", "predicted", "classes", "which", "correspond", "to", "the", "selected", "class", "(", "y", ")", "and", "have", "probabilities", "nearest", "to", "1", "/", "number_of_classes", "(", "eg", ".", "0", ".", "5", "for", "2", "classes", "0", ".", "33", "for", "3", "classes", ")", "for", "the", "selected", "class", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/plots.py#L173-L182
[ "def", "most_by_uncertain", "(", "self", ",", "y", ")", ":", "return", "self", ".", "most_uncertain_by_mask", "(", "(", "self", ".", "ds", ".", "y", "==", "y", ")", ",", "y", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
main
PyTorch distributed training launch helper that spawns multiple distributed processes
fastai/launch.py
def main( gpus:Param("The GPUs to use for distributed training", str)='all', script:Param("Script to run", str, opt=False)='', args:Param("Args to pass to script", nargs='...', opt=False)='' ): "PyTorch distributed training launch helper that spawns multiple distributed processes" # Loosely based on torch.distributed.launch current_env = os.environ.copy() gpus = list(range(torch.cuda.device_count())) if gpus=='all' else list(gpus) current_env["WORLD_SIZE"] = str(len(gpus)) current_env["MASTER_ADDR"] = '127.0.0.1' current_env["MASTER_PORT"] = '29500' processes = [] for i,gpu in enumerate(gpus): current_env["RANK"] = str(i) cmd = [sys.executable, "-u", script, f"--gpu={gpu}"] + args process = subprocess.Popen(cmd, env=current_env) processes.append(process) for process in processes: process.wait()
def main( gpus:Param("The GPUs to use for distributed training", str)='all', script:Param("Script to run", str, opt=False)='', args:Param("Args to pass to script", nargs='...', opt=False)='' ): "PyTorch distributed training launch helper that spawns multiple distributed processes" # Loosely based on torch.distributed.launch current_env = os.environ.copy() gpus = list(range(torch.cuda.device_count())) if gpus=='all' else list(gpus) current_env["WORLD_SIZE"] = str(len(gpus)) current_env["MASTER_ADDR"] = '127.0.0.1' current_env["MASTER_PORT"] = '29500' processes = [] for i,gpu in enumerate(gpus): current_env["RANK"] = str(i) cmd = [sys.executable, "-u", script, f"--gpu={gpu}"] + args process = subprocess.Popen(cmd, env=current_env) processes.append(process) for process in processes: process.wait()
[ "PyTorch", "distributed", "training", "launch", "helper", "that", "spawns", "multiple", "distributed", "processes" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/launch.py#L5-L25
[ "def", "main", "(", "gpus", ":", "Param", "(", "\"The GPUs to use for distributed training\"", ",", "str", ")", "=", "'all'", ",", "script", ":", "Param", "(", "\"Script to run\"", ",", "str", ",", "opt", "=", "False", ")", "=", "''", ",", "args", ":", "Param", "(", "\"Args to pass to script\"", ",", "nargs", "=", "'...'", ",", "opt", "=", "False", ")", "=", "''", ")", ":", "# Loosely based on torch.distributed.launch", "current_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "gpus", "=", "list", "(", "range", "(", "torch", ".", "cuda", ".", "device_count", "(", ")", ")", ")", "if", "gpus", "==", "'all'", "else", "list", "(", "gpus", ")", "current_env", "[", "\"WORLD_SIZE\"", "]", "=", "str", "(", "len", "(", "gpus", ")", ")", "current_env", "[", "\"MASTER_ADDR\"", "]", "=", "'127.0.0.1'", "current_env", "[", "\"MASTER_PORT\"", "]", "=", "'29500'", "processes", "=", "[", "]", "for", "i", ",", "gpu", "in", "enumerate", "(", "gpus", ")", ":", "current_env", "[", "\"RANK\"", "]", "=", "str", "(", "i", ")", "cmd", "=", "[", "sys", ".", "executable", ",", "\"-u\"", ",", "script", ",", "f\"--gpu={gpu}\"", "]", "+", "args", "process", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "env", "=", "current_env", ")", "processes", ".", "append", "(", "process", ")", "for", "process", "in", "processes", ":", "process", ".", "wait", "(", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LossMetrics.on_train_begin
Add the metrics names to the `Recorder`.
fastai/callbacks/loss_metrics.py
def on_train_begin(self, **kwargs): "Add the metrics names to the `Recorder`." self.names = ifnone(self.learn.loss_func.metric_names, []) if not self.names: warn('LossMetrics requested but no loss_func.metric_names provided') self.learn.recorder.add_metric_names(self.names)
def on_train_begin(self, **kwargs): "Add the metrics names to the `Recorder`." self.names = ifnone(self.learn.loss_func.metric_names, []) if not self.names: warn('LossMetrics requested but no loss_func.metric_names provided') self.learn.recorder.add_metric_names(self.names)
[ "Add", "the", "metrics", "names", "to", "the", "Recorder", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/loss_metrics.py#L11-L15
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "names", "=", "ifnone", "(", "self", ".", "learn", ".", "loss_func", ".", "metric_names", ",", "[", "]", ")", "if", "not", "self", ".", "names", ":", "warn", "(", "'LossMetrics requested but no loss_func.metric_names provided'", ")", "self", ".", "learn", ".", "recorder", ".", "add_metric_names", "(", "self", ".", "names", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LossMetrics.on_epoch_begin
Initialize the metrics for this epoch.
fastai/callbacks/loss_metrics.py
def on_epoch_begin(self, **kwargs): "Initialize the metrics for this epoch." self.metrics = {name:0. for name in self.names} self.nums = 0
def on_epoch_begin(self, **kwargs): "Initialize the metrics for this epoch." self.metrics = {name:0. for name in self.names} self.nums = 0
[ "Initialize", "the", "metrics", "for", "this", "epoch", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/loss_metrics.py#L17-L20
[ "def", "on_epoch_begin", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "metrics", "=", "{", "name", ":", "0.", "for", "name", "in", "self", ".", "names", "}", "self", ".", "nums", "=", "0" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LossMetrics.on_batch_end
Update the metrics if not `train`
fastai/callbacks/loss_metrics.py
def on_batch_end(self, last_target, train, **kwargs): "Update the metrics if not `train`" if train: return bs = last_target.size(0) for name in self.names: self.metrics[name] += bs * self.learn.loss_func.metrics[name].detach().cpu() self.nums += bs
def on_batch_end(self, last_target, train, **kwargs): "Update the metrics if not `train`" if train: return bs = last_target.size(0) for name in self.names: self.metrics[name] += bs * self.learn.loss_func.metrics[name].detach().cpu() self.nums += bs
[ "Update", "the", "metrics", "if", "not", "train" ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/loss_metrics.py#L22-L28
[ "def", "on_batch_end", "(", "self", ",", "last_target", ",", "train", ",", "*", "*", "kwargs", ")", ":", "if", "train", ":", "return", "bs", "=", "last_target", ".", "size", "(", "0", ")", "for", "name", "in", "self", ".", "names", ":", "self", ".", "metrics", "[", "name", "]", "+=", "bs", "*", "self", ".", "learn", ".", "loss_func", ".", "metrics", "[", "name", "]", ".", "detach", "(", ")", ".", "cpu", "(", ")", "self", ".", "nums", "+=", "bs" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
LossMetrics.on_epoch_end
Finish the computation and sends the result to the Recorder.
fastai/callbacks/loss_metrics.py
def on_epoch_end(self, last_metrics, **kwargs): "Finish the computation and sends the result to the Recorder." if not self.nums: return metrics = [self.metrics[name]/self.nums for name in self.names] return {'last_metrics': last_metrics+metrics}
def on_epoch_end(self, last_metrics, **kwargs): "Finish the computation and sends the result to the Recorder." if not self.nums: return metrics = [self.metrics[name]/self.nums for name in self.names] return {'last_metrics': last_metrics+metrics}
[ "Finish", "the", "computation", "and", "sends", "the", "result", "to", "the", "Recorder", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/loss_metrics.py#L30-L34
[ "def", "on_epoch_end", "(", "self", ",", "last_metrics", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "nums", ":", "return", "metrics", "=", "[", "self", ".", "metrics", "[", "name", "]", "/", "self", ".", "nums", "for", "name", "in", "self", ".", "names", "]", "return", "{", "'last_metrics'", ":", "last_metrics", "+", "metrics", "}" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
CycleGANTrainer.on_train_begin
Create the various optimizers.
fastai/vision/cyclegan.py
def on_train_begin(self, **kwargs): "Create the various optimizers." self.G_A,self.G_B = self.learn.model.G_A,self.learn.model.G_B self.D_A,self.D_B = self.learn.model.D_A,self.learn.model.D_B self.crit = self.learn.loss_func.crit self.opt_G = self.learn.opt.new([nn.Sequential(*flatten_model(self.G_A), *flatten_model(self.G_B))]) self.opt_D_A = self.learn.opt.new([nn.Sequential(*flatten_model(self.D_A))]) self.opt_D_B = self.learn.opt.new([nn.Sequential(*flatten_model(self.D_B))]) self.learn.opt.opt = self.opt_G.opt self._set_trainable() self.names = ['idt_loss', 'gen_loss', 'cyc_loss', 'da_loss', 'db_loss'] self.learn.recorder.no_val=True self.learn.recorder.add_metric_names(self.names) self.smootheners = {n:SmoothenValue(0.98) for n in self.names}
def on_train_begin(self, **kwargs): "Create the various optimizers." self.G_A,self.G_B = self.learn.model.G_A,self.learn.model.G_B self.D_A,self.D_B = self.learn.model.D_A,self.learn.model.D_B self.crit = self.learn.loss_func.crit self.opt_G = self.learn.opt.new([nn.Sequential(*flatten_model(self.G_A), *flatten_model(self.G_B))]) self.opt_D_A = self.learn.opt.new([nn.Sequential(*flatten_model(self.D_A))]) self.opt_D_B = self.learn.opt.new([nn.Sequential(*flatten_model(self.D_B))]) self.learn.opt.opt = self.opt_G.opt self._set_trainable() self.names = ['idt_loss', 'gen_loss', 'cyc_loss', 'da_loss', 'db_loss'] self.learn.recorder.no_val=True self.learn.recorder.add_metric_names(self.names) self.smootheners = {n:SmoothenValue(0.98) for n in self.names}
[ "Create", "the", "various", "optimizers", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/cyclegan.py#L145-L158
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "G_A", ",", "self", ".", "G_B", "=", "self", ".", "learn", ".", "model", ".", "G_A", ",", "self", ".", "learn", ".", "model", ".", "G_B", "self", ".", "D_A", ",", "self", ".", "D_B", "=", "self", ".", "learn", ".", "model", ".", "D_A", ",", "self", ".", "learn", ".", "model", ".", "D_B", "self", ".", "crit", "=", "self", ".", "learn", ".", "loss_func", ".", "crit", "self", ".", "opt_G", "=", "self", ".", "learn", ".", "opt", ".", "new", "(", "[", "nn", ".", "Sequential", "(", "*", "flatten_model", "(", "self", ".", "G_A", ")", ",", "*", "flatten_model", "(", "self", ".", "G_B", ")", ")", "]", ")", "self", ".", "opt_D_A", "=", "self", ".", "learn", ".", "opt", ".", "new", "(", "[", "nn", ".", "Sequential", "(", "*", "flatten_model", "(", "self", ".", "D_A", ")", ")", "]", ")", "self", ".", "opt_D_B", "=", "self", ".", "learn", ".", "opt", ".", "new", "(", "[", "nn", ".", "Sequential", "(", "*", "flatten_model", "(", "self", ".", "D_B", ")", ")", "]", ")", "self", ".", "learn", ".", "opt", ".", "opt", "=", "self", ".", "opt_G", ".", "opt", "self", ".", "_set_trainable", "(", ")", "self", ".", "names", "=", "[", "'idt_loss'", ",", "'gen_loss'", ",", "'cyc_loss'", ",", "'da_loss'", ",", "'db_loss'", "]", "self", ".", "learn", ".", "recorder", ".", "no_val", "=", "True", "self", ".", "learn", ".", "recorder", ".", "add_metric_names", "(", "self", ".", "names", ")", "self", ".", "smootheners", "=", "{", "n", ":", "SmoothenValue", "(", "0.98", ")", "for", "n", "in", "self", ".", "names", "}" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67
train
CycleGANTrainer.on_batch_end
Steps through the generators then each of the critics.
fastai/vision/cyclegan.py
def on_batch_end(self, last_input, last_output, **kwargs): "Steps through the generators then each of the critics." self.G_A.zero_grad(); self.G_B.zero_grad() fake_A, fake_B = last_output[0].detach(), last_output[1].detach() real_A, real_B = last_input self._set_trainable(D_A=True) self.D_A.zero_grad() loss_D_A = 0.5 * (self.crit(self.D_A(real_A), True) + self.crit(self.D_A(fake_A), False)) loss_D_A.backward() self.opt_D_A.step() self._set_trainable(D_B=True) self.D_B.zero_grad() loss_D_B = 0.5 * (self.crit(self.D_B(real_B), True) + self.crit(self.D_B(fake_B), False)) loss_D_B.backward() self.opt_D_B.step() self._set_trainable() metrics = self.learn.loss_func.metrics + [loss_D_A, loss_D_B] for n,m in zip(self.names,metrics): self.smootheners[n].add_value(m)
def on_batch_end(self, last_input, last_output, **kwargs): "Steps through the generators then each of the critics." self.G_A.zero_grad(); self.G_B.zero_grad() fake_A, fake_B = last_output[0].detach(), last_output[1].detach() real_A, real_B = last_input self._set_trainable(D_A=True) self.D_A.zero_grad() loss_D_A = 0.5 * (self.crit(self.D_A(real_A), True) + self.crit(self.D_A(fake_A), False)) loss_D_A.backward() self.opt_D_A.step() self._set_trainable(D_B=True) self.D_B.zero_grad() loss_D_B = 0.5 * (self.crit(self.D_B(real_B), True) + self.crit(self.D_B(fake_B), False)) loss_D_B.backward() self.opt_D_B.step() self._set_trainable() metrics = self.learn.loss_func.metrics + [loss_D_A, loss_D_B] for n,m in zip(self.names,metrics): self.smootheners[n].add_value(m)
[ "Steps", "through", "the", "generators", "then", "each", "of", "the", "critics", "." ]
fastai/fastai
python
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/cyclegan.py#L164-L181
[ "def", "on_batch_end", "(", "self", ",", "last_input", ",", "last_output", ",", "*", "*", "kwargs", ")", ":", "self", ".", "G_A", ".", "zero_grad", "(", ")", "self", ".", "G_B", ".", "zero_grad", "(", ")", "fake_A", ",", "fake_B", "=", "last_output", "[", "0", "]", ".", "detach", "(", ")", ",", "last_output", "[", "1", "]", ".", "detach", "(", ")", "real_A", ",", "real_B", "=", "last_input", "self", ".", "_set_trainable", "(", "D_A", "=", "True", ")", "self", ".", "D_A", ".", "zero_grad", "(", ")", "loss_D_A", "=", "0.5", "*", "(", "self", ".", "crit", "(", "self", ".", "D_A", "(", "real_A", ")", ",", "True", ")", "+", "self", ".", "crit", "(", "self", ".", "D_A", "(", "fake_A", ")", ",", "False", ")", ")", "loss_D_A", ".", "backward", "(", ")", "self", ".", "opt_D_A", ".", "step", "(", ")", "self", ".", "_set_trainable", "(", "D_B", "=", "True", ")", "self", ".", "D_B", ".", "zero_grad", "(", ")", "loss_D_B", "=", "0.5", "*", "(", "self", ".", "crit", "(", "self", ".", "D_B", "(", "real_B", ")", ",", "True", ")", "+", "self", ".", "crit", "(", "self", ".", "D_B", "(", "fake_B", ")", ",", "False", ")", ")", "loss_D_B", ".", "backward", "(", ")", "self", ".", "opt_D_B", ".", "step", "(", ")", "self", ".", "_set_trainable", "(", ")", "metrics", "=", "self", ".", "learn", ".", "loss_func", ".", "metrics", "+", "[", "loss_D_A", ",", "loss_D_B", "]", "for", "n", ",", "m", "in", "zip", "(", "self", ".", "names", ",", "metrics", ")", ":", "self", ".", "smootheners", "[", "n", "]", ".", "add_value", "(", "m", ")" ]
9fb84a5cdefe5a766cdb792b8f5d8971737b7e67