Seema Varshney
Seema Varshney

Reputation: 61

ValueError: Type must be a sub-type of ndarray type

when i try to train my model,

"ValueError: Type must be a sub-type of ndarray type"

arises at line x_norm=(np.power(x,2)).sum(1).view(-1,1) .

Code :

def pairwise_distances(x, y=None):
  
  x_norm = (np.power(x,2)).sum(1).view(-1, 1)

   if y is not None:
   y_t = torch.transpose(y, 0, 1)
   y_norm = (y**2).sum(1).view(1, -1)
  else:
   y_t = torch.transpose(x, 0, 1)
   y_norm = x_norm.view(1, -1)

  dist = x_norm + y_norm - 2.0 * torch.mm(x, y_t)
  # Ensure diagonal is zero if x=y
  # if y is None:
  #     dist = dist - torch.diag(dist.diag)
  return torch.clamp(dist, 0.0, np.inf)

Upvotes: 5

Views: 12835

Answers (2)

user7769950
user7769950

Reputation: 1

I just want to add to @Kallzvx's answer that ndarray.view CAN change the shape of the array. For instance

array_uint16 = np.ones((10, 10, 4), dtype=np.uint8)
array_uint16.view(np.uint32).shape
> (10, 10, 1)

According to the documentation,

For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the last axis of a must be contiguous. This axis will be resized in the result.

Upvotes: 0

weilueluo
weilueluo

Reputation: 673

Numpy array view is different from torch tensor view.
In numpy:

ndarray.view([dtype][, type])
    New view of array with the same data.

In pytorch:

view(*shape) → Tensor
    Returns a new tensor with the same data as the self tensor but of a different shape.

Numpy's view changes the data type of the array, not the shape. If you want to change the shape of the array in numpy, use ndarray.reshape instead.

Upvotes: 9

Related Questions