Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
Bird.birdIsAlive
(self)
Método para verificar se o pássaro está vivo
Método para verificar se o pássaro está vivo
def birdIsAlive(self): """ Método para verificar se o pássaro está vivo """ return self.__isAlive
[ "def", "birdIsAlive", "(", "self", ")", ":", "return", "self", ".", "__isAlive" ]
[ 64, 4 ]
[ 69, 29 ]
python
en
['en', 'error', 'th']
False
Bird.checkCollision
(self)
Método para verificar se o pássaro ultrapassou a borda da janela ou colidiu com algo
Método para verificar se o pássaro ultrapassou a borda da janela ou colidiu com algo
def checkCollision(self): """ Método para verificar se o pássaro ultrapassou a borda da janela ou colidiu com algo """ # Recebe a posição do pássaro no background position = list(self.__canvas.bbox(self.__tag)) # Se o pássaro tiver ultrapassado a borda de baixo do backg...
[ "def", "checkCollision", "(", "self", ")", ":", "# Recebe a posição do pássaro no background", "position", "=", "list", "(", "self", ".", "__canvas", ".", "bbox", "(", "self", ".", "__tag", ")", ")", "# Se o pássaro tiver ultrapassado a borda de baixo do background, ele s...
[ 71, 4 ]
[ 111, 33 ]
python
en
['en', 'error', 'th']
False
Bird.getTag
(self)
Método para retornar a tag do pássaro
Método para retornar a tag do pássaro
def getTag(self): """ Método para retornar a tag do pássaro """ return self.__tag
[ "def", "getTag", "(", "self", ")", ":", "return", "self", ".", "__tag" ]
[ 113, 4 ]
[ 118, 25 ]
python
en
['en', 'error', 'th']
False
Bird.getPhotoImage
(image=None, image_path=None, width=None, height=None, closeAfter=False)
Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image (photoImage, new, original) @param image: Instância de PIL.Image.open @param image_path: Diretório da imagem @param width: Largura da imagem @param height: Altura da imag...
Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image (photoImage, new, original)
def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAfter=False): """ Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image (photoImage, new, original) @param image: Instância de PIL.Image.open @param image_p...
[ "def", "getPhotoImage", "(", "image", "=", "None", ",", "image_path", "=", "None", ",", "width", "=", "None", ",", "height", "=", "None", ",", "closeAfter", "=", "False", ")", ":", "if", "not", "image", ":", "if", "not", "image_path", ":", "return", ...
[ 121, 4 ]
[ 160, 42 ]
python
en
['en', 'error', 'th']
False
Bird.jumps
(self, event=None)
Método para fazer o pássaro pular
Método para fazer o pássaro pular
def jumps(self, event=None): """ Método para fazer o pássaro pular """ # Verifica se o pássaro saiu da área do background self.checkCollision() # Se o pássaro estiver morto, esse método não pode ser executado if not self.__isAlive or not self.__running: ...
[ "def", "jumps", "(", "self", ",", "event", "=", "None", ")", ":", "# Verifica se o pássaro saiu da área do background", "self", ".", "checkCollision", "(", ")", "# Se o pássaro estiver morto, esse método não pode ser executado", "if", "not", "self", ".", "__isAlive", "or"...
[ 162, 4 ]
[ 193, 36 ]
python
en
['en', 'error', 'th']
False
Bird.kill
(self)
Método para matar o pássaro
Método para matar o pássaro
def kill(self): """ Método para matar o pássaro """ self.__isAlive = False
[ "def", "kill", "(", "self", ")", ":", "self", ".", "__isAlive", "=", "False" ]
[ 195, 4 ]
[ 200, 30 ]
python
en
['en', 'error', 'th']
False
Bird.run
(self)
#Método para iniciar a animação do passáro caindo
#Método para iniciar a animação do passáro caindo
def run(self): """ #Método para iniciar a animação do passáro caindo """ self.__running = True # Verifica se o pássaro saiu da área do background self.checkCollision() # Enquanto o pássaro não tiver chegado em sua velocidade máxima, a velocidade aumentará em 0....
[ "def", "run", "(", "self", ")", ":", "self", ".", "__running", "=", "True", "# Verifica se o pássaro saiu da área do background", "self", ".", "checkCollision", "(", ")", "# Enquanto o pássaro não tiver chegado em sua velocidade máxima, a velocidade aumentará em 0.05", "if", "s...
[ 202, 4 ]
[ 230, 34 ]
python
en
['en', 'error', 'th']
False
empty
(shape, dtype=None, order='C')
Return a new matrix of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int Shape of the empty matrix. dtype : data-type, optional Desired output data-type. order : {'C', 'F'}, optional Whether to store multi-dimensional data ...
Return a new matrix of given shape and type, without initializing entries.
def empty(shape, dtype=None, order='C'): """Return a new matrix of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int Shape of the empty matrix. dtype : data-type, optional Desired output data-type. order : {'C', 'F'}, optional ...
[ "def", "empty", "(", "shape", ",", "dtype", "=", "None", ",", "order", "=", "'C'", ")", ":", "return", "ndarray", ".", "__new__", "(", "matrix", ",", "shape", ",", "dtype", ",", "order", "=", "order", ")" ]
[ 12, 0 ]
[ 48, 61 ]
python
en
['en', 'en', 'en']
True
ones
(shape, dtype=None, order='C')
Matrix of ones. Return a matrix of given shape and type, filled with ones. Parameters ---------- shape : {sequence of ints, int} Shape of the matrix dtype : data-type, optional The desired data-type for the matrix, default is np.float64. order : {'C', 'F'}, optional ...
Matrix of ones.
def ones(shape, dtype=None, order='C'): """ Matrix of ones. Return a matrix of given shape and type, filled with ones. Parameters ---------- shape : {sequence of ints, int} Shape of the matrix dtype : data-type, optional The desired data-type for the matrix, default is np.f...
[ "def", "ones", "(", "shape", ",", "dtype", "=", "None", ",", "order", "=", "'C'", ")", ":", "a", "=", "ndarray", ".", "__new__", "(", "matrix", ",", "shape", ",", "dtype", ",", "order", "=", "order", ")", "a", ".", "fill", "(", "1", ")", "retur...
[ 50, 0 ]
[ 93, 12 ]
python
en
['en', 'error', 'th']
False
zeros
(shape, dtype=None, order='C')
Return a matrix of given shape and type, filled with zeros. Parameters ---------- shape : int or sequence of ints Shape of the matrix dtype : data-type, optional The desired data-type for the matrix, default is float. order : {'C', 'F'}, optional Whether to store the re...
Return a matrix of given shape and type, filled with zeros.
def zeros(shape, dtype=None, order='C'): """ Return a matrix of given shape and type, filled with zeros. Parameters ---------- shape : int or sequence of ints Shape of the matrix dtype : data-type, optional The desired data-type for the matrix, default is float. order : {'C'...
[ "def", "zeros", "(", "shape", ",", "dtype", "=", "None", ",", "order", "=", "'C'", ")", ":", "a", "=", "ndarray", ".", "__new__", "(", "matrix", ",", "shape", ",", "dtype", ",", "order", "=", "order", ")", "a", ".", "fill", "(", "0", ")", "retu...
[ 95, 0 ]
[ 137, 12 ]
python
en
['en', 'error', 'th']
False
identity
(n,dtype=None)
Returns the square identity matrix of given size. Parameters ---------- n : int Size of the returned identity matrix. dtype : data-type, optional Data-type of the output. Defaults to ``float``. Returns ------- out : matrix `n` x `n` matrix with its main diagona...
Returns the square identity matrix of given size.
def identity(n,dtype=None): """ Returns the square identity matrix of given size. Parameters ---------- n : int Size of the returned identity matrix. dtype : data-type, optional Data-type of the output. Defaults to ``float``. Returns ------- out : matrix `n`...
[ "def", "identity", "(", "n", ",", "dtype", "=", "None", ")", ":", "a", "=", "array", "(", "[", "1", "]", "+", "n", "*", "[", "0", "]", ",", "dtype", "=", "dtype", ")", "b", "=", "empty", "(", "(", "n", ",", "n", ")", ",", "dtype", "=", ...
[ 139, 0 ]
[ 173, 12 ]
python
en
['en', 'error', 'th']
False
eye
(n,M=None, k=0, dtype=float, order='C')
Return a matrix with ones on the diagonal and zeros elsewhere. Parameters ---------- n : int Number of rows in the output. M : int, optional Number of columns in the output, defaults to `n`. k : int, optional Index of the diagonal: 0 refers to the main diagonal, ...
Return a matrix with ones on the diagonal and zeros elsewhere.
def eye(n,M=None, k=0, dtype=float, order='C'): """ Return a matrix with ones on the diagonal and zeros elsewhere. Parameters ---------- n : int Number of rows in the output. M : int, optional Number of columns in the output, defaults to `n`. k : int, optional Index ...
[ "def", "eye", "(", "n", ",", "M", "=", "None", ",", "k", "=", "0", ",", "dtype", "=", "float", ",", "order", "=", "'C'", ")", ":", "return", "asmatrix", "(", "np", ".", "eye", "(", "n", ",", "M", "=", "M", ",", "k", "=", "k", ",", "dtype"...
[ 175, 0 ]
[ 217, 66 ]
python
en
['en', 'error', 'th']
False
rand
(*args)
Return a matrix of random values with given shape. Create a matrix of the given shape and propagate it with random samples from a uniform distribution over ``[0, 1)``. Parameters ---------- \\*args : Arguments Shape of the output. If given as N integers, each integer specifies...
Return a matrix of random values with given shape.
def rand(*args): """ Return a matrix of random values with given shape. Create a matrix of the given shape and propagate it with random samples from a uniform distribution over ``[0, 1)``. Parameters ---------- \\*args : Arguments Shape of the output. If given as N integers...
[ "def", "rand", "(", "*", "args", ")", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "tuple", ")", ":", "args", "=", "args", "[", "0", "]", "return", "asmatrix", "(", "np", ".", "random", ".", "rand", "(", "*", "args", ")", ")" ]
[ 219, 0 ]
[ 263, 42 ]
python
en
['en', 'error', 'th']
False
randn
(*args)
Return a random matrix with data from the "standard normal" distribution. `randn` generates a matrix filled with random floats sampled from a univariate "normal" (Gaussian) distribution of mean 0 and variance 1. Parameters ---------- \\*args : Arguments Shape of the output. If...
Return a random matrix with data from the "standard normal" distribution.
def randn(*args): """ Return a random matrix with data from the "standard normal" distribution. `randn` generates a matrix filled with random floats sampled from a univariate "normal" (Gaussian) distribution of mean 0 and variance 1. Parameters ---------- \\*args : Arguments Shape ...
[ "def", "randn", "(", "*", "args", ")", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "tuple", ")", ":", "args", "=", "args", "[", "0", "]", "return", "asmatrix", "(", "np", ".", "random", ".", "randn", "(", "*", "args", ")", ")" ]
[ 265, 0 ]
[ 314, 43 ]
python
en
['en', 'error', 'th']
False
repmat
(a, m, n)
Repeat a 0-D to 2-D array or matrix MxN times. Parameters ---------- a : array_like The array or matrix to be repeated. m, n : int The number of times `a` is repeated along the first and second axes. Returns ------- out : ndarray The result of repeating `a`. ...
Repeat a 0-D to 2-D array or matrix MxN times.
def repmat(a, m, n): """ Repeat a 0-D to 2-D array or matrix MxN times. Parameters ---------- a : array_like The array or matrix to be repeated. m, n : int The number of times `a` is repeated along the first and second axes. Returns ------- out : ndarray The...
[ "def", "repmat", "(", "a", ",", "m", ",", "n", ")", ":", "a", "=", "asanyarray", "(", "a", ")", "ndim", "=", "a", ".", "ndim", "if", "ndim", "==", "0", ":", "origrows", ",", "origcols", "=", "(", "1", ",", "1", ")", "elif", "ndim", "==", "1...
[ 316, 0 ]
[ 364, 32 ]
python
en
['en', 'error', 'th']
False
BaseFinetuning.flatten_modules
(modules: Union[Module, Iterable[Union[Module, Iterable]]])
This function is used to flatten a module or an iterable of modules into a list of its modules. Args: modules: A given module or an iterable of modules Returns: List of modules
This function is used to flatten a module or an iterable of modules into a list of its modules.
def flatten_modules(modules: Union[Module, Iterable[Union[Module, Iterable]]]) -> List[Module]: """ This function is used to flatten a module or an iterable of modules into a list of its modules. Args: modules: A given module or an iterable of modules Returns: L...
[ "def", "flatten_modules", "(", "modules", ":", "Union", "[", "Module", ",", "Iterable", "[", "Union", "[", "Module", ",", "Iterable", "]", "]", "]", ")", "->", "List", "[", "Module", "]", ":", "if", "isinstance", "(", "modules", ",", "Iterable", ")", ...
[ 84, 4 ]
[ 106, 9 ]
python
en
['en', 'error', 'th']
False
BaseFinetuning.filter_params
( modules: Union[Module, Iterable[Union[Module, Iterable]]], train_bn: bool = True, requires_grad: bool = True )
Yields the `requires_grad` parameters of a given module or list of modules. Args: modules: A given module or an iterable of modules train_bn: Whether to train BatchNorm module requires_grad: Whether to create a generator for trainable or non-trainable parameters. Re...
Yields the `requires_grad` parameters of a given module or list of modules.
def filter_params( modules: Union[Module, Iterable[Union[Module, Iterable]]], train_bn: bool = True, requires_grad: bool = True ) -> Generator: """Yields the `requires_grad` parameters of a given module or list of modules. Args: modules: A given module or an iter...
[ "def", "filter_params", "(", "modules", ":", "Union", "[", "Module", ",", "Iterable", "[", "Union", "[", "Module", ",", "Iterable", "]", "]", "]", ",", "train_bn", ":", "bool", "=", "True", ",", "requires_grad", ":", "bool", "=", "True", ")", "->", "...
[ 109, 4 ]
[ 130, 31 ]
python
en
['en', 'en', 'en']
True
BaseFinetuning.make_trainable
(modules: Union[Module, Iterable[Union[Module, Iterable]]])
Unfreezes the parameters of the provided modules Args: modules: A given module or an iterable of modules
Unfreezes the parameters of the provided modules
def make_trainable(modules: Union[Module, Iterable[Union[Module, Iterable]]]) -> None: """ Unfreezes the parameters of the provided modules Args: modules: A given module or an iterable of modules """ modules = BaseFinetuning.flatten_modules(modules) for modul...
[ "def", "make_trainable", "(", "modules", ":", "Union", "[", "Module", ",", "Iterable", "[", "Union", "[", "Module", ",", "Iterable", "]", "]", "]", ")", "->", "None", ":", "modules", "=", "BaseFinetuning", ".", "flatten_modules", "(", "modules", ")", "fo...
[ 133, 4 ]
[ 143, 42 ]
python
en
['en', 'error', 'th']
False
BaseFinetuning.freeze
(modules: Union[Module, Iterable[Union[Module, Iterable]]], train_bn: bool = True)
Freezes the parameters of the provided modules Args: modules: A given module or an iterable of modules train_bn: If True, leave the BatchNorm layers in training mode Returns: None
Freezes the parameters of the provided modules
def freeze(modules: Union[Module, Iterable[Union[Module, Iterable]]], train_bn: bool = True) -> None: """ Freezes the parameters of the provided modules Args: modules: A given module or an iterable of modules train_bn: If True, leave the BatchNorm layers in training mode...
[ "def", "freeze", "(", "modules", ":", "Union", "[", "Module", ",", "Iterable", "[", "Union", "[", "Module", ",", "Iterable", "]", "]", "]", ",", "train_bn", ":", "bool", "=", "True", ")", "->", "None", ":", "modules", "=", "BaseFinetuning", ".", "fla...
[ 146, 4 ]
[ 163, 47 ]
python
en
['en', 'error', 'th']
False
BaseFinetuning.filter_on_optimizer
(optimizer: Optimizer, params: Iterable)
This function is used to exclude any parameter which already exists in this optimizer Args: optimizer: Optimizer used for parameter exclusion params: Iterable of parameters used to check against the provided optimizer Returns: List of parameters not...
This function is used to exclude any parameter which already exists in this optimizer
def filter_on_optimizer(optimizer: Optimizer, params: Iterable) -> List: """ This function is used to exclude any parameter which already exists in this optimizer Args: optimizer: Optimizer used for parameter exclusion params: Iterable of parameters used to check...
[ "def", "filter_on_optimizer", "(", "optimizer", ":", "Optimizer", ",", "params", ":", "Iterable", ")", "->", "List", ":", "out_params", "=", "[", "]", "removed_params", "=", "[", "]", "for", "param", "in", "params", ":", "if", "not", "any", "(", "torch",...
[ 166, 4 ]
[ 193, 25 ]
python
en
['en', 'error', 'th']
False
BaseFinetuning.unfreeze_and_add_param_group
( modules: Union[Module, Iterable[Union[Module, Iterable]]], optimizer: Optimizer, lr: Optional[float] = None, initial_denom_lr: float = 10., train_bn: bool = True, )
Unfreezes a module and adds its parameters to an optimizer. Args: modules: A module or iterable of modules to unfreeze. Their parameters will be added to an optimizer as a new param group. optimizer: The provided optimizer will receive new parameters and will ...
Unfreezes a module and adds its parameters to an optimizer.
def unfreeze_and_add_param_group( modules: Union[Module, Iterable[Union[Module, Iterable]]], optimizer: Optimizer, lr: Optional[float] = None, initial_denom_lr: float = 10., train_bn: bool = True, ) -> None: """ Unfreezes a module and adds its parameters to an...
[ "def", "unfreeze_and_add_param_group", "(", "modules", ":", "Union", "[", "Module", ",", "Iterable", "[", "Union", "[", "Module", ",", "Iterable", "]", "]", "]", ",", "optimizer", ":", "Optimizer", ",", "lr", ":", "Optional", "[", "float", "]", "=", "Non...
[ 196, 4 ]
[ 233, 14 ]
python
en
['en', 'error', 'th']
False
BaseFinetuning.on_train_epoch_start
(self, trainer, pl_module)
Called when the epoch begins.
Called when the epoch begins.
def on_train_epoch_start(self, trainer, pl_module): """Called when the epoch begins.""" for opt_idx, optimizer in trainer.train_loop.prepare_optimizers(): self.finetune_function(pl_module, trainer.current_epoch, optimizer, opt_idx)
[ "def", "on_train_epoch_start", "(", "self", ",", "trainer", ",", "pl_module", ")", ":", "for", "opt_idx", ",", "optimizer", "in", "trainer", ".", "train_loop", ".", "prepare_optimizers", "(", ")", ":", "self", ".", "finetune_function", "(", "pl_module", ",", ...
[ 238, 4 ]
[ 241, 88 ]
python
en
['en', 'de', 'en']
True
BaseFinetuning.finetune_function
(self, pl_module: LightningModule, epoch: int, optimizer: Optimizer, opt_idx: int)
Override to add your unfreeze logic
Override to add your unfreeze logic
def finetune_function(self, pl_module: LightningModule, epoch: int, optimizer: Optimizer, opt_idx: int): """ Override to add your unfreeze logic """ raise NotImplementedError
[ "def", "finetune_function", "(", "self", ",", "pl_module", ":", "LightningModule", ",", "epoch", ":", "int", ",", "optimizer", ":", "Optimizer", ",", "opt_idx", ":", "int", ")", ":", "raise", "NotImplementedError" ]
[ 243, 4 ]
[ 247, 33 ]
python
en
['en', 'error', 'th']
False
BaseFinetuning.freeze_before_training
(self, pl_module: LightningModule)
Override to add your freeze logic
Override to add your freeze logic
def freeze_before_training(self, pl_module: LightningModule): """ Override to add your freeze logic """ raise NotImplementedError
[ "def", "freeze_before_training", "(", "self", ",", "pl_module", ":", "LightningModule", ")", ":", "raise", "NotImplementedError" ]
[ 249, 4 ]
[ 253, 33 ]
python
en
['en', 'error', 'th']
False
BackboneFinetuning.on_fit_start
(self, trainer, pl_module)
Raises: MisconfigurationException: If LightningModule has no nn.Module `backbone` attribute.
Raises: MisconfigurationException: If LightningModule has no nn.Module `backbone` attribute.
def on_fit_start(self, trainer, pl_module): """ Raises: MisconfigurationException: If LightningModule has no nn.Module `backbone` attribute. """ if hasattr(pl_module, "backbone") and isinstance(pl_module.backbone, Module): return raise Misc...
[ "def", "on_fit_start", "(", "self", ",", "trainer", ",", "pl_module", ")", ":", "if", "hasattr", "(", "pl_module", ",", "\"backbone\"", ")", "and", "isinstance", "(", "pl_module", ".", "backbone", ",", "Module", ")", ":", "return", "raise", "Misconfiguration...
[ 319, 4 ]
[ 327, 107 ]
python
en
['en', 'error', 'th']
False
BackboneFinetuning.finetune_function
(self, pl_module: LightningModule, epoch: int, optimizer: Optimizer, opt_idx: int)
Called when the epoch begins.
Called when the epoch begins.
def finetune_function(self, pl_module: LightningModule, epoch: int, optimizer: Optimizer, opt_idx: int): """Called when the epoch begins.""" if epoch == self.unfreeze_backbone_at_epoch: current_lr = optimizer.param_groups[0]['lr'] initial_backbone_lr = self.backbone_initial_lr i...
[ "def", "finetune_function", "(", "self", ",", "pl_module", ":", "LightningModule", ",", "epoch", ":", "int", ",", "optimizer", ":", "Optimizer", ",", "opt_idx", ":", "int", ")", ":", "if", "epoch", "==", "self", ".", "unfreeze_backbone_at_epoch", ":", "curre...
[ 332, 4 ]
[ 364, 17 ]
python
en
['en', 'de', 'en']
True
PythonChecker.recurse
(self)
Flag to determine whether to apply checks recursively
Flag to determine whether to apply checks recursively
def recurse(self) -> bool: """Flag to determine whether to apply checks recursively""" return self.args.recurse
[ "def", "recurse", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "args", ".", "recurse" ]
[ 54, 4 ]
[ 56, 32 ]
python
en
['en', 'el-Latn', 'en']
True
PythonChecker.check_flake8
(self)
Run flake8 on files and/or repo
Run flake8 on files and/or repo
def check_flake8(self) -> None: """Run flake8 on files and/or repo""" errors = [] with utils.buffered(stdout=errors, mangle=self._strip_lines): self.flake8_app.run_checks() self.flake8_app.report() if errors: self.error("flake8", errors)
[ "def", "check_flake8", "(", "self", ")", "->", "None", ":", "errors", "=", "[", "]", "with", "utils", ".", "buffered", "(", "stdout", "=", "errors", ",", "mangle", "=", "self", ".", "_strip_lines", ")", ":", "self", ".", "flake8_app", ".", "run_checks"...
[ 80, 4 ]
[ 87, 40 ]
python
en
['en', 'en', 'en']
True
PythonChecker.check_yapf
(self)
Run flake8 on files and/or repo
Run flake8 on files and/or repo
def check_yapf(self) -> None: """Run flake8 on files and/or repo""" for python_file in self.yapf_files: self.yapf_run(python_file)
[ "def", "check_yapf", "(", "self", ")", "->", "None", ":", "for", "python_file", "in", "self", ".", "yapf_files", ":", "self", ".", "yapf_run", "(", "python_file", ")" ]
[ 89, 4 ]
[ 92, 38 ]
python
en
['en', 'en', 'en']
True
get_warp_matrix
(theta, size_input, size_dst, size_target)
Calculate the transformation matrix under the constraint of unbiased. Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020). Args: theta (float): Rotation angle in degrees. size_input (np.ndarray): Size of input imag...
Calculate the transformation matrix under the constraint of unbiased. Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020).
def get_warp_matrix(theta, size_input, size_dst, size_target): """Calculate the transformation matrix under the constraint of unbiased. Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020). Args: theta (float): Rotation...
[ "def", "get_warp_matrix", "(", "theta", ",", "size_input", ",", "size_dst", ",", "size_target", ")", ":", "theta", "=", "np", ".", "deg2rad", "(", "theta", ")", "matrix", "=", "np", ".", "zeros", "(", "(", "2", ",", "3", ")", ",", "dtype", "=", "np...
[ 10, 0 ]
[ 38, 17 ]
python
en
['en', 'en', 'en']
True
warp_affine_joints
(joints, mat)
Apply affine transformation defined by the transform matrix on the joints. Args: joints (np.ndarray[..., 2]): Origin coordinate of joints. mat (np.ndarray[3, 2]): The affine matrix. Returns: matrix (np.ndarray[..., 2]): Result coordinate of joints.
Apply affine transformation defined by the transform matrix on the joints.
def warp_affine_joints(joints, mat): """Apply affine transformation defined by the transform matrix on the joints. Args: joints (np.ndarray[..., 2]): Origin coordinate of joints. mat (np.ndarray[3, 2]): The affine matrix. Returns: matrix (np.ndarray[..., 2]): Result coordinate ...
[ "def", "warp_affine_joints", "(", "joints", ",", "mat", ")", ":", "joints", "=", "np", ".", "array", "(", "joints", ")", "shape", "=", "joints", ".", "shape", "joints", "=", "joints", ".", "reshape", "(", "-", "1", ",", "2", ")", "return", "np", "....
[ 41, 0 ]
[ 57, 29 ]
python
en
['en', 'en', 'en']
True
_ceil_to_multiples_of
(x, base=64)
Transform x to the integral multiple of the base.
Transform x to the integral multiple of the base.
def _ceil_to_multiples_of(x, base=64): """Transform x to the integral multiple of the base.""" return int(np.ceil(x / base)) * base
[ "def", "_ceil_to_multiples_of", "(", "x", ",", "base", "=", "64", ")", ":", "return", "int", "(", "np", ".", "ceil", "(", "x", "/", "base", ")", ")", "*", "base" ]
[ 60, 0 ]
[ 62, 40 ]
python
en
['en', 'en', 'en']
True
_get_multi_scale_size
(image, input_size, current_scale, min_scale, use_udp=False)
Get the size for multi-scale training. Args: image: Input image. input_size (int): Size of the image input. current_scale (float): Scale factor. min_scale (float): Minimal scale. use_udp (bool): To use unbiased data processing. Paper ref: Huang et al. The Devil i...
Get the size for multi-scale training.
def _get_multi_scale_size(image, input_size, current_scale, min_scale, use_udp=False): """Get the size for multi-scale training. Args: image: Input image. input_size (int): Size of the image ...
[ "def", "_get_multi_scale_size", "(", "image", ",", "input_size", ",", "current_scale", ",", "min_scale", ",", "use_udp", "=", "False", ")", ":", "h", ",", "w", ",", "_", "=", "image", ".", "shape", "# calculate the size for min_scale", "min_input_size", "=", "...
[ 65, 0 ]
[ 118, 71 ]
python
en
['en', 'en', 'en']
True
_resize_align_multi_scale
(image, input_size, current_scale, min_scale)
Resize the images for multi-scale training. Args: image: Input image input_size (int): Size of the image input current_scale (float): Current scale min_scale (float): Minimal scale Returns: tuple: A tuple containing image info. - image_resized (tuple): size of ...
Resize the images for multi-scale training.
def _resize_align_multi_scale(image, input_size, current_scale, min_scale): """Resize the images for multi-scale training. Args: image: Input image input_size (int): Size of the image input current_scale (float): Current scale min_scale (float): Minimal scale Returns: ...
[ "def", "_resize_align_multi_scale", "(", "image", ",", "input_size", ",", "current_scale", ",", "min_scale", ")", ":", "size_resized", ",", "center", ",", "scale", "=", "_get_multi_scale_size", "(", "image", ",", "input_size", ",", "current_scale", ",", "min_scale...
[ 121, 0 ]
[ 143, 39 ]
python
en
['en', 'en', 'en']
True
_resize_align_multi_scale_udp
(image, input_size, current_scale, min_scale)
Resize the images for multi-scale training. Args: image: Input image input_size (int): Size of the image input current_scale (float): Current scale min_scale (float): Minimal scale Returns: tuple: A tuple containing image info. - image_resized (tuple): size of ...
Resize the images for multi-scale training.
def _resize_align_multi_scale_udp(image, input_size, current_scale, min_scale): """Resize the images for multi-scale training. Args: image: Input image input_size (int): Size of the image input current_scale (float): Current scale min_scale (float): Minimal scale Returns: ...
[ "def", "_resize_align_multi_scale_udp", "(", "image", ",", "input_size", ",", "current_scale", ",", "min_scale", ")", ":", "size_resized", ",", "_", ",", "_", "=", "_get_multi_scale_size", "(", "image", ",", "input_size", ",", "current_scale", ",", "min_scale", ...
[ 146, 0 ]
[ 176, 39 ]
python
en
['en', 'en', 'en']
True
HeatmapGenerator.__call__
(self, joints)
Generate heatmaps.
Generate heatmaps.
def __call__(self, joints): """Generate heatmaps.""" hms = np.zeros((self.num_joints, self.output_res, self.output_res), dtype=np.float32) sigma = self.sigma for p in joints: for idx, pt in enumerate(p): if pt[2] > 0: ...
[ "def", "__call__", "(", "self", ",", "joints", ")", ":", "hms", "=", "np", ".", "zeros", "(", "(", "self", ".", "num_joints", ",", "self", ".", "output_res", ",", "self", ".", "output_res", ")", ",", "dtype", "=", "np", ".", "float32", ")", "sigma"...
[ 208, 4 ]
[ 242, 18 ]
python
en
['en', 'fy', 'en']
False
JointsEncoder.__call__
(self, joints)
Note: number of people in image: N number of keypoints: K max number of people in an image: M Args: joints (np.ndarray[NxKx3]) Returns: visible_kpts (np.ndarray[MxKx2]).
Note: number of people in image: N number of keypoints: K max number of people in an image: M
def __call__(self, joints): """ Note: number of people in image: N number of keypoints: K max number of people in an image: M Args: joints (np.ndarray[NxKx3]) Returns: visible_kpts (np.ndarray[MxKx2]). """ visi...
[ "def", "__call__", "(", "self", ",", "joints", ")", ":", "visible_kpts", "=", "np", ".", "zeros", "(", "(", "self", ".", "max_num_people", ",", "self", ".", "num_joints", ",", "2", ")", ",", "dtype", "=", "np", ".", "float32", ")", "output_res", "=",...
[ 264, 4 ]
[ 292, 27 ]
python
en
['en', 'error', 'th']
False
test_join_matches_subprocess
(Parser, runner, argv)
Test that join produces strings understood by subprocess
Test that join produces strings understood by subprocess
def test_join_matches_subprocess(Parser, runner, argv): """ Test that join produces strings understood by subprocess """ # invoke python to return its arguments as json cmd = [ sys.executable, '-c', 'import json, sys; print(json.dumps(sys.argv[1:]))' ] joined = Parser.join(cm...
[ "def", "test_join_matches_subprocess", "(", "Parser", ",", "runner", ",", "argv", ")", ":", "# invoke python to return its arguments as json", "cmd", "=", "[", "sys", ".", "executable", ",", "'-c'", ",", "'import json, sys; print(json.dumps(sys.argv[1:]))'", "]", "joined"...
[ 55, 0 ]
[ 66, 39 ]
python
en
['en', 'error', 'th']
False
test_roundtrip
(Parser, argv)
Test that split is the inverse operation of join
Test that split is the inverse operation of join
def test_roundtrip(Parser, argv): """ Test that split is the inverse operation of join """ try: joined = Parser.join(argv) assert argv == Parser.split(joined) except NotImplementedError: pytest.skip("Not implemented")
[ "def", "test_roundtrip", "(", "Parser", ",", "argv", ")", ":", "try", ":", "joined", "=", "Parser", ".", "join", "(", "argv", ")", "assert", "argv", "==", "Parser", ".", "split", "(", "joined", ")", "except", "NotImplementedError", ":", "pytest", ".", ...
[ 70, 0 ]
[ 78, 38 ]
python
en
['en', 'error', 'th']
False
pythonlib_dir
()
return path where libpython* is.
return path where libpython* is.
def pythonlib_dir(): """return path where libpython* is.""" if sys.platform == 'win32': return os.path.join(sys.prefix, "libs") else: return get_config_var('LIBDIR')
[ "def", "pythonlib_dir", "(", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "return", "os", ".", "path", ".", "join", "(", "sys", ".", "prefix", ",", "\"libs\"", ")", "else", ":", "return", "get_config_var", "(", "'LIBDIR'", ")" ]
[ 74, 0 ]
[ 79, 39 ]
python
en
['en', 'gd', 'en']
True
is_npy_no_signal
()
Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header.
Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header.
def is_npy_no_signal(): """Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header.""" return sys.platform == 'win32'
[ "def", "is_npy_no_signal", "(", ")", ":", "return", "sys", ".", "platform", "==", "'win32'" ]
[ 81, 0 ]
[ 84, 34 ]
python
en
['en', 'en', 'en']
True
is_npy_no_smp
()
Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled).
Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled).
def is_npy_no_smp(): """Return True if the NPY_NO_SMP symbol must be defined in public header (when SMP support cannot be reliably enabled).""" # Perhaps a fancier check is in order here. # so that threads are only enabled if there # are actually multiple CPUS? -- but # threaded code can be n...
[ "def", "is_npy_no_smp", "(", ")", ":", "# Perhaps a fancier check is in order here.", "# so that threads are only enabled if there", "# are actually multiple CPUS? -- but", "# threaded code can be nice even on a single", "# CPU so that long-calculating code doesn't", "# block.", "return",...
[ 86, 0 ]
[ 95, 36 ]
python
en
['en', 'en', 'en']
True
visibility_define
(config)
Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty string).
Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty string).
def visibility_define(config): """Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty string).""" hide = '__attribute__((visibility("hidden")))' if config.check_gcc_function_attribute(hide, 'hideme'): return hide else: return ''
[ "def", "visibility_define", "(", "config", ")", ":", "hide", "=", "'__attribute__((visibility(\"hidden\")))'", "if", "config", ".", "check_gcc_function_attribute", "(", "hide", ",", "'hideme'", ")", ":", "return", "hide", "else", ":", "return", "''" ]
[ 391, 0 ]
[ 398, 17 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.__init__
(self, logger=False, sample_period=0.05, log_directory = 'logs', logfile_name = None )
Constructor
Constructor
def __init__(self, logger=False, sample_period=0.05, log_directory = 'logs', logfile_name = None ): """Constructor """ self._logger = logger or logging.getLogger(__name__) self._tx_log_filename = os.path...
[ "def", "__init__", "(", "self", ",", "logger", "=", "False", ",", "sample_period", "=", "0.05", ",", "log_directory", "=", "'logs'", ",", "logfile_name", "=", "None", ")", ":", "self", ".", "_logger", "=", "logger", "or", "logging", ".", "getLogger", "("...
[ 61, 4 ]
[ 81, 65 ]
python
en
['en', 'en', 'pt']
False
ADP_Conn.set_adp_tx_callbacks
(self, callbacks)
Set callback functions to call when ADP transaction of specific names are received via ADP
Set callback functions to call when ADP transaction of specific names are received via ADP
def set_adp_tx_callbacks(self, callbacks): """Set callback functions to call when ADP transaction of specific names are received via ADP """ self._read_buffer.set_adp_tx_callbacks(callbacks)
[ "def", "set_adp_tx_callbacks", "(", "self", ",", "callbacks", ")", ":", "self", ".", "_read_buffer", ".", "set_adp_tx_callbacks", "(", "callbacks", ")" ]
[ 83, 4 ]
[ 86, 57 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.close
(self)
Closes the ADP port
Closes the ADP port
def close(self): """Closes the ADP port """ self._logger.info("Closing ADP Port") if self._port: self._port.close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Closing ADP Port\"", ")", "if", "self", ".", "_port", ":", "self", ".", "_port", ".", "close", "(", ")" ]
[ 88, 4 ]
[ 93, 30 ]
python
en
['en', 'ca', 'en']
True
ADP_Conn.open
(self, port_path, timeout=1, print_received=False)
Opens an ADP port connection :param port_path: Path to the serial port to use :type port_path: str :param timeout: The amount of time (in seconds) to wait in all serial communications before an error is thrown if nothing is received :type ...
Opens an ADP port connection
def open(self, port_path, timeout=1, print_received=False): """Opens an ADP port connection :param port_path: Path to the serial port to use :type port_path: str :param timeout: The amount of time (in seconds) to wait in all serial communications before an error ...
[ "def", "open", "(", "self", ",", "port_path", ",", "timeout", "=", "1", ",", "print_received", "=", "False", ")", ":", "# Display start message", "self", ".", "_logger", ".", "info", "(", "\"Opening ADP port: \"", "+", "port_path", ")", "# Connect to ADP", "se...
[ 106, 4 ]
[ 143, 26 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.memory_write
(self, address, data)
Write data to any address location in the memory map :param address: The memory address :type address: int :param data: The value to write :type data: int
Write data to any address location in the memory map :param address: The memory address :type address: int :param data: The value to write :type data: int
def memory_write(self, address, data): """ Write data to any address location in the memory map :param address: The memory address :type address: int :param data: The value to write :type data: int """ self._logger.debug('memory write.. A:{:X}, Data:{:X}'...
[ "def", "memory_write", "(", "self", ",", "address", ",", "data", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'memory write.. A:{:X}, Data:{:X}'", ".", "format", "(", "address", ",", "data", ")", ")", "if", "type", "(", "address", ")", "==", "st...
[ 200, 4 ]
[ 218, 16 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.memory_read
(self, address)
Read any address location in the memory map :param address: The memory address :type address: int :return: the value at that address :rtype: int
Read any address location in the memory map :param address: The memory address :type address: int :return: the value at that address :rtype: int
def memory_read(self, address): """ Read any address location in the memory map :param address: The memory address :type address: int :return: the value at that address :rtype: int """ # Write address # Change the hex to string without the L suffi...
[ "def", "memory_read", "(", "self", ",", "address", ")", ":", "# Write address", "# Change the hex to string without the L suffix", "self", ".", "_read_buffer", ".", "flush_buffer", "(", "'adp'", ")", "self", ".", "_logger", ".", "debug", "(", "'memory read.. {}'", "...
[ 233, 4 ]
[ 268, 27 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.memory_dump_bin
(self, bin_path, address, limit)
Write a binary image to a memory region (fast) :param bin_address: Path to binary file to load :type bin_path: str :param address: The start address :type address: int :param limit: The maximum length to write (bytes) :type limit: int
Write a binary image to a memory region (fast) :param bin_address: Path to binary file to load :type bin_path: str :param address: The start address :type address: int :param limit: The maximum length to write (bytes) :type limit: int
def memory_dump_bin(self, bin_path, address, limit): """ Write a binary image to a memory region (fast) :param bin_address: Path to binary file to load :type bin_path: str :param address: The start address :type address: int :param limit: The maximum length to wr...
[ "def", "memory_dump_bin", "(", "self", ",", "bin_path", ",", "address", ",", "limit", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Binary memory dump\"", ")", "time", ".", "sleep", "(", "1", ")", "if", "type", "(", "address", ")", "==", "str...
[ 270, 4 ]
[ 335, 33 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.memory_dump
(self, hex_path, address, limit)
Write a hex image to a memory region (slow) - old implementation :param hex_path: Path to the hex file to load :param address: The start address :param limit: The maximum length to write (words)
Write a hex image to a memory region (slow) - old implementation
def memory_dump(self, hex_path, address, limit): """ Write a hex image to a memory region (slow) - old implementation :param hex_path: Path to the hex file to load :param address: The start address :param limit: The maximum length to write (words) """ if not isinstance(a...
[ "def", "memory_dump", "(", "self", ",", "hex_path", ",", "address", ",", "limit", ")", ":", "if", "not", "isinstance", "(", "address", ",", "int", ")", ":", "raise", "ValueError", "(", "\"Only integer address now supported\"", ")", "self", ".", "_logger", "....
[ 337, 4 ]
[ 390, 33 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.memory_read_batch_fast
(self, address, words)
Fast batch memory read function :param address: The start/base address (word-aligned) :type address: int :param words: The number of words to read :type words: int :return: List of integer word values at each word address :rtype: list
Fast batch memory read function :param address: The start/base address (word-aligned) :type address: int :param words: The number of words to read :type words: int :return: List of integer word values at each word address :rtype: list
def memory_read_batch_fast(self, address, words): """Fast batch memory read function :param address: The start/base address (word-aligned) :type address: int :param words: The number of words to read :type words: int :return: List of integer word values at each w...
[ "def", "memory_read_batch_fast", "(", "self", ",", "address", ",", "words", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Started (fast) memory read batch. Address: 0x{:08X}, Words: {:d}\"", ".", "format", "(", "address", ",", "words", ")", ")", "if", "ty...
[ 393, 4 ]
[ 459, 19 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.stdin
(self, string)
Send text to device via ADP STDIN (standard input) :param string: Text to write via standard input :type string: str
Send text to device via ADP STDIN (standard input)
def stdin(self, string): """Send text to device via ADP STDIN (standard input) :param string: Text to write via standard input :type string: str """ self._adp_exit() for s in string: self.write(s) self._adp_enter()
[ "def", "stdin", "(", "self", ",", "string", ")", ":", "self", ".", "_adp_exit", "(", ")", "for", "s", "in", "string", ":", "self", ".", "write", "(", "s", ")", "self", ".", "_adp_enter", "(", ")" ]
[ 522, 4 ]
[ 531, 25 ]
python
en
['en', 'mt', 'it']
False
ADP_Conn.flush_output
(self)
Clears all data in output buffer
Clears all data in output buffer
def flush_output(self): """Clears all data in output buffer """ self._port.reset_output_buffer()
[ "def", "flush_output", "(", "self", ")", ":", "self", ".", "_port", ".", "reset_output_buffer", "(", ")" ]
[ 533, 4 ]
[ 536, 40 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.create_buffer
(self, buffer_name)
Creates an independent software buffer in which any received data (including ADP command response and printf/stdout) is inserted into. :param buffer_name: Name of the buffer to create :type buffer_name: str
Creates an independent software buffer in which any received data (including ADP command response and printf/stdout) is inserted into.
def create_buffer(self, buffer_name): """Creates an independent software buffer in which any received data (including ADP command response and printf/stdout) is inserted into. :param buffer_name: Name of the buffer to create :type buffer_name: str """ self._logger.debug("Creati...
[ "def", "create_buffer", "(", "self", ",", "buffer_name", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Creating buffer: {}...\"", ".", "format", "(", "buffer_name", ")", ")", "self", ".", "_read_buffer", ".", "create_buffer", "(", "buffer_name", ")" ...
[ 538, 4 ]
[ 545, 52 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.read_all_buffer
(self, buffer_name)
Reads and clears the selected buffer (destructive read) independently of other defined buffers :param buffer_name: The name of the existing buffer :type buffer_name: str :return: All data in the buffer :rtype: str
Reads and clears the selected buffer (destructive read) independently of other defined buffers
def read_all_buffer(self, buffer_name): """Reads and clears the selected buffer (destructive read) independently of other defined buffers :param buffer_name: The name of the existing buffer :type buffer_name: str :return: All data in the buffer :rtype: str """ se...
[ "def", "read_all_buffer", "(", "self", ",", "buffer_name", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Reading all buffer: {}...\"", ".", "format", "(", "buffer_name", ")", ")", "return", "self", ".", "_read_buffer", ".", "read_all_buffer", "(", "bu...
[ 547, 4 ]
[ 556, 61 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.read_only_buffer
(self, buffer_name)
Reads the selected buffer (without clearing) independently of other defined buffers :param buffer_name: The name of the existing buffer :type buffer_name: str :return: All data in the buffer :rtype: str
Reads the selected buffer (without clearing) independently of other defined buffers
def read_only_buffer(self, buffer_name): """Reads the selected buffer (without clearing) independently of other defined buffers :param buffer_name: The name of the existing buffer :type buffer_name: str :return: All data in the buffer :rtype: str """ self._logger...
[ "def", "read_only_buffer", "(", "self", ",", "buffer_name", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Read only buffer: {}...\"", ".", "format", "(", "buffer_name", ")", ")", "self", ".", "_read_buffer", ".", "read_only_buffer", "(", "buffer_name", ...
[ 562, 4 ]
[ 571, 55 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.poll_buffer_for_string
(self, buffer_name, string, period=0.5, timeout=1, remove_angle_brackets=False)
Monitors a buffer until a specific string is detected or a timeout occurs :param buffer_name: name of the existing buffer to poll :type buffer_name: str :param string: The string to match in the buffer :type string: str :param period: The time interval (in seconds) at which to t...
Monitors a buffer until a specific string is detected or a timeout occurs
def poll_buffer_for_string(self, buffer_name, string, period=0.5, timeout=1, remove_angle_brackets=False): """Monitors a buffer until a specific string is de...
[ "def", "poll_buffer_for_string", "(", "self", ",", "buffer_name", ",", "string", ",", "period", "=", "0.5", ",", "timeout", "=", "1", ",", "remove_angle_brackets", "=", "False", ")", ":", "stop_time", "=", "time", ".", "time", "(", ")", "+", "timeout", "...
[ 573, 4 ]
[ 606, 48 ]
python
en
['en', 'en', 'en']
True
ADP_Conn.poll_buffer_for_pattern
(self, buffer_name, expr, period=0.05, timeout=1, remove_angle_brackets=False)
Monitors a buffer until a specific regular expression (regex) is matched or a timeout occurs :param buffer_name: name of the existing buffer to poll :type buffer_name: str :param expr: The regular expression (regex) to match in the buffer :type string: str :param period: The tim...
Monitors a buffer until a specific regular expression (regex) is matched or a timeout occurs
def poll_buffer_for_pattern(self, buffer_name, expr, period=0.05, timeout=1, remove_angle_brackets=False): """Monitors a buffer until a specific regular expr...
[ "def", "poll_buffer_for_pattern", "(", "self", ",", "buffer_name", ",", "expr", ",", "period", "=", "0.05", ",", "timeout", "=", "1", ",", "remove_angle_brackets", "=", "False", ")", ":", "stop_time", "=", "time", ".", "time", "(", ")", "+", "timeout", "...
[ 608, 4 ]
[ 645, 73 ]
python
en
['en', 'en', 'en']
True
test_num_training_batches
(tmpdir)
Tests that the correct number of batches are allocated
Tests that the correct number of batches are allocated
def test_num_training_batches(tmpdir): """ Tests that the correct number of batches are allocated """ # when we have fewer batches in the dataloader we should use those instead of the limit model = EvalModelTemplate() trainer = Trainer(limit_val_batches=100, limit_train_batches=100, max_epochs=1...
[ "def", "test_num_training_batches", "(", "tmpdir", ")", ":", "# when we have fewer batches in the dataloader we should use those instead of the limit", "model", "=", "EvalModelTemplate", "(", ")", "trainer", "=", "Trainer", "(", "limit_val_batches", "=", "100", ",", "limit_tr...
[ 28, 0 ]
[ 52, 44 ]
python
en
['en', 'error', 'th']
False
test_model_reset_correctly
(tmpdir)
Check that model weights are correctly reset after scaling batch size.
Check that model weights are correctly reset after scaling batch size.
def test_model_reset_correctly(tmpdir): """ Check that model weights are correctly reset after scaling batch size. """ tutils.reset_seed() model = EvalModelTemplate() # logger file to get meta trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, ) before_state_dict = ...
[ "def", "test_model_reset_correctly", "(", "tmpdir", ")", ":", "tutils", ".", "reset_seed", "(", ")", "model", "=", "EvalModelTemplate", "(", ")", "# logger file to get meta", "trainer", "=", "Trainer", "(", "default_root_dir", "=", "tmpdir", ",", "max_epochs", "="...
[ 158, 0 ]
[ 178, 68 ]
python
en
['en', 'en', 'en']
True
test_trainer_reset_correctly
(tmpdir)
Check that all trainer parameters are reset correctly after scaling batch size.
Check that all trainer parameters are reset correctly after scaling batch size.
def test_trainer_reset_correctly(tmpdir): """ Check that all trainer parameters are reset correctly after scaling batch size. """ tutils.reset_seed() model = EvalModelTemplate() # logger file to get meta trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, ) changed_a...
[ "def", "test_trainer_reset_correctly", "(", "tmpdir", ")", ":", "tutils", ".", "reset_seed", "(", ")", "model", "=", "EvalModelTemplate", "(", ")", "# logger file to get meta", "trainer", "=", "Trainer", "(", "default_root_dir", "=", "tmpdir", ",", "max_epochs", "...
[ 181, 0 ]
[ 215, 81 ]
python
en
['en', 'en', 'en']
True
test_auto_scale_batch_size_trainer_arg
(tmpdir, scale_arg)
Test possible values for 'batch size auto scaling' Trainer argument.
Test possible values for 'batch size auto scaling' Trainer argument.
def test_auto_scale_batch_size_trainer_arg(tmpdir, scale_arg): """ Test possible values for 'batch size auto scaling' Trainer argument. """ tutils.reset_seed() hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) before_batch_size = hparams.get('batch_size') tra...
[ "def", "test_auto_scale_batch_size_trainer_arg", "(", "tmpdir", ",", "scale_arg", ")", ":", "tutils", ".", "reset_seed", "(", ")", "hparams", "=", "EvalModelTemplate", ".", "get_default_hparams", "(", ")", "model", "=", "EvalModelTemplate", "(", "*", "*", "hparams...
[ 220, 0 ]
[ 237, 74 ]
python
en
['en', 'en', 'en']
True
test_auto_scale_batch_size_set_model_attribute
(tmpdir, use_hparams)
Test that new batch size gets written to the correct hyperparameter attribute.
Test that new batch size gets written to the correct hyperparameter attribute.
def test_auto_scale_batch_size_set_model_attribute(tmpdir, use_hparams): """ Test that new batch size gets written to the correct hyperparameter attribute. """ tutils.reset_seed() hparams = EvalModelTemplate.get_default_hparams() before_batch_size = hparams.get('batch_size') class HparamsEvalModel...
[ "def", "test_auto_scale_batch_size_set_model_attribute", "(", "tmpdir", ",", "use_hparams", ")", ":", "tutils", ".", "reset_seed", "(", ")", "hparams", "=", "EvalModelTemplate", ".", "get_default_hparams", "(", ")", "before_batch_size", "=", "hparams", ".", "get", "...
[ 242, 0 ]
[ 279, 45 ]
python
en
['en', 'en', 'en']
True
test_auto_scale_batch_size_duplicate_attribute_warning
(tmpdir)
Test for a warning when model.batch_size and model.hparams.batch_size both present.
Test for a warning when model.batch_size and model.hparams.batch_size both present.
def test_auto_scale_batch_size_duplicate_attribute_warning(tmpdir): """ Test for a warning when model.batch_size and model.hparams.batch_size both present. """ hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) model.hparams = hparams # now we have model.batch_siz...
[ "def", "test_auto_scale_batch_size_duplicate_attribute_warning", "(", "tmpdir", ")", ":", "hparams", "=", "EvalModelTemplate", ".", "get_default_hparams", "(", ")", "model", "=", "EvalModelTemplate", "(", "*", "*", "hparams", ")", "model", ".", "hparams", "=", "hpar...
[ 282, 0 ]
[ 291, 27 ]
python
en
['en', 'en', 'en']
True
test_call_to_trainer_method
(tmpdir, scale_method)
Test that calling the trainer method itself works.
Test that calling the trainer method itself works.
def test_call_to_trainer_method(tmpdir, scale_method): """ Test that calling the trainer method itself works. """ tutils.reset_seed() hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) before_batch_size = hparams.get('batch_size') # logger file to get meta ...
[ "def", "test_call_to_trainer_method", "(", "tmpdir", ",", "scale_method", ")", ":", "tutils", ".", "reset_seed", "(", ")", "hparams", "=", "EvalModelTemplate", ".", "get_default_hparams", "(", ")", "model", "=", "EvalModelTemplate", "(", "*", "*", "hparams", ")"...
[ 295, 0 ]
[ 314, 77 ]
python
en
['en', 'en', 'en']
True
test_error_on_dataloader_passed_to_fit
(tmpdir)
Verify that when the auto scale batch size feature raises an error if a train dataloader is passed to fit
Verify that when the auto scale batch size feature raises an error if a train dataloader is passed to fit
def test_error_on_dataloader_passed_to_fit(tmpdir): """Verify that when the auto scale batch size feature raises an error if a train dataloader is passed to fit """ # only train passed to fit model = EvalModelTemplate() trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, ...
[ "def", "test_error_on_dataloader_passed_to_fit", "(", "tmpdir", ")", ":", "# only train passed to fit", "model", "=", "EvalModelTemplate", "(", ")", "trainer", "=", "Trainer", "(", "default_root_dir", "=", "tmpdir", ",", "max_epochs", "=", "1", ",", "limit_val_batches...
[ 317, 0 ]
[ 333, 42 ]
python
en
['en', 'fr', 'en']
True
ApexMixedPrecisionPlugin.connect
(self, model: torch.nn.Module, optimizers, lr_schedulers)
Connects the precision plugin to the training process, configures apex and reinits the schedulers
Connects the precision plugin to the training process, configures apex and reinits the schedulers
def connect(self, model: torch.nn.Module, optimizers, lr_schedulers): """Connects the precision plugin to the training process, configures apex and reinits the schedulers """ if model.device.type != "cuda": return model, optimizers, lr_schedulers model, optimizers = s...
[ "def", "connect", "(", "self", ",", "model", ":", "torch", ".", "nn", ".", "Module", ",", "optimizers", ",", "lr_schedulers", ")", ":", "if", "model", ".", "device", ".", "type", "!=", "\"cuda\"", ":", "return", "model", ",", "optimizers", ",", "lr_sch...
[ 36, 4 ]
[ 44, 47 ]
python
en
['en', 'en', 'en']
True
ApexMixedPrecisionPlugin.backward
( self, model: LightningModule, closure_loss: torch.Tensor, optimizer: torch.optim.Optimizer, opt_idx: int, should_accumulate: bool, *args, **kwargs, )
performs the actual backpropagation Args: model: the model to be optimized closure_loss: the loss value obtained from the closure optimizer: the optimizer to perform the step lateron opt_idx: the optimizer's index should_accumulate: whether to accumul...
performs the actual backpropagation
def backward( self, model: LightningModule, closure_loss: torch.Tensor, optimizer: torch.optim.Optimizer, opt_idx: int, should_accumulate: bool, *args, **kwargs, ): """performs the actual backpropagation Args: model: the mo...
[ "def", "backward", "(", "self", ",", "model", ":", "LightningModule", ",", "closure_loss", ":", "torch", ".", "Tensor", ",", "optimizer", ":", "torch", ".", "optim", ".", "Optimizer", ",", "opt_idx", ":", "int", ",", "should_accumulate", ":", "bool", ",", ...
[ 46, 4 ]
[ 92, 27 ]
python
en
['en', 'en', 'en']
True
ApexMixedPrecisionPlugin.configure_apex
( self, amp: object, model: LightningModule, optimizers: List[Optimizer], amp_level: str, )
r""" Override to init AMP your own way. Must return a model and list of optimizers. Args: amp: pointer to amp library object. model: pointer to current :class:`LightningModule`. optimizers: list of optimizers passed in :meth:`configure_optimizers`. ...
r""" Override to init AMP your own way. Must return a model and list of optimizers.
def configure_apex( self, amp: object, model: LightningModule, optimizers: List[Optimizer], amp_level: str, ) -> Tuple[LightningModule, List[Optimizer]]: r""" Override to init AMP your own way. Must return a model and list of optimizers. Args:...
[ "def", "configure_apex", "(", "self", ",", "amp", ":", "object", ",", "model", ":", "LightningModule", ",", "optimizers", ":", "List", "[", "Optimizer", "]", ",", "amp_level", ":", "str", ",", ")", "->", "Tuple", "[", "LightningModule", ",", "List", "[",...
[ 94, 4 ]
[ 126, 32 ]
python
cy
['en', 'cy', 'hi']
False
ApexMixedPrecisionPlugin.reinit_scheduler_properties
(optimizers: list, schedulers: list)
Reinitializes schedulers with correct properties
Reinitializes schedulers with correct properties
def reinit_scheduler_properties(optimizers: list, schedulers: list): """Reinitializes schedulers with correct properties""" # Reinitialize optimizer.step properties added by schedulers for scheduler in schedulers: scheduler = scheduler['scheduler'] state = None ...
[ "def", "reinit_scheduler_properties", "(", "optimizers", ":", "list", ",", "schedulers", ":", "list", ")", ":", "# Reinitialize optimizer.step properties added by schedulers", "for", "scheduler", "in", "schedulers", ":", "scheduler", "=", "scheduler", "[", "'scheduler'", ...
[ 129, 4 ]
[ 148, 25 ]
python
en
['en', 'en', 'en']
True
ApexMixedPrecisionPlugin.pre_optimizer_step
( self, pl_module: LightningModule, optimizer: Optimizer, optimizer_idx: int, lambda_closure: Callable, **kwargs )
always called before the optimizer step.
always called before the optimizer step.
def pre_optimizer_step( self, pl_module: LightningModule, optimizer: Optimizer, optimizer_idx: int, lambda_closure: Callable, **kwargs ) -> bool: """ always called before the optimizer step. """ # apex amp does not support closures. lambda_closure() if not pl...
[ "def", "pre_optimizer_step", "(", "self", ",", "pl_module", ":", "LightningModule", ",", "optimizer", ":", "Optimizer", ",", "optimizer_idx", ":", "int", ",", "lambda_closure", ":", "Callable", ",", "*", "*", "kwargs", ")", "->", "bool", ":", "# apex amp does ...
[ 150, 4 ]
[ 164, 20 ]
python
en
['en', 'error', 'th']
False
TestDataloaderVariations.dataloader
(self, *args, **kwargs)
placeholder
placeholder
def dataloader(self, *args, **kwargs): """placeholder"""
[ "def", "dataloader", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":" ]
[ 21, 4 ]
[ 22, 25 ]
python
en
['en', 'da', 'en']
False
merge
()
merge csv files to one file
merge csv files to one file
def merge(): """merge csv files to one file""" # indicates use of a global variable. global resultfile # use list save the csv files csvfiles = [f for f in os.listdir('.') if f != resultfile \ and (len(f.split('.')) >= 2) and f.split('.')[1] == 'csv'] # open file to write ...
[ "def", "merge", "(", ")", ":", "# indicates use of a global variable.", "global", "resultfile", "# use list save the csv files", "csvfiles", "=", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "'.'", ")", "if", "f", "!=", "resultfile", "and", "(", "len...
[ 13, 0 ]
[ 31, 48 ]
python
en
['en', 'en', 'en']
True
IoU.compute
(self)
Computes intersection over union (IoU)
Computes intersection over union (IoU)
def compute(self) -> torch.Tensor: """ Computes intersection over union (IoU) """ return _iou_from_confmat(self.confmat, self.num_classes, self.ignore_index, self.absent_score, self.reduction)
[ "def", "compute", "(", "self", ")", "->", "torch", ".", "Tensor", ":", "return", "_iou_from_confmat", "(", "self", ".", "confmat", ",", "self", ".", "num_classes", ",", "self", ".", "ignore_index", ",", "self", ".", "absent_score", ",", "self", ".", "red...
[ 102, 4 ]
[ 106, 118 ]
python
en
['en', 'error', 'th']
False
traverse_service
(type_context, service_proto, visitor)
Traverse a service definition. Args: type_context: type_context.TypeContext for service type. service_proto: ServiceDescriptorProto for service. visitor: visitor.Visitor defining the business logic of the plugin. Returns: Plugin specific output.
Traverse a service definition.
def traverse_service(type_context, service_proto, visitor): """Traverse a service definition. Args: type_context: type_context.TypeContext for service type. service_proto: ServiceDescriptorProto for service. visitor: visitor.Visitor defining the business logic of the plugin. Return...
[ "def", "traverse_service", "(", "type_context", ",", "service_proto", ",", "visitor", ")", ":", "return", "visitor", ".", "visit_service", "(", "service_proto", ",", "type_context", ")" ]
[ 5, 0 ]
[ 16, 61 ]
python
fr
['fr', 'fr', 'en']
True
traverse_enum
(type_context, enum_proto, visitor)
Traverse an enum definition. Args: type_context: type_context.TypeContext for enum type. enum_proto: EnumDescriptorProto for enum. visitor: visitor.Visitor defining the business logic of the plugin. Returns: Plugin specific output.
Traverse an enum definition.
def traverse_enum(type_context, enum_proto, visitor): """Traverse an enum definition. Args: type_context: type_context.TypeContext for enum type. enum_proto: EnumDescriptorProto for enum. visitor: visitor.Visitor defining the business logic of the plugin. Returns: Plugin sp...
[ "def", "traverse_enum", "(", "type_context", ",", "enum_proto", ",", "visitor", ")", ":", "return", "visitor", ".", "visit_enum", "(", "enum_proto", ",", "type_context", ")" ]
[ 19, 0 ]
[ 30, 55 ]
python
br
['br', 'gd', 'nl']
False
traverse_message
(type_context, msg_proto, visitor)
Traverse a message definition. Args: type_context: type_context.TypeContext for message type. msg_proto: DescriptorProto for message. visitor: visitor.Visitor defining the business logic of the plugin. Returns: Plugin specific output.
Traverse a message definition.
def traverse_message(type_context, msg_proto, visitor): """Traverse a message definition. Args: type_context: type_context.TypeContext for message type. msg_proto: DescriptorProto for message. visitor: visitor.Visitor defining the business logic of the plugin. Returns: Plug...
[ "def", "traverse_message", "(", "type_context", ",", "msg_proto", ",", "visitor", ")", ":", "# We need to do some extra work to recover the map type annotation from the", "# synthesized messages.", "type_context", ".", "map_typenames", "=", "{", "'%s.%s'", "%", "(", "type_con...
[ 33, 0 ]
[ 63, 84 ]
python
fr
['fr', 'fr', 'en']
True
traverse_file
(file_proto, visitor)
Traverse a proto file definition. Args: file_proto: FileDescriptorProto for file. visitor: visitor.Visitor defining the business logic of the plugin. Returns: Plugin specific output.
Traverse a proto file definition.
def traverse_file(file_proto, visitor): """Traverse a proto file definition. Args: file_proto: FileDescriptorProto for file. visitor: visitor.Visitor defining the business logic of the plugin. Returns: Plugin specific output. """ source_code_info = type_context.SourceCodeIn...
[ "def", "traverse_file", "(", "file_proto", ",", "visitor", ")", ":", "source_code_info", "=", "type_context", ".", "SourceCodeInfo", "(", "file_proto", ".", "name", ",", "file_proto", ".", "source_code_info", ")", "package_type_context", "=", "type_context", ".", ...
[ 66, 0 ]
[ 93, 86 ]
python
it
['it', 'it', 'en']
True
norm
(x)
Dot product-based Euclidean norm implementation See: http://fseoane.net/blog/2011/computing-the-vector-norm/ Parameters ---------- x : array-like Vector for which to compute the norm
Dot product-based Euclidean norm implementation
def norm(x): """Dot product-based Euclidean norm implementation See: http://fseoane.net/blog/2011/computing-the-vector-norm/ Parameters ---------- x : array-like Vector for which to compute the norm """ return sqrt(squared_norm(x))
[ "def", "norm", "(", "x", ")", ":", "return", "sqrt", "(", "squared_norm", "(", "x", ")", ")" ]
[ 35, 0 ]
[ 45, 32 ]
python
en
['en', 'en', 'en']
True
trace_dot
(X, Y)
Trace of np.dot(X, Y.T). Parameters ---------- X : array-like First matrix Y : array-like Second matrix
Trace of np.dot(X, Y.T).
def trace_dot(X, Y): """Trace of np.dot(X, Y.T). Parameters ---------- X : array-like First matrix Y : array-like Second matrix """ return np.dot(X.ravel(), Y.ravel())
[ "def", "trace_dot", "(", "X", ",", "Y", ")", ":", "return", "np", ".", "dot", "(", "X", ".", "ravel", "(", ")", ",", "Y", ".", "ravel", "(", ")", ")" ]
[ 48, 0 ]
[ 58, 39 ]
python
en
['en', 'en', 'en']
True
_beta_divergence
(X, W, H, V, beta, square_root=False)
Compute the beta-divergence of X and dot(W, H+V). Parameters ---------- X : float or array-like, shape (n_samples, n_features) W : float or dense array-like, shape (n_samples, n_components) H : float or dense array-like, shape (n_components, n_features) V: float or dense array-like, shape (...
Compute the beta-divergence of X and dot(W, H+V).
def _beta_divergence(X, W, H, V, beta, square_root=False): """Compute the beta-divergence of X and dot(W, H+V). Parameters ---------- X : float or array-like, shape (n_samples, n_features) W : float or dense array-like, shape (n_samples, n_components) H : float or dense array-like, shape (n_c...
[ "def", "_beta_divergence", "(", "X", ",", "W", ",", "H", ",", "V", ",", "beta", ",", "square_root", "=", "False", ")", ":", "beta", "=", "_beta_loss_to_float", "(", "beta", ")", "# The method can be called with scalars", "if", "not", "sp", ".", "issparse", ...
[ 71, 0 ]
[ 176, 18 ]
python
en
['en', 'en', 'en']
True
_special_sparse_dot
(W, H, V, X)
Computes np.dot(W, H+V), only where X is non zero.
Computes np.dot(W, H+V), only where X is non zero.
def _special_sparse_dot(W, H, V, X): """Computes np.dot(W, H+V), only where X is non zero.""" if sp.issparse(X): ii, jj = X.nonzero() n_vals = ii.shape[0] dot_vals = np.empty(n_vals) n_components = W.shape[1] batch_size = max(n_components, n_vals // n_components) ...
[ "def", "_special_sparse_dot", "(", "W", ",", "H", ",", "V", ",", "X", ")", ":", "if", "sp", ".", "issparse", "(", "X", ")", ":", "ii", ",", "jj", "=", "X", ".", "nonzero", "(", ")", "n_vals", "=", "ii", ".", "shape", "[", "0", "]", "dot_vals"...
[ 179, 0 ]
[ 196, 29 ]
python
en
['en', 'en', 'en']
True
_beta_loss_to_float
(beta_loss)
Convert string beta_loss to float
Convert string beta_loss to float
def _beta_loss_to_float(beta_loss): """Convert string beta_loss to float""" allowed_beta_loss = {'frobenius': 2, 'kullback-leibler': 1, 'itakura-saito': 0} if isinstance(beta_loss, str) and beta_loss in allowed_beta_loss: beta_loss = allowed_beta_los...
[ "def", "_beta_loss_to_float", "(", "beta_loss", ")", ":", "allowed_beta_loss", "=", "{", "'frobenius'", ":", "2", ",", "'kullback-leibler'", ":", "1", ",", "'itakura-saito'", ":", "0", "}", "if", "isinstance", "(", "beta_loss", ",", "str", ")", "and", "beta_...
[ 228, 0 ]
[ 240, 20 ]
python
en
['en', 'en', 'en']
True
_initialize_nmf
(X, n_components, init=None, eps=1e-6, random_state=None)
Algorithms for NMF initialization. Computes an initial guess for the non-negative rank k matrix approximation for X: X = WH Parameters ---------- X : array-like, shape (n_samples, n_features) The data matrix to be decomposed. n_components : integer The number of components des...
Algorithms for NMF initialization.
def _initialize_nmf(X, n_components, init=None, eps=1e-6, random_state=None): """Algorithms for NMF initialization. Computes an initial guess for the non-negative rank k matrix approximation for X: X = WH Parameters ---------- X : array-like, shape (n_samples, n_features) ...
[ "def", "_initialize_nmf", "(", "X", ",", "n_components", ",", "init", "=", "None", ",", "eps", "=", "1e-6", ",", "random_state", "=", "None", ")", ":", "check_non_negative", "(", "X", ",", "\"NMF initialization\"", ")", "n_samples", ",", "n_features", "=", ...
[ 243, 0 ]
[ 386, 15 ]
python
en
['en', 'en', 'en']
True
_update_coordinate_descent
(X, W, Ht, l1_reg, l2_reg, shuffle, random_state)
Helper function for _fit_coordinate_descent Update W to minimize the objective function, iterating once over all coordinates. By symmetry, to update H, one can call _update_coordinate_descent(X.T, Ht, W, ...)
Helper function for _fit_coordinate_descent
def _update_coordinate_descent(X, W, Ht, l1_reg, l2_reg, shuffle, random_state): """Helper function for _fit_coordinate_descent Update W to minimize the objective function, iterating once over all coordinates. By symmetry, to update H, one can call _update_coordinate_desc...
[ "def", "_update_coordinate_descent", "(", "X", ",", "W", ",", "Ht", ",", "l1_reg", ",", "l2_reg", ",", "shuffle", ",", "random_state", ")", ":", "n_components", "=", "Ht", ".", "shape", "[", "1", "]", "HHt", "=", "np", ".", "dot", "(", "Ht", ".", "...
[ 389, 0 ]
[ 417, 55 ]
python
en
['en', 'en', 'en']
True
_fit_coordinate_descent
(X, W, H, tol=1e-4, max_iter=200, l1_reg_W=0, l1_reg_H=0, l2_reg_W=0, l2_reg_H=0, update_H=True, verbose=0, shuffle=False, random_state=None)
Compute Non-negative Matrix Factorization (NMF) with Coordinate Descent The objective function is minimized with an alternating minimization of W and H. Each minimization is done with a cyclic (up to a permutation of the features) Coordinate Descent. Parameters ---------- X : array-like, shape...
Compute Non-negative Matrix Factorization (NMF) with Coordinate Descent
def _fit_coordinate_descent(X, W, H, tol=1e-4, max_iter=200, l1_reg_W=0, l1_reg_H=0, l2_reg_W=0, l2_reg_H=0, update_H=True, verbose=0, shuffle=False, random_state=None): """Compute Non-negative Matrix Factorization (NMF) with Coordinate Descent The object...
[ "def", "_fit_coordinate_descent", "(", "X", ",", "W", ",", "H", ",", "tol", "=", "1e-4", ",", "max_iter", "=", "200", ",", "l1_reg_W", "=", "0", ",", "l1_reg_H", "=", "0", ",", "l2_reg_W", "=", "0", ",", "l2_reg_H", "=", "0", ",", "update_H", "=", ...
[ 420, 0 ]
[ 523, 29 ]
python
en
['en', 'it', 'en']
True
_multiplicative_update_w
(X, W, H, V, beta_loss, alpha, gamma, update_H=True)
update W in Multiplicative Update NMF
update W in Multiplicative Update NMF
def _multiplicative_update_w(X, W, H, V, beta_loss, alpha, gamma, update_H=True): """update W in Multiplicative Update NMF""" regularisation = alpha * np.dot(W, np.dot(V,V.T)) if beta_loss == 2: # Numerator numerator = safe_sparse_dot(X, H.T + V.T) # Denominator HHt...
[ "def", "_multiplicative_update_w", "(", "X", ",", "W", ",", "H", ",", "V", ",", "beta_loss", ",", "alpha", ",", "gamma", ",", "update_H", "=", "True", ")", ":", "regularisation", "=", "alpha", "*", "np", ".", "dot", "(", "W", ",", "np", ".", "dot",...
[ 526, 0 ]
[ 606, 18 ]
python
co
['en', 'co', 'it']
False
_multiplicative_update_v
(X, W, H, V, beta_loss, alpha, gamma, update_H=True)
update W in Multiplicative Update NMF
update W in Multiplicative Update NMF
def _multiplicative_update_v(X, W, H, V, beta_loss, alpha, gamma, update_H=True): """update W in Multiplicative Update NMF""" regularisation = alpha * np.dot(np.dot(W.T,W),V) if beta_loss == 2: # Numerator numerator = safe_sparse_dot(W.T,X) # Denominator WHt = np.do...
[ "def", "_multiplicative_update_v", "(", "X", ",", "W", ",", "H", ",", "V", ",", "beta_loss", ",", "alpha", ",", "gamma", ",", "update_H", "=", "True", ")", ":", "regularisation", "=", "alpha", "*", "np", ".", "dot", "(", "np", ".", "dot", "(", "W",...
[ 610, 0 ]
[ 689, 18 ]
python
co
['en', 'co', 'it']
False
_multiplicative_update_h
(X, W, H, V, beta_loss, alpha, gamma)
update H in Multiplicative Update NMF
update H in Multiplicative Update NMF
def _multiplicative_update_h(X, W, H, V, beta_loss, alpha, gamma): """update H in Multiplicative Update NMF""" if beta_loss == 2: numerator = 0 denominator = 0 for i in range(len(X)): numerator += safe_sparse_dot(W[i].T, X[i]) denominator += np.dot(np.dot(W[i].T, ...
[ "def", "_multiplicative_update_h", "(", "X", ",", "W", ",", "H", ",", "V", ",", "beta_loss", ",", "alpha", ",", "gamma", ")", ":", "if", "beta_loss", "==", "2", ":", "numerator", "=", "0", "denominator", "=", "0", "for", "i", "in", "range", "(", "l...
[ 692, 0 ]
[ 771, 18 ]
python
co
['en', 'co', 'it']
False
_fit_multiplicative_update
(X, W, H, V, beta_loss='frobenius', max_iter=200, tol=1e-4, alpha=1.0, update_H=True, verbose=0)
Compute Non-negative Matrix Factorization with Multiplicative Update The objective function is _beta_divergence(X, WH) and is minimized with an alternating minimization of W and H. Each minimization is done with a Multiplicative Update. Parameters ---------- X : array-like, shape (n_samples, n...
Compute Non-negative Matrix Factorization with Multiplicative Update
def _fit_multiplicative_update(X, W, H, V, beta_loss='frobenius', max_iter=200, tol=1e-4, alpha=1.0, update_H=True, verbose=0): """Compute Non-negative Matrix Factorization with Multiplicative Update The objective function is _beta_divergence(X, WH)...
[ "def", "_fit_multiplicative_update", "(", "X", ",", "W", ",", "H", ",", "V", ",", "beta_loss", "=", "'frobenius'", ",", "max_iter", "=", "200", ",", "tol", "=", "1e-4", ",", "alpha", "=", "1.0", ",", "update_H", "=", "True", ",", "verbose", "=", "0",...
[ 774, 0 ]
[ 905, 26 ]
python
en
['en', 'it', 'en']
True
integrative_non_negative_factorization
(X, W=None, H=None, V=None, n_components=None, init=None, update_H=True, solver='mu', beta_loss=2, tol=1e-4, max_iter=200, alpha=1.0, random_state=None, verbose=0, shuffle=False)
r"""Integrative Compute Non-negative Matrix Factorization (iNMF) https://www.ncbi.nlm.nih.gov/pubmed/26377073 Find non-negative matrices (W, H) whose product approximates the non- negative matrix X. This factorization can be used for example for dimensionality reduction, source separation or topic ex...
r"""Integrative Compute Non-negative Matrix Factorization (iNMF)
def integrative_non_negative_factorization(X, W=None, H=None, V=None, n_components=None, init=None, update_H=True, solver='mu', beta_loss=2, tol=1e-4, max_iter=200, alpha=1.0, random_state=None, v...
[ "def", "integrative_non_negative_factorization", "(", "X", ",", "W", "=", "None", ",", "H", "=", "None", ",", "V", "=", "None", ",", "n_components", "=", "None", ",", "init", "=", "None", ",", "update_H", "=", "True", ",", "solver", "=", "'mu'", ",", ...
[ 908, 0 ]
[ 1148, 26 ]
python
it
['en', 'it', 'it']
True
INMF.fit_transform
(self, X, y=None, W=None, H=None, V=None)
Learn a NMF model for the data X and returns the transformed data. This is more efficient than calling fit followed by transform. Parameters ---------- X : list of {array-like, sparse matrix}, shape (n_samples, n_features) Data matrix to be decomposed y : Ignored ...
Learn a NMF model for the data X and returns the transformed data.
def fit_transform(self, X, y=None, W=None, H=None, V=None): """Learn a NMF model for the data X and returns the transformed data. This is more efficient than calling fit followed by transform. Parameters ---------- X : list of {array-like, sparse matrix}, shape (n_samples, n_fe...
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ",", "W", "=", "None", ",", "H", "=", "None", ",", "V", "=", "None", ")", ":", "for", "i", "in", "range", "(", "len", "(", "X", ")", ")", ":", "X", "[", "i", "]", "=", ...
[ 1296, 4 ]
[ 1348, 22 ]
python
en
['en', 'en', 'en']
True
INMF.fit
(self, X, y=None, **params)
Learn a NMF model for the data X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Data matrix to be decomposed y : Ignored Returns ------- self
Learn a NMF model for the data X.
def fit(self, X, y=None, **params): """Learn a NMF model for the data X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Data matrix to be decomposed y : Ignored Returns ------- self """ s...
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "params", ")", ":", "self", ".", "fit_transform", "(", "X", ",", "*", "*", "params", ")", "return", "self" ]
[ 1350, 4 ]
[ 1365, 19 ]
python
en
['en', 'en', 'en']
True
INMF.transform
(self, X)
Transform the data X according to the fitted NMF model Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Data matrix to be transformed by the model Returns ------- W : array, shape (n_samples, n_components) Tran...
Transform the data X according to the fitted NMF model
def transform(self, X): """Transform the data X according to the fitted NMF model Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Data matrix to be transformed by the model Returns ------- W : array, shape (n_samp...
[ "def", "transform", "(", "self", ",", "X", ")", ":", "W", ",", "_", ",", "_", ",", "n_iter_", "=", "integrative_non_negative_factorization", "(", "X", "=", "X", ",", "W", "=", "None", ",", "H", "=", "self", ".", "components_", ",", "V", "=", "None"...
[ 1367, 4 ]
[ 1388, 16 ]
python
en
['en', 'en', 'en']
True
INMF.inverse_transform
(self, W, V)
Transform data back to its original space. Parameters ---------- W : list of {array-like, sparse matrix}, shape (n_samples, n_components) Transformed data matrix V: list of {array-like, sparse matrix}, shape (n_components,n_features) Dataset specific factors ...
Transform data back to its original space.
def inverse_transform(self, W, V): """Transform data back to its original space. Parameters ---------- W : list of {array-like, sparse matrix}, shape (n_samples, n_components) Transformed data matrix V: list of {array-like, sparse matrix}, shape (n_components,n_feat...
[ "def", "inverse_transform", "(", "self", ",", "W", ",", "V", ")", ":", "return", "[", "np", ".", "dot", "(", "W", "[", "i", "]", ",", "self", ".", "components_", "+", "V", "[", "i", "]", ")", "for", "i", "in", "range", "(", "len", "(", "W", ...
[ 1390, 4 ]
[ 1408, 77 ]
python
en
['en', 'pt', 'en']
True
test_checkpoint_callbacks_are_last
(tmpdir)
Test that checkpoint callbacks always get moved to the end of the list, with preserved order.
Test that checkpoint callbacks always get moved to the end of the list, with preserved order.
def test_checkpoint_callbacks_are_last(tmpdir): """ Test that checkpoint callbacks always get moved to the end of the list, with preserved order. """ checkpoint1 = ModelCheckpoint(tmpdir) checkpoint2 = ModelCheckpoint(tmpdir) early_stopping = EarlyStopping() lr_monitor = LearningRateMonitor() pr...
[ "def", "test_checkpoint_callbacks_are_last", "(", "tmpdir", ")", ":", "checkpoint1", "=", "ModelCheckpoint", "(", "tmpdir", ")", "checkpoint2", "=", "ModelCheckpoint", "(", "tmpdir", ")", "early_stopping", "=", "EarlyStopping", "(", ")", "lr_monitor", "=", "Learning...
[ 17, 0 ]
[ 39, 100 ]
python
en
['en', 'en', 'en']
True
test_all_callback_states_saved_before_checkpoint_callback
(tmpdir)
Test that all callback states get saved even if the ModelCheckpoint is not given as last.
Test that all callback states get saved even if the ModelCheckpoint is not given as last.
def test_all_callback_states_saved_before_checkpoint_callback(tmpdir): """ Test that all callback states get saved even if the ModelCheckpoint is not given as last. """ callback0 = StatefulCallback0() callback1 = StatefulCallback1() checkpoint_callback = ModelCheckpoint(dirpath=tmpdir, filename="all_st...
[ "def", "test_all_callback_states_saved_before_checkpoint_callback", "(", "tmpdir", ")", ":", "callback0", "=", "StatefulCallback0", "(", ")", "callback1", "=", "StatefulCallback1", "(", ")", "checkpoint_callback", "=", "ModelCheckpoint", "(", "dirpath", "=", "tmpdir", "...
[ 54, 0 ]
[ 74, 57 ]
python
en
['en', 'en', 'en']
True
test_attach_model_callbacks
()
Test that the callbacks defined in the model and through Trainer get merged correctly.
Test that the callbacks defined in the model and through Trainer get merged correctly.
def test_attach_model_callbacks(): """ Test that the callbacks defined in the model and through Trainer get merged correctly. """ def assert_composition(trainer_callbacks, model_callbacks, expected): model = Mock() model.configure_callbacks.return_value = model_callbacks trainer = Train...
[ "def", "test_attach_model_callbacks", "(", ")", ":", "def", "assert_composition", "(", "trainer_callbacks", ",", "model_callbacks", ",", "expected", ")", ":", "model", "=", "Mock", "(", ")", "model", ".", "configure_callbacks", ".", "return_value", "=", "model_cal...
[ 77, 0 ]
[ 128, 5 ]
python
en
['en', 'en', 'en']
True
test_attach_model_callbacks_override_info
(caplog)
Test that the logs contain the info about overriding callbacks returned by configure_callbacks.
Test that the logs contain the info about overriding callbacks returned by configure_callbacks.
def test_attach_model_callbacks_override_info(caplog): """ Test that the logs contain the info about overriding callbacks returned by configure_callbacks. """ model = Mock() model.configure_callbacks.return_value = [LearningRateMonitor(), EarlyStopping()] trainer = Trainer(checkpoint_callback=False, cal...
[ "def", "test_attach_model_callbacks_override_info", "(", "caplog", ")", ":", "model", "=", "Mock", "(", ")", "model", ".", "configure_callbacks", ".", "return_value", "=", "[", "LearningRateMonitor", "(", ")", ",", "EarlyStopping", "(", ")", "]", "trainer", "=",...
[ 131, 0 ]
[ 140, 100 ]
python
en
['en', 'en', 'en']
True