Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unit tests for transforms module #112

Merged
merged 2 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 0 additions & 14 deletions piqture/data_loader/minmax_normalization.py

This file was deleted.

10 changes: 1 addition & 9 deletions piqture/data_loader/mnist_data_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import torch.utils.data
import torchvision
from torchvision import datasets
from piqture.data_loader.minmax_normalization import MinMaxNormalization
from piqture.transforms import MinMaxNormalization


def load_mnist_dataset(
Expand Down Expand Up @@ -65,14 +65,6 @@ def load_mnist_dataset(
raise TypeError("The input labels must be of the type list.")

if normalize_max and normalize_min:
# Check if normalize_min and max are int or float.
if not isinstance(normalize_max, (int, float)) and not isinstance(
normalize_min, (int, float)
):
raise TypeError(
"The inputs normalize_min and normlaize_max must be of the type int or float."
)

# Define a custom mnist transforms.
mnist_transform = torchvision.transforms.Compose(
[
Expand Down
19 changes: 19 additions & 0 deletions piqture/transforms/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# (C) Copyright SaashaJoshi 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""
Transforms (module: piqture.data_loader)
"""

from .transforms import MinMaxNormalization

__all__ = [
"MinMaxNormalization",
]
47 changes: 47 additions & 0 deletions piqture/transforms/transforms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# (C) Copyright SaashaJoshi 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Data transforms for Pytorch datasets."""

from typing import Union
import torch
from torch import Tensor


# pylint: disable=too-few-public-methods
class MinMaxNormalization:
"""Normalizes input values in range [min, max]."""

def __init__(
self, normalize_min: Union[int, float], normalize_max: Union[int, float]
):
# Check if normalize_min and max are int or float.
if not isinstance(normalize_max, (int, float)) or isinstance(
normalize_max, bool
):
raise TypeError("The input normalize_max must be of the type int or float.")
if not isinstance(normalize_min, (int, float)) or isinstance(
normalize_min, bool
):
raise TypeError("The input normalize_min must be of the type int or float.")
self.min = normalize_min
self.max = normalize_max

def __repr__(self):
"""MinMaxNormalization transform representation."""
return (
f"{__class__.__name__}(normalize_min={self.min}, normalize_max={self.max})"
)

def __call__(self, x: Tensor) -> Tensor:
"""Normalizes data to a range [min, max]."""
return self.min + (
(x - torch.min(x)) * (self.max - self.min) / (torch.max(x) - torch.min(x))
)
Empty file added tests/transforms/__init__.py
Empty file.
73 changes: 73 additions & 0 deletions tests/transforms/test_transforms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# (C) Copyright SaashaJoshi 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Unit test for transforms"""

from __future__ import annotations
import numpy as np
import pytest
import torch
from pytest import raises
from piqture.transforms.transforms import MinMaxNormalization


class TestMinMaxNormalization:
"""Test class for MinMaxNormalization transform."""

@pytest.mark.parametrize(
"normalize_min, normalize_max", [(0, 1), (-np.pi, np.pi), (0, np.pi / 2)]
)
def test_repr(self, normalize_min, normalize_max):
"""Tests MinMaxNormalization class representation."""
result = (
f"MinMaxNormalization(normalize_min={normalize_min}, "
f"normalize_max={normalize_max})"
)
assert result == repr(MinMaxNormalization(normalize_min, normalize_max))

@pytest.mark.parametrize(
"normalize_min, normalize_max",
[(None, None), ({}, []), ("12", "abc"), (True, False)],
)
def test_min(self, normalize_min, normalize_max):
"""Tests the normalize_min inputs"""
with raises(
TypeError, match="The input normalize_max must be of the type int or float."
):
_ = MinMaxNormalization(1, normalize_max)

with raises(
TypeError, match="The input normalize_min must be of the type int or float."
):
_ = MinMaxNormalization(normalize_min, 2.3)

@pytest.mark.parametrize(
"normalize_min, normalize_max, x, output",
[
(0, 1, torch.Tensor([1, 2, 3, 4]), torch.Tensor([0, 0.3333, 0.6667, 1])),
(
-np.pi,
np.pi,
torch.Tensor([251, 252, 253, 254]),
torch.Tensor([-np.pi, -np.pi / 3, np.pi / 3, np.pi]),
),
(
0,
np.pi / 2,
torch.Tensor([1.8, 2.1, 3.2, 4.5]),
torch.Tensor([0, np.pi / 18, (7 * np.pi) / 27, np.pi / 2]),
),
],
)
def test_minmax_transform(self, normalize_min, normalize_max, x, output):
"""Tests the transform output."""
transform = MinMaxNormalization(normalize_min, normalize_max)
result = transform(x)
assert torch.allclose(result, output, atol=1e-5, rtol=1e-4)
Loading