0. Background

In MXNet, NDArray is a class and the primary tool for storing and transforming data. If you’ve worked with NumPy before, you’ll notice that NDArray is very similar to NumPy’s multidimensional arrays. However, NDArray offers more features such as GPU computing and automatic gradient finding, which make it more suitable for deep learning. Tensor, like TensorFlow, and Variable from PyTorch, learn how NumPy operates and do GPU calculations, because NumPy doesn’t support Gpus.

1. Problem description

Sometimes we need to convert NDArray and NumPy multidimensional arrays to and from each other to achieve the desired functionality. In MXNet, data can be converted between NDArray and NumPy formats by array functions and ASNUMpy functions. Let’s transform an NDArray instance into a NumPy instance.

In [1]:

import mxnet as mx
Copy the code

In [2]:

X_nd = mx. Nd. Arange (12). Reshape x_nd ([- 1, 3])Copy the code

Out[2]:

[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]
 [ 9. 10. 11.]]
<NDArray 4x3 @cpu(0)>
Copy the code

In [3]:

x_np = x_nd.asnumpy()
x_np
Copy the code

Out[3]:

array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.],
       [ 9., 10., 11.]], dtype=float32)
Copy the code

Then convert NumPy instance to NDArray instance.

In [4]:

 

x_nd1 = mx.nd.array(x_np)
x_nd1
Copy the code

Out[4]:

[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]
 [ 9. 10. 11.]]
<NDArray 4x3 @cpu(0)>
Copy the code