🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Drop `scipy` from dev dependencies (#2634)
João Gustavo A. Amorim083270a140ad
diff --git a/conftest.py b/conftest.pyindex b79d71fb3..ae3ec004e 100644--- a/conftest.py+++ b/conftest.py@@ -155,7 +155,6 @@ def pytest_report_header(config):import kornia_rsimport onnx- import scipyreturn f"""main deps:@@ -168,7 +167,6 @@ x deps:dev deps:- kornia_rs-{kornia_rs.__version__}- onnx-{onnx.__version__}- - scipy-{scipy.__version__}"""diff --git a/docker/Dockerfile b/docker/Dockerfileindex 1622a9ef4..a01d61f1b 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -10,7 +10,7 @@ RUN curl -o ~/miniconda.sh -O https://repo.continuum.io/miniconda/Miniconda3-lachmod +x ~/miniconda.sh && \~/miniconda.sh -b -p /opt/conda && \rm ~/miniconda.sh && \- /opt/conda/bin/conda install -y python=$PYTHON_VERSION numpy pyyaml scipy ipython mkl mkl-include cython typing && \+ /opt/conda/bin/conda install -y python=$PYTHON_VERSION numpy pyyaml ipython mkl mkl-include cython typing && \/opt/conda/bin/conda install -y -c pytorch magma-cuda90 && \/opt/conda/bin/conda clean -yaENV PATH /opt/conda/bin:$PATHdiff --git a/requirements/requirements-dev.txt b/requirements/requirements-dev.txtindex 5bbe4d688..9f9c5f6a5 100644--- a/requirements/requirements-dev.txt+++ b/requirements/requirements-dev.txt@@ -8,4 +8,3 @@ pre-commit>=2pydocstylepytest==7.4.2pytest-timeout-scipydiff --git a/test/losses/test_hd.py b/test/losses/test_hd.pyindex a44f7825b..d4d761b66 100644--- a/test/losses/test_hd.py+++ b/test/losses/test_hd.py@@ -1,8 +1,5 @@-import numpy as npimport pytestimport torch-from scipy.ndimage import convolve-from torch import nnfrom torch.autograd import gradcheckimport kornia@@ -10,97 +7,6 @@ import kornia.testing as utilsfrom kornia.testing import assert_close-class HausdorffERLossNumpy(nn.Module):- """Binary Hausdorff loss based on morphological erosion.-- Taken from https://github.com/PatRyg99/HausdorffLoss/blob/master/hausdorff_loss.py- """-- def __init__(self, alpha=2.0, erosions=10, **kwargs):- super().__init__()- self.alpha = alpha- self.erosions = erosions- self.prepare_kernels()-- def prepare_kernels(self):- cross = np.array([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])- bound = np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 0]]])-- self.kernel2D = cross * 0.2- # NOTE: updated from np.array([bound, cross, bound]) * (1 / 7)- self.kernel3D = np.array([bound, cross, bound]).squeeze()[None] * (1 / 7)-- @torch.no_grad()- def perform_erosion(self, pred: np.ndarray, target: np.ndarray) -> np.ndarray:- bound = (pred - target) ** 2-- if bound.ndim == 5:- kernel = self.kernel3D- elif bound.ndim == 4:- kernel = self.kernel2D- else:- raise ValueError(f"Dimension {bound.ndim} is nor supported.")-- eroted = np.zeros_like(bound)-- for batch in range(len(bound)):- for k in range(self.erosions):- # compute convolution with kernel- dilation = convolve(bound[batch], kernel, mode="constant", cval=0.0)-- # apply soft thresholding at 0.5 and normalize- erosion = dilation - 0.5- erosion[erosion < 0] = 0-- if erosion.ptp() != 0:- erosion = (erosion - erosion.min()) / erosion.ptp()-- # save erosion and add to loss- bound[batch] = erosion- eroted[batch] += erosion * (k + 1) ** self.alpha-- return eroted-- def forward_one(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:- """- Uses one binary channel: 1 - fg, 0 - bg- pred: (b, 1, x, y, z) or (b, 1, x, y)- target: (b, 1, x, y, z) or (b, 1, x, y)- """- assert pred.size(1) == target.size(1) == 1- # pred = torch.sigmoid(pred)-- eroted = torch.from_numpy(self.perform_erosion(pred.cpu().numpy(), target.cpu().numpy())).to(- dtype=pred.dtype, device=pred.device- )-- loss = eroted.mean()-- return loss-- def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:- """- Uses one binary channel: 1 - fg, 0 - bg- pred: (b, 1, x, y, z) or (b, 1, x, y)- target: (b, 1, x, y, z) or (b, 1, x, y)- """- assert pred.dim() in (4, 5), "Only 2D and 3D supported"- assert pred.dim() == target.dim() and target.size(1) == 1, "Prediction and target need to be of same dimension"- return torch.stack(- [- self.forward_one(- pred[:, i : i + 1],- torch.where(- target == i,- torch.tensor(1, device=target.device, dtype=target.dtype),- torch.tensor(0, device=target.device, dtype=target.dtype),- ),- )- for i in range(pred.size(1))- ]- ).mean()--class TestHausdorffLoss:@pytest.mark.parametrize("reduction", ['mean', 'none', 'sum'])@pytest.mark.parametrize(@@ -140,19 +46,30 @@ class TestHausdorffLoss:)assert 'Invalid target value' in str(errinf)- @pytest.mark.parametrize(- "hd,shape", [[kornia.losses.HausdorffERLoss, (50, 50)], [kornia.losses.HausdorffERLoss3D, (50, 50, 50)]]- )- def test_numeric(self, hd, shape, device, dtype):+ def test_numeric(self, device, dtype):+ num_classes = 3+ shape = (50, 50)+ hd = kornia.losses.HausdorffERLoss+ logits = torch.rand(2, num_classes, *shape, dtype=dtype, device=device)+ labels = (torch.rand(2, 1, *shape, dtype=dtype, device=device) * (num_classes - 1)).long()+ loss = hd(k=10)++ expected = torch.tensor(0.025, device=device, dtype=dtype)++ actual = loss(logits, labels)+ assert_close(actual, expected, rtol=0.005, atol=0.005)++ def test_numeric_3d(self, device, dtype):num_classes = 3+ shape = (50, 50, 50)+ hd = kornia.losses.HausdorffERLoss3Dlogits = torch.rand(2, num_classes, *shape, dtype=dtype, device=device)labels = (torch.rand(2, 1, *shape, dtype=dtype, device=device) * (num_classes - 1)).long()loss = hd(k=10)- loss_np = HausdorffERLossNumpy(erosions=10)- expected = loss_np(logits, labels)+ expected = torch.tensor(0.011, device=device, dtype=dtype)actual = loss(logits, labels)- assert_close(actual, expected)+ assert_close(actual, expected, rtol=1e-2, atol=1e-2)@pytest.mark.parametrize("hd,shape", [[kornia.losses.HausdorffERLoss, (5, 5)], [kornia.losses.HausdorffERLoss3D, (5, 5, 5)]]