0

I have two 0D numpy arrays and want to check if they are same class. The first one y1 is obtained by matmul two 1D arrays; and the second y2 is obtained by squeezing a 1D array.

import numpy as np

y1 = np.array([1]) @ np.array([5])
y2 = np.array([3]).squeeze()

y1.ndim == y2.ndim == 0  # -> True
y1.__class__ is np.ndarray  # -> False
y2.__class__ is np.ndarray  # -> True

as shown above, y1 and y2 are both 0D. If y1 is not a ndarray, what is it?

In my actual case, y1 is just matmul of two numpy arrays, whose output can be a numpy array, or not, as show above; y2 come from some other operations, whose output should be same class as y1, so I have an assertion: assert y1.__class__ is y2.__class__. and this fails when y1 is matmul of two 1D arrays. What should I do then? Thanks!

Sam-gege
  • 723
  • 3
  • 12
  • 1
    "what is it?" did you try checking `type(y1)`? – juanpa.arrivillaga Apr 27 '22 at 06:34
  • 1
    it's ```numpy.int64``` – Nin17 Apr 27 '22 at 06:35
  • Yes I checked. Just confused why the output from matmul is not a numpy array, but a datatype like np.int64? – Sam-gege Apr 27 '22 at 06:44
  • Check out: https://stackoverflow.com/questions/773030/why-are-0d-arrays-in-numpy-not-considered-scalar – juanpa.arrivillaga Apr 27 '22 at 06:48
  • A `numpy.int64` is an `array scalar`, https://numpy.org/doc/stable/reference/arrays.scalars.html. It has a lot of the same attributes and methods as a 0d `ndarray`. Check the type of the element of `y2`, `type(y2[()])`. – hpaulj Apr 27 '22 at 06:48
  • Why are you using this class assertion? What different classes are you watching for? Here you've uncovered the distinction between a `ndarray` and an `array scalar`. Anything else you are worried about? – hpaulj Apr 27 '22 at 07:14
  • I'm also watching for `cupy` arrays. I need to assert that `y1` and `y2` are either both numpy arrays, or both cupy arrays – Sam-gege Apr 28 '22 at 05:00

0 Answers0