We’ll start by introducing the NDArray
, MXNet’s primary tool for storing and transforming data. If you’ve worked with NumPy
before, you’ll notice that a NDArray is, by design, similar to NumPy’s multi-dimensional array.
To get started, let's import the ndarray
package (nd
is shortform) from MXNet.
# Uncomment the following line to install the latest MXNet
# !pip install --pre mxnet
# Or use the following version to accelerate Intel CPU performance.
# !pip install --pre mxnet-mkl
from mxnet import nd
Next, let's see how to create a 2D array (also called a matrix) with values from two sets of numbers: 1, 2, 3 and 4, 5, 6. This might also be referred to as a tuple of a tuple of integers.
nd.array(((1,2,3),(5,6,7)))
We can also create a very simple matrix with the same shape (2 rows by 3 columns), but fill it with 1s.
x = nd.ones((2,3))
x
Often we’ll want to create arrays whose values are sampled randomly. For example, sampling values uniformly between -1 and 1. Here we create the same shape, but with random sampling.
y = nd.random.uniform(-1,1,(2,3))
y
You can also fill an array of a given shape with a given value, such as 2.0
.
x = nd.full((2,3), 2.0)
x
As with NumPy, the dimensions of each NDArray are accessible by accessing the .shape
attribute. We can also query its size
, which is equal to the product of the components of the shape. In addition, .dtype
tells the data type of the stored values.
(x.shape, x.size, x.dtype)
NDArray supports a large number of standard mathematical operations. Such as element-wise multiplication:
x * y
Exponentiation:
y.exp()
And grab a matrix’s transpose to compute a proper matrix-matrix product:
nd.dot(x, y.T)
MXNet NDArrays support slicing in all the ridiculous ways you might imagine accessing your data. Here’s an example of reading a particular element, which returns a 1D array with shape (1,)
.
y[1,2]
Read the second and third columns from y
.
y[:,1:3]
and writing to a specific element
y[:,1:3] = 2
y
Multi-dimensional slicing is also supported.
y[1:2,0:2] = 4
y
Converting MXNet NDArrays to and from NumPy is easy. The converted arrays do not share memory.
a = x.asnumpy()
(type(a), a)
nd.array(a)