Convert MXNet NDArray to NumPy Multidimensional Array

Convert an MXNet NDArray to a NumPy Multidimensional Array so that it retains the specific data type using the asnumpy MXNet function

Convert an MXNet NDArray to a NumPy Multidimensional Array so that it retains the specific data type using the asnumpy MXNet function

Video Transcript


We import NumPy as np.

import numpy as np


Then we print the NumPy version.

print(np.__version__)

We are using NumPy 1.13.3.


Next, we import MXNet as mx:

import mxnet as mx


And we print the MXNet version that we are going to use.

print(mx.__version__)

We are using MXNet 0.12.1.


For this video where we’re going to convert an MXNet NDArray to a NumPy multidimensional array, we’re going to start out with an MXNet NDArray.

mx_ex_int_array = mx.nd.array([
                                  [[1,2,3,4], [2,3,4,5], [3,4,5,6]],
                                  [[4,5,6,7], [5,6,7,8], [6,7,8,9]]
                              ], dtype="int32")

So we do mx.nd.array.

We pass in the multidimensional array and we set the data type as int32.

Note that we could set other types of data types like float32 or anything else you wanted.

We take this whole thing and we assign it to the Python variable, mx_ex_int_array.


We can check the type:

type(mx_ex_int_array)

And we see that it is of class mxnet.ndarray.ndarray.NDArray.

So we have an MXNet NDArray.


Next, we can look at the shape:

mx_ex_int_array.shape

And we see that it is 2x3x4.


Then we can look at the dtype:

mx_ex_int_array.dtype

Here, we pass the int32.

What we’ll get back is numpy.int32.

So MXNet, underneath the NDArray, is using the NumPy data types.

So that’s why when we get back the data type, we see that it is numpy.int32.


To convert our MXNet NDArray to a NumPy multidimensional array, we’re going to use the MXNet .asnumpy() function.

np_ex_int_array = mx_ex_int_array.asnumpy()

So we pass in our MXNet NDArray and we say .asnumpy and we’re assigning that result to the Python variable np_ex_int_array.


The first thing we want to check is what exactly we have:

type(np_ex_int_array)

We can see that we have a numpy.ndarray now whereas before, we had an mxnet.ndarray.

So we have converted successfully the MXNet NDArray to a NumPy multidimensional array.


Let’s check the rest of the particulars of the array.


We can check the shape:

np_ex_int_array.shape

We see that it is still 2x3x4 which is what we expected.


We can check the data type:

np_ex_int_array.dtype

And we see that it is dtype('int32').


Finally, we can print the NumPy multidimensional array:

print(np_ex_int_array)

When we compare it to our MXNet NDArray, we see that it’s the exact same thing.


That is how you convert an MXNet NDArray to a NumPy multidimensional array so that it retains the specific data type using the .asnumpy MXNet function.

Receive the Data Science Weekly Newsletter every Thursday

Easy to unsubscribe at any time. Your e-mail address is safe.