Return False for the same Tensor

This following code should output True since Tensor boxes1_area_expected should be the same as Tensor boxes1_area_computed. But it returns False. Am I doing it wrong?
PyTorch version: 0.4.1
python 3.5.2 on ubuntu 16.04

import torch

def area(boxes):
  """Computes area of boxes.
  Args:
    boxes: torch tensor with shape [N, 4] holding N boxes, x, y, w, h
  Returns:
    a torch tensor with shape [N*1] representing box areas
  """

  return boxes[:, 2] * boxes[:, 3]

boxes1 = torch.tensor([[0.5, 0.5, 0.5, 0.5],
                           [0.2, 0.2, 0.1, 0.1],
                           [0.6, 0.6, 0.2, 0.2]])

boxes1_area_computed = area(boxes1)
boxes1_area_expected = torch.tensor([0.25, 0.01, 0.04])
print(boxes1_area_computed.equal(boxes1_area_expected))

This behavior is due to numerical precision of float tensors. You can use .allclose() to check if float tensors are equal upto epsilon.

Additionally, you can print the numpy array to see the exact values stored in the tensor.

import torch
import numpy as np
np.set_printoptions(precision=10)

def area(boxes):
  """Computes area of boxes.
  Args:
    boxes: torch tensor with shape [N, 4] holding N boxes, x, y, w, h
  Returns:
    a torch tensor with shape [N*1] representing box areas
  """

  return boxes[:, 2] * boxes[:, 3]

boxes1 = torch.tensor([[0.5, 0.5, 0.5, 0.5],
                           [0.2, 0.2, 0.1, 0.1],
                           [0.6, 0.6, 0.2, 0.2]])

boxes1_area_computed = area(boxes1)
boxes1_area_expected = torch.tensor([0.25, 0.01, 0.04])
print(boxes1_area_computed.numpy(), boxes1_area_expected.numpy())
print(boxes1_area_computed.allclose(boxes1_area_expected))
1 Like

Thanks for answering!