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

F.normalize unsqueeze mean & std only for 1-d arrays #2002

Merged
merged 2 commits into from
Mar 23, 2020
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
20 changes: 20 additions & 0 deletions test/test_transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import torchvision.transforms as transforms
import torchvision.transforms.functional as F
from torch._utils_internal import get_file_path_2
from numpy.testing import assert_array_almost_equal
import unittest
import math
import random
Expand Down Expand Up @@ -843,6 +844,25 @@ def test_normalize_different_dtype(self):
# checks that it doesn't crash
transforms.functional.normalize(img, mean, std)

def test_normalize_3d_tensor(self):
torch.manual_seed(28)
n_channels = 3
img_size = 10
mean = torch.rand(n_channels)
std = torch.rand(n_channels)
img = torch.rand(n_channels, img_size, img_size)
target = F.normalize(img, mean, std).numpy()

mean_unsqueezed = mean.view(-1, 1, 1)
std_unsqueezed = std.view(-1, 1, 1)
result1 = F.normalize(img, mean_unsqueezed, std_unsqueezed)
result2 = F.normalize(img,
mean_unsqueezed.repeat(1, img_size, img_size),
std_unsqueezed.repeat(1, img_size, img_size))
assert_array_almost_equal(target, result1.numpy())
assert_array_almost_equal(target, result2.numpy())


def test_adjust_brightness(self):
x_shape = [2, 2, 3]
x_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1]
Expand Down
6 changes: 5 additions & 1 deletion torchvision/transforms/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,11 @@ def normalize(tensor, mean, std, inplace=False):
std = torch.as_tensor(std, dtype=dtype, device=tensor.device)
if (std == 0).any():
raise ValueError('std evaluated to zero after conversion to {}, leading to division by zero.'.format(dtype))
tensor.sub_(mean[:, None, None]).div_(std[:, None, None])
if mean.ndim == 1:
mean = mean[:, None, None]
if std.ndim == 1:
std = std[:, None, None]
tensor.sub_(mean).div_(std)
return tensor


Expand Down