π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Fix] Fixes docs in morphology and morphology (#842)
Edgar Ribaeb3545e9e495
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex 7d3b18346..75d6049d2 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -1252,6 +1252,7 @@ class GaussianBlur(AugmentationBase2D):[0.6329, 0.6732, 0.5634, 0.4037, 0.2049],[0.8307, 0.6753, 0.7147, 0.5768, 0.7097]]]])"""+def __init__(self, kernel_size: Tuple[int, int],sigma: Tuple[float, float],border_type: str = 'reflect',diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.pyindex 6c9e58317..3091b727b 100644--- a/kornia/feature/mkd.py+++ b/kornia/feature/mkd.py@@ -3,6 +3,7 @@ from typing import Union, Tuple, Dict, Listimport torchimport torch.nn as nnimport torch.nn.functional as F+from kornia.constants import pifrom kornia.utils import create_meshgridfrom kornia.geometry.conversions import cart2pol@@ -223,13 +224,13 @@ class EmbedGradients(nn.Module):', ' + 'relative=' + str(self.relative) + ')'-def spatial_kernel_embedding(kerneltype, grids: dict) -> torch.Tensor:+def spatial_kernel_embedding(kernel_type, grids: dict) -> torch.Tensor:"""Compute embeddings for cartesian and polar parametrizations. """factors = {"phi": 1.0, "rho": pi / sqrt2, "x": pi / 2, "y": pi / 2}- if kerneltype == 'cart':+ if kernel_type == 'cart':coeffs_ = 'xy'params_ = ['x', 'y']- elif kerneltype == 'polar':+ elif kernel_type == 'polar':coeffs_ = 'rhophi'params_ = ['phi', 'rho']@@ -260,7 +261,7 @@ class ExplicitSpacialEncoding(nn.Module):"""Module that computes explicit cartesian or polar embedding.Args:- kerneltype: (str) Parametrization of kernel.+ kernel_type: (str) Parametrization of kernel.'polar', 'cart' ('polar' is default)fmap_size: (int) Input feature map size in pixels (32 is default)in_dims: (int) Dimensionality of input feature map (7 is default)@@ -273,7 +274,7 @@ class ExplicitSpacialEncoding(nn.Module):- Output: (B, out_dims, fmap_size, fmap_size)Examples::>>> emb_ori = torch.rand(23, 7, 32, 32)- >>> ese = ExplicitSpacialEncoding(kerneltype='polar',+ >>> ese = ExplicitSpacialEncoding(kernel_type='polar',... fmap_size=32,... in_dims=7,... do_gmask=True,@@ -282,17 +283,17 @@ class ExplicitSpacialEncoding(nn.Module):"""def __init__(self,- kerneltype: str = 'polar',+ kernel_type: str = 'polar',fmap_size: int = 32,in_dims: int = 7,do_gmask: bool = True,do_l2: bool = True) -> None:super().__init__()- if kerneltype not in ['polar', 'cart']:- raise NotImplementedError(f'{kerneltype} is not valid, use polar or cart).')+ if kernel_type not in ['polar', 'cart']:+ raise NotImplementedError(f'{kernel_type} is not valid, use polar or cart).')- self.kerneltype = kerneltype+ self.kernel_type = kernel_typeself.fmap_size = fmap_sizeself.in_dims = in_dimsself.do_gmask = do_gmask@@ -301,7 +302,7 @@ class ExplicitSpacialEncoding(nn.Module):self.gmask = None# Precompute embedding.- emb = spatial_kernel_embedding(self.kerneltype, self.grid)+ emb = spatial_kernel_embedding(self.kernel_type, self.grid)# Gaussian mask.if self.do_gmask:@@ -347,7 +348,7 @@ class ExplicitSpacialEncoding(nn.Module):def __repr__(self) -> str:return self.__class__.__name__ +\- '(' + 'kerneltype=' + str(self.kerneltype) +\+ '(' + 'kernel_type=' + str(self.kernel_type) +\', ' + 'fmap_size=' + str(self.fmap_size) +\', ' + 'in_dims=' + str(self.in_dims) +\', ' + 'out_dims=' + str(self.out_dims) +\@@ -471,30 +472,32 @@ class Whitening(nn.Module):class MKDDescriptor(nn.Module):- """- Module that computes Multiple Kernel local descriptors.+ r"""Module that computes Multiple Kernel local descriptors.This is based on the paper "Understanding and Improving Kernel Local Descriptors".See :cite:`mukundan2019understanding` for more details.Args:- patch_size: (int) Input patch size in pixels (32 is default)- kerneltype: (str) Parametrization of kernel- 'concat', 'cart', 'polar' ('concat' is default)+ patch_size: (int) Input patch size in pixels (32 is default).+ kernel_type: (str) Parametrization of kernel+ 'concat', 'cart', 'polar' ('concat' is default).whitening: (str) Whitening transform to apply- None, 'lw', 'pca', 'pcawt', 'pcaws' ('pcawt' is default)+ None, 'lw', 'pca', 'pcawt', 'pcaws' ('pcawt' is default).training_set: (str) Set that model was trained on- 'liberty', 'notredame', 'yosemite' ('liberty' is default)- output_dims: (int) Dimensionality reduction (128 is default)+ 'liberty', 'notredame', 'yosemite' ('liberty' is default).+ output_dims: (int) Dimensionality reduction (128 is default).+Returns:- Tensor: Explicit cartesian or polar embedding+ torch.Tensor: Explicit cartesian or polar embedding.+Shape:- - Input: (B, in_dims, fmap_size, fmap_size)- - Output: (B, out_dims, fmap_size, fmap_size)- Examples::+ - Input: :math:`(B, in_dims, fmap_size, fmap_size)`.+ - Output: :math:`(B, out_dims, fmap_size, fmap_size)`,++ Examples:>>> patches = torch.rand(23, 1, 32, 32)>>> mkd = MKDDescriptor(patch_size=32,- ... kerneltype='concat',+ ... kernel_type='concat',... whitening='pcawt',... training_set='liberty',... output_dims=128)@@ -503,14 +506,14 @@ class MKDDescriptor(nn.Module):def __init__(self,patch_size: int = 32,- kerneltype: str = 'concat',+ kernel_type: str = 'concat',whitening: str = 'pcawt',training_set: str = 'liberty',output_dims: int = 128) -> None:super().__init__()self.patch_size = patch_size- self.kerneltype = kerneltype+ self.kernel_type = kernel_typeself.whitening = whiteningself.training_set = training_set@@ -520,7 +523,7 @@ class MKDDescriptor(nn.Module):'replicate')self.gradients = MKDGradients()- self.parametrizations = ['polar', 'cart'] if self.kerneltype == 'concat' else [self.kerneltype]+ self.parametrizations = ['polar', 'cart'] if self.kernel_type == 'concat' else [self.kernel_type]# Initialize cartesian/polar embedding with absolute/relative gradients.self.odims: int = 0@@ -529,7 +532,7 @@ class MKDDescriptor(nn.Module):for parametrization in self.parametrizations:gradient_embedding = EmbedGradients(patch_size=patch_size,relative=relative_orientations[parametrization])- spatial_encoding = ExplicitSpacialEncoding(kerneltype=parametrization,+ spatial_encoding = ExplicitSpacialEncoding(kernel_type=parametrization,fmap_size=patch_size,in_dims=gradient_embedding.kernel.d)@@ -542,7 +545,7 @@ class MKDDescriptor(nn.Module):# Load supervised(lw)/unsupervised(pca) model trained on training_set.if self.whitening is not None:whitening_models = torch.hub.load_state_dict_from_url(- urls[self.kerneltype], map_location=lambda storage, loc: storage+ urls[self.kernel_type], map_location=lambda storage, loc: storage)whitening_model = whitening_models[training_set]self.whitening_layer = Whitening(whitening,@@ -583,15 +586,15 @@ class MKDDescriptor(nn.Module):def __repr__(self) -> str:return self.__class__.__name__ +\'(' + 'patch_size=' + str(self.patch_size) +\- ', ' + 'kerneltype=' + str(self.kerneltype) +\+ ', ' + 'kernel_type=' + str(self.kernel_type) +\', ' + 'whitening=' + str(self.whitening) +\', ' + 'training_set=' + str(self.training_set) +\', ' + 'output_dims=' + str(self.output_dims) + ')'-def load_whitening_model(kerneltype: str, training_set: str) -> Dict:+def load_whitening_model(kernel_type: str, training_set: str) -> Dict:whitening_models = torch.hub.load_state_dict_from_url(- urls[kerneltype], map_location=lambda storage, loc: storage+ urls[kernel_type], map_location=lambda storage, loc: storage)whitening_model = whitening_models[training_set]return whitening_model@@ -602,23 +605,23 @@ class SimpleKD(nn.Module):def __init__(self,patch_size: int = 32,- kerneltype: str = 'polar', # 'cart' 'polar'+ kernel_type: str = 'polar', # 'cart' 'polar'whitening: str = 'pcawt', # 'lw', 'pca', 'pcaws', 'pcawttraining_set: str = 'liberty', # 'liberty', 'notredame', 'yosemite'output_dims: int = 128) -> None:super().__init__()- relative = kerneltype == 'polar'+ relative = kernel_type == 'polar'sigma = 1.4 * (patch_size / 64)# Sequence of modules.smoothing = GaussianBlur2d((5, 5), (sigma, sigma), 'replicate')gradients = MKDGradients()ori = EmbedGradients(patch_size=patch_size, relative=relative)- ese = ExplicitSpacialEncoding(kerneltype=kerneltype,+ ese = ExplicitSpacialEncoding(kernel_type=kernel_type,fmap_size=patch_size, in_dims=ori.kernel.d)wh = Whitening(whitening,- load_whitening_model(kerneltype, training_set),+ load_whitening_model(kernel_type, training_set),in_dims=ese.odims,output_dims=output_dims)diff --git a/kornia/morphology/basic_operators.py b/kornia/morphology/basic_operators.pyindex 7704ed704..81cd76dc5 100644--- a/kornia/morphology/basic_operators.py+++ b/kornia/morphology/basic_operators.py@@ -1,8 +1,8 @@-# Libraries+from typing import Tuple, Union, List+import torchimport torch.nn as nnimport torch.nn.functional as F-from typing import Tuple, Union# _se_to_mask@@ -19,27 +19,21 @@ def _se_to_mask(se: torch.Tensor) -> torch.Tensor:def dilation(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:+ r"""Returns the dilated image applying the same kernel in each channel.- r"""-- Returns the dilated image applying the same kernel in each channel.The kernel must have 2 dimensions, each one defined by an odd number.- Args-+ Args:tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.Returns:-torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.Example:->>> tensor = torch.rand(1, 3, 5, 5)>>> kernel = torch.ones(3, 3)>>> dilated_img = dilation(tensor, kernel)-"""if not isinstance(tensor, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(@@ -58,43 +52,37 @@ def dilation(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:kernel.dim()))# prepare kernel- se_d = kernel - 1- kernel_d = _se_to_mask(se_d)+ se_d: torch.Tensor = kernel - 1.+ kernel_d: torch.Tensor = _se_to_mask(se_d)# padse_h, se_w = kernel.shape- pad_d = (se_h // 2, se_w // 2)+ pad_d: List[int] = [se_h // 2, se_w // 2]- output = tensor.view(tensor.shape[0] * tensor.shape[1], 1, tensor.shape[2], tensor.shape[3])+ output: torch.Tensor = tensor.view(+ tensor.shape[0] * tensor.shape[1], 1, tensor.shape[2], tensor.shape[3])output = (F.conv2d(output, kernel_d, padding=pad_d) + se_d.view(1, -1, 1, 1)).max(dim=1)[0]- shape = tensor.shape- return output.view(shape)+ return output.view_as(tensor)# erosiondef erosion(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:+ r"""Returns the eroded image applying the same kernel in each channel.- r"""-- Returns the eroded image applying the same kernel in each channel.The kernel must have 2 dimensions, each one defined by an odd number.- Args-+ Args:tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.Returns:-torch.Tensor: Eroded image with shape :math:`(B, C, H, W)`.Example:->>> tensor = torch.rand(1, 3, 5, 5)>>> kernel = torch.ones(5, 5)>>> output = erosion(tensor, kernel)-"""if not isinstance(tensor, torch.Tensor):@@ -114,16 +102,16 @@ def erosion(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:kernel.dim()))# prepare kernel- se_e = kernel - 1- kernel_e = _se_to_mask(se_e)+ se_e: torch.Tensor = kernel - 1.+ kernel_e: torch.Tensor = _se_to_mask(se_e)# padse_h, se_w = kernel.shape- pad_e = (se_h // 2, se_w // 2, se_h // 2, se_w // 2)+ pad_e: List[int] = [se_h // 2, se_w // 2, se_h // 2, se_w // 2]- output = tensor.view(tensor.shape[0] * tensor.shape[1], 1, tensor.shape[2], tensor.shape[3])+ output: torch.Tensor = tensor.view(+ tensor.shape[0] * tensor.shape[1], 1, tensor.shape[2], tensor.shape[3])output = F.pad(output, pad_e, mode='constant', value=1.)output = (F.conv2d(output, kernel_e) - se_e.view(1, -1, 1, 1)).min(dim=1)[0]- shape = tensor.shape- return output.view(shape)+ return output.view_as(tensor)diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.pyindex a126b77cf..5693dec6f 100644--- a/kornia/morphology/morphology.py+++ b/kornia/morphology/morphology.py@@ -1,36 +1,30 @@-# Librariesimport torchimport torch.nn as nnimport torch.nn.functional as F+from kornia.morphology.basic_operators import dilation, erosionfrom kornia.morphology.open_close import open, close# morphological gradientdef gradient(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:+ r"""Returns the morphological gradient of an image.- r"""-- Returns the morphological gradient of an image,- (that means, dilation - erosion) applying the same kernel in each channel.- The kernel must have 2 dimensions, each one defined by an odd number.-- Args-- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.- kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.-- Returns:+ That means, (dilation - erosion) applying the same kernel in each channel.+ The kernel must have 2 dimensions, each one defined by an odd number.- torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.+ Args:+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.- Example:+ Returns:+ torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.- >>> tensor = torch.rand(1, 3, 5, 5)- >>> kernel = torch.ones(3, 3)- >>> gradient_img = gradient(tensor, kernel)-- """+ Example:+ >>> tensor = torch.rand(1, 3, 5, 5)+ >>> kernel = torch.ones(3, 3)+ >>> gradient_img = gradient(tensor, kernel)+ """if not isinstance(tensor, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(@@ -53,32 +47,25 @@ def gradient(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:# top_hatdef top_hat(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:+ r"""Returns the top hat tranformation of an image.- r"""-- Returns the top hat tranformation of an image,- (that means, image - opened_image) applying the same kernel in each channel.-- The kernel must have 2 dimensions, each one defined by an odd number.-- See :class:`~kornia.morphology.open` for details.+ That means, (image - opened_image) applying the same kernel in each channel.+ The kernel must have 2 dimensions, each one defined by an odd number.- Args+ See :class:`~kornia.morphology.open` for details.- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.- kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.+ Args:+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.- Returns:+ Returns:+ torch.Tensor: Top hat transformated image with shape :math:`(B, C, H, W)`.- torch.Tensor: Top hat transformated image with shape :math:`(B, C, H, W)`.-- Example:-- >>> tensor = torch.rand(1, 3, 5, 5)- >>> kernel = torch.ones(3, 3)- >>> top_hat_img = top_hat(tensor, kernel)-- """+ Example:+ >>> tensor = torch.rand(1, 3, 5, 5)+ >>> kernel = torch.ones(3, 3)+ >>> top_hat_img = top_hat(tensor, kernel)+ """if not isinstance(tensor, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(@@ -101,32 +88,25 @@ def top_hat(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:# black_hatdef black_hat(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:+ r"""Returns the black hat tranformation of an image.- r"""-- Returns the black hat tranformation of an image,- (that means, closed_image - image) applying the same kernel in each channel.-- The kernel must have 2 dimensions, each one defined by an odd number.-- See :class:`~kornia.morphology.close` for details.-- Args-- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.- kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.-- Returns:+ That means, (closed_image - image) applying the same kernel in each channel.+ The kernel must have 2 dimensions, each one defined by an odd number.- torch.Tensor: Top hat transformated image with shape :math:`(B, C, H, W)`.+ See :class:`~kornia.morphology.close` for details.- Example:+ Args:+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.- >>> tensor = torch.rand(1, 3, 5, 5)- >>> kernel = torch.ones(3, 3)- >>> black_hat_img = black_hat(tensor, kernel)+ Returns:+ torch.Tensor: Top hat transformated image with shape :math:`(B, C, H, W)`.- """+ Example:+ >>> tensor = torch.rand(1, 3, 5, 5)+ >>> kernel = torch.ones(3, 3)+ >>> black_hat_img = black_hat(tensor, kernel)+ """if not isinstance(tensor, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(diff --git a/kornia/morphology/open_close.py b/kornia/morphology/open_close.pyindex d318be88a..b88be76ce 100644--- a/kornia/morphology/open_close.py+++ b/kornia/morphology/open_close.py@@ -1,34 +1,28 @@-# Librariesimport torchimport torch.nn as nnimport torch.nn.functional as F+from kornia.morphology.basic_operators import dilation, erosion# opendef open(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:+ r"""Returns the opened image, (that means, erosion after a dilation) applying the same kernel in each channel.- r"""-- Returns the opened image, (that means, erosion after a dilation) applying the same kernel in each channel.- The kernel must have 2 dimensions, each one defined by an odd number.-- Args-- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.- kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.-- Returns:-- torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.+ The kernel must have 2 dimensions, each one defined by an odd number.- Example:+ Args:+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.- >>> tensor = torch.rand(1, 3, 5, 5)- >>> kernel = torch.ones(3, 3)- >>> opened_img = open(tensor, kernel)+ Returns:+ torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.- """+ Example:+ >>> tensor = torch.rand(1, 3, 5, 5)+ >>> kernel = torch.ones(3, 3)+ >>> opened_img = open(tensor, kernel)+ """if not isinstance(tensor, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(@@ -51,28 +45,22 @@ def open(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:# closedef close(tensor: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:+ r"""Returns the closed image, (that means, dilation after an erosion) applying the same kernel in each channel.- r"""-- Returns the closed image, (that means, dilation after an erosion) applying the same kernel in each channel.- The kernel must have 2 dimensions, each one defined by an odd number.-- Args-- tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.- kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.-- Returns:-- torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.+ The kernel must have 2 dimensions, each one defined by an odd number.- Example:+ Args:+ tensor (torch.Tensor): Image with shape :math:`(B, C, H, W)`.+ kernel (torch.Tensor): Structuring element with shape :math:`(H, W)`.- >>> tensor = torch.rand(1, 3, 5, 5)- >>> kernel = torch.ones(3, 3)- >>> closed_img = close(tensor, kernel)+ Returns:+ torch.Tensor: Dilated image with shape :math:`(B, C, H, W)`.- """+ Example:+ >>> tensor = torch.rand(1, 3, 5, 5)+ >>> kernel = torch.ones(3, 3)+ >>> closed_img = close(tensor, kernel)+ """if not isinstance(tensor, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(diff --git a/test/feature/test_mkd.py b/test/feature/test_mkd.pyindex a47975d32..10933320e 100644--- a/test/feature/test_mkd.py+++ b/test/feature/test_mkd.py@@ -176,41 +176,41 @@ class TestEmbedGradients:raise_exception=True, nondet_tol=1e-4)[email protected]("kerneltype,d,ps", [('cart', 9, 9), ('polar', 25, 9),- ('cart', 9, 16), ('polar', 25, 16)])-def test_spatial_kernel_embedding(kerneltype, ps, d):[email protected]("kernel_type,d,ps", [('cart', 9, 9), ('polar', 25, 9),+ ('cart', 9, 16), ('polar', 25, 16)])+def test_spatial_kernel_embedding(kernel_type, ps, d):grids = get_grid_dict(ps)- spatial_kernel = spatial_kernel_embedding(kerneltype, grids)+ spatial_kernel = spatial_kernel_embedding(kernel_type, grids)assert spatial_kernel.shape == (d, ps, ps)class TestExplicitSpacialEncoding:- @pytest.mark.parametrize("kerneltype,ps,in_dims", [('cart', 9, 3),- ('polar', 9, 3), ('cart', 13, 7), ('polar', 13, 7)])- def test_shape(self, kerneltype, ps, in_dims, device):+ @pytest.mark.parametrize("kernel_type,ps,in_dims", [('cart', 9, 3),+ ('polar', 9, 3), ('cart', 13, 7), ('polar', 13, 7)])+ def test_shape(self, kernel_type, ps, in_dims, device):inp = torch.ones(1, in_dims, ps, ps).to(device)- ese = ExplicitSpacialEncoding(kerneltype=kerneltype,+ ese = ExplicitSpacialEncoding(kernel_type=kernel_type,fmap_size=ps,in_dims=in_dims).to(device)out = ese(inp)- d_ = 9 if kerneltype == 'cart' else 25+ d_ = 9 if kernel_type == 'cart' else 25assert out.shape == (1, d_ * in_dims)- @pytest.mark.parametrize("kerneltype,bs", [('cart', 1), ('cart', 5), ('cart', 13),- ('polar', 1), ('polar', 5), ('polar', 13)])- def test_batch_shape(self, kerneltype, bs, device):+ @pytest.mark.parametrize("kernel_type,bs", [('cart', 1), ('cart', 5), ('cart', 13),+ ('polar', 1), ('polar', 5), ('polar', 13)])+ def test_batch_shape(self, kernel_type, bs, device):inp = torch.ones(bs, 7, 15, 15).to(device)- ese = ExplicitSpacialEncoding(kerneltype=kerneltype,+ ese = ExplicitSpacialEncoding(kernel_type=kernel_type,fmap_size=15,in_dims=7).to(device)out = ese(inp)- d_ = 9 if kerneltype == 'cart' else 25+ d_ = 9 if kernel_type == 'cart' else 25assert out.shape == (bs, d_ * 7)- @pytest.mark.parametrize("kerneltype", ['cart', 'polar'])- def test_print(self, kerneltype, device):- ese = ExplicitSpacialEncoding(kerneltype=kerneltype,+ @pytest.mark.parametrize("kernel_type", ['cart', 'polar'])+ def test_print(self, kernel_type, device):+ ese = ExplicitSpacialEncoding(kernel_type=kernel_type,fmap_size=15,in_dims=7).to(device)ese.__repr__()@@ -218,7 +218,7 @@ class TestExplicitSpacialEncoding:def test_toy(self, device):inp = torch.ones(1, 2, 6, 6).to(device).float()inp[0, 0, :, :] = 0- cart_ese = ExplicitSpacialEncoding(kerneltype='cart',+ cart_ese = ExplicitSpacialEncoding(kernel_type='cart',fmap_size=6,in_dims=2).to(device)out = cart_ese(inp)@@ -226,7 +226,7 @@ class TestExplicitSpacialEncoding:expected = torch.zeros_like(out_part).to(device)assert_allclose(out_part, expected, atol=1e-3, rtol=1e-3)- polar_ese = ExplicitSpacialEncoding(kerneltype='polar',+ polar_ese = ExplicitSpacialEncoding(kernel_type='polar',fmap_size=6,in_dims=2).to(device)out = polar_ese(inp)@@ -234,14 +234,14 @@ class TestExplicitSpacialEncoding:expected = torch.zeros_like(out_part).to(device)assert_allclose(out_part, expected, atol=1e-3, rtol=1e-3)- @pytest.mark.parametrize("kerneltype", ['cart', 'polar'])- def test_gradcheck(self, kerneltype, device):+ @pytest.mark.parametrize("kernel_type", ['cart', 'polar'])+ def test_gradcheck(self, kernel_type, device):batch_size, channels, ps = 1, 2, 13patches = torch.rand(batch_size, channels, ps, ps).to(device)patches = utils.tensor_to_gradcheck_var(patches) # to vardef explicit_spatial_describe(patches, ps=13):- ese = ExplicitSpacialEncoding(kerneltype=kerneltype,+ ese = ExplicitSpacialEncoding(kernel_type=kernel_type,fmap_size=ps,in_dims=2)ese.to(device)@@ -251,11 +251,13 @@ class TestExplicitSpacialEncoding:class TestWhitening:- @pytest.mark.parametrize("kerneltype,xform,output_dims", [('cart', None, 3),- ('polar', None, 3), ('cart', 'lw', 7), ('polar', 'lw', 7),- ('cart', 'pca', 9), ('polar', 'pca', 9)])- def test_shape(self, kerneltype, xform, output_dims, device):- in_dims = 63 if kerneltype == 'cart' else 175+ @pytest.mark.parametrize("kernel_type,xform,output_dims", [+ ('cart', None, 3), ('polar', None, 3),+ ('cart', 'lw', 7), ('polar', 'lw', 7),+ ('cart', 'pca', 9), ('polar', 'pca', 9)+ ])+ def test_shape(self, kernel_type, xform, output_dims, device):+ in_dims = 63 if kernel_type == 'cart' else 175wh = Whitening(xform=xform,whitening_model=None,in_dims=in_dims,@@ -309,32 +311,32 @@ class TestWhitening:class TestMKDDescriptor:dims = {'cart': 63, 'polar': 175, 'concat': 238}- @pytest.mark.parametrize("ps,kerneltype", [(9, 'concat'),- (9, 'cart'), (9, 'polar'), (32, 'concat'), (32, 'cart'), (32, 'polar')])- def test_shape(self, ps, kerneltype, device):+ @pytest.mark.parametrize("ps,kernel_type", [(9, 'concat'),+ (9, 'cart'), (9, 'polar'), (32, 'concat'), (32, 'cart'), (32, 'polar')])+ def test_shape(self, ps, kernel_type, device):mkd = MKDDescriptor(patch_size=ps,- kerneltype=kerneltype,+ kernel_type=kernel_type,whitening=None).to(device)inp = torch.ones(1, 1, ps, ps).to(device)out = mkd(inp)- assert out.shape == (1, self.dims[kerneltype])+ assert out.shape == (1, self.dims[kernel_type])- @pytest.mark.parametrize("ps,kerneltype,whitening", [(9, 'concat', 'lw'),- (9, 'cart', 'lw'), (9, 'polar', 'lw'), (9, 'concat', 'pcawt'),- (9, 'cart', 'pcawt'), (9, 'polar', 'pcawt')])- def test_whitened_shape(self, ps, kerneltype, whitening, device):+ @pytest.mark.parametrize("ps,kernel_type,whitening", [(9, 'concat', 'lw'),+ (9, 'cart', 'lw'), (9, 'polar', 'lw'), (9, 'concat', 'pcawt'),+ (9, 'cart', 'pcawt'), (9, 'polar', 'pcawt')])+ def test_whitened_shape(self, ps, kernel_type, whitening, device):mkd = MKDDescriptor(patch_size=ps,- kerneltype=kerneltype,+ kernel_type=kernel_type,whitening=whitening).to(device)inp = torch.ones(1, 1, ps, ps).to(device)out = mkd(inp)- output_dims = min(self.dims[kerneltype], 128)+ output_dims = min(self.dims[kernel_type], 128)assert out.shape == (1, output_dims)@pytest.mark.parametrize("bs", [1, 3, 7])def test_batch_shape(self, bs, device):mkd = MKDDescriptor(patch_size=19,- kerneltype='concat',+ kernel_type='concat',whitening=None).to(device)inp = torch.ones(bs, 1, 19, 19).to(device)out = mkd(inp)@@ -351,7 +353,7 @@ class TestMKDDescriptor:inp = torch.ones(1, 1, 6, 6).to(device).float()inp[0, 0, :, :] = 0mkd = MKDDescriptor(patch_size=6,- kerneltype='concat',+ kernel_type='concat',whitening=None).to(device)out = mkd(inp)out_part = out[0, -28:]@@ -366,7 +368,7 @@ class TestMKDDescriptor:def mkd_describe(patches, patch_size=19):mkd = MKDDescriptor(patch_size=patch_size,- kerneltype='concat',+ kernel_type='concat',whitening=whitening).double()mkd.to(device)return mkd(patches.double())@@ -377,25 +379,25 @@ class TestMKDDescriptor:class TestSimpleKD:dims = {'cart': 63, 'polar': 175}- @pytest.mark.parametrize("ps,kerneltype", [(9, 'cart'), (9, 'polar'),- (32, 'cart'), (32, 'polar')])- def test_shape(self, ps, kerneltype, device):+ @pytest.mark.parametrize("ps,kernel_type", [(9, 'cart'), (9, 'polar'),+ (32, 'cart'), (32, 'polar')])+ def test_shape(self, ps, kernel_type, device):skd = SimpleKD(patch_size=ps,- kerneltype=kerneltype).to(device)+ kernel_type=kernel_type).to(device)inp = torch.ones(1, 1, ps, ps).to(device)out = skd(inp)- assert out.shape == (1, min(128, self.dims[kerneltype]))+ assert out.shape == (1, min(128, self.dims[kernel_type]))@pytest.mark.parametrize("bs", [1, 3, 7])def test_batch_shape(self, bs, device):skd = SimpleKD(patch_size=19,- kerneltype='polar').to(device)+ kernel_type='polar').to(device)inp = torch.ones(bs, 1, 19, 19).to(device)out = skd(inp)assert out.shape == (bs, 128)def test_print(self, device):- skd = SimpleKD(patch_size=19, kerneltype='polar').to(device)+ skd = SimpleKD(patch_size=19, kernel_type='polar').to(device)skd.__repr__()def test_gradcheck(self, device):@@ -404,7 +406,7 @@ class TestSimpleKD:patches = utils.tensor_to_gradcheck_var(patches) # to vardef skd_describe(patches, patch_size=19):- skd = SimpleKD(patch_size=patch_size, kerneltype='polar',+ skd = SimpleKD(patch_size=patch_size, kernel_type='polar',whitening='lw').double()skd.to(device)return skd(patches.double())