Conversion Between NumPy and Tensor

Sample Code

import numpy as npfrom mindx.sdk.base 
import Tensor

dtypes = [np.uint8,
          np.int8,
          np.int16,
          np.uint16,
          np.uint32,
          np.int32,
          np.int64,
          np.uint64,
          np.float16,
          np.float32,
          np.double,
          bool]  # List the data types supported by NumPy.
shape = [5, 4, 3, 2]  # Create a 4-dimensional array.
try:
    for d in dtypes:
        a = np.ones(shape, dtype=d)  # Create a NumPy array of type d.
        t = Tensor(a)  # Convert the NumPy array into tensor objects.
        b = np.array(t)  # Convert tensor objects into a NumPy array.
        print(t.shape == shape)  # Compare the array formats before and after the conversion.
        print((a == b).all())  # Compare each element in the array before and after the conversion.
        print(a.dtype == b.dtype)  # Compare the array types before and after the conversion.
except Exception as e:
    print(e)

Precautions

The tensor data structure receives a buffer memory address transferred as a parameter. Therefore, when using the NumPy array to pre-process data and convert the data into tensors, check whether the memory is modified during the pre-processing.

For example, the transpose() function is used to exchange the index values of arrays. However, this function does not rearrange the data memory addresses and returns the converted values only when obtaining the NumPy array. When the NumPy array is converted to tensors, the value of print((a == b).all()) in the preceding code is actually False. (That is, the NumPy array is an array after the transpose, and tensors are an array before the transpose.)

If you want to use a function that does not change the memory arrangement, such as transpose(), use ascontiguousarray() to rearrange the memory data after using transpose(), so that the converted tensor object data is consistent with the expected transposed array.