In [31]:
import mxnet as mx
In [13]:
# Set a random seed
mx.random.seed(1)
In [4]:
# Create an NDArray without any values initialized.
x = mx.nd.empty(shape=(3, 4))
x
Out[4]:
In [6]:
# Create an NDArray of zeros
x = mx.nd.zeros(shape=(3, 5))
x
Out[6]:
In [8]:
# Create an NDArray of ones
x = mx.nd.ones(shape=(3, 4))
x
Out[8]:
In [14]:
# Create an NDArray of randomly sampled values
# Example: Values drawn from a standard normal distribution with zero mean and unit variance
# loc: mean of the distribution
# scale: standard deviation of the distribution
y = mx.nd.random_normal(loc=0, scale=1, shape=(3, 4))
y
Out[14]:
In [17]:
# Shape of the array
y.shape
Out[17]:
In [20]:
x.shape
Out[20]:
In [18]:
# Size of the array, which is equal to the product
y.size
Out[18]:
In [21]:
# Element-wise addition
x + y
Out[21]:
In [22]:
# Element-wise multiplication
x * y
Out[22]:
In [23]:
# Exponentiation
mx.nd.exp(y)
Out[23]:
In [24]:
# Dot product
mx.nd.dot(x, y.T)
Out[24]:
In order to perform efficient in-place operations, we should avoid:
y = y + x
Instead, we should use:
y[:] = y + x
In [27]:
# Incorrect
print('id(y):', id(y))
y = y + x
print('id(y):', id(y))
# They have different IDs, which means they memory for variable y is allocated twice!
In [28]:
# Correct
print('id(y):', id(y))
y[:] = y + x
print('id(y):', id(y))
In [29]:
# Element-wise addition
mx.nd.elemwise_add(x, y, out=y)
Out[29]:
In [30]:
# Another accepted notation is '+='
print('id(x):', id(x))
x += y
print('id(x):', id(x))
In [32]:
x
Out[32]:
In [34]:
# Single-dimensional slicing
x[1:3]
Out[34]:
In [35]:
# Multi-dimensional slicing
In [37]:
x[1:2, 1:3]
Out[37]:
In [40]:
# Assigning new values
x[1:2,1:3] = 5
In [41]:
x
Out[41]:
In [43]:
x = mx.nd.ones(shape=(3, 3))
x
Out[43]:
In [45]:
y = mx.nd.arange(3)
y
Out[45]:
In [46]:
x + y
Out[46]:
Broadcasting prefers to duplicate along the left most axis.
In [47]:
y = y.reshape(shape=(3, 1))
In [48]:
x + y
Out[48]:
In [49]:
a = x.asnumpy()
type(a)
Out[49]:
In [51]:
y = mx.nd.array(a)
type(y)
Out[51]:
In [53]:
# An array initialized on the GPU
z = mx.nd.ones(shape=(3, 3), ctx=mx.gpu(0))
z
Out[53]:
In [55]:
# Copying an NDArray from one context to another
x_gpu = x.copyto(mx.gpu(0))
x_gpu
Out[55]:
In [56]:
x_gpu + z
Out[56]:
In [57]:
# Checking the context of an NDArray
x_gpu.context
Out[57]:
In [58]:
x.context
Out[58]:
In [62]:
print('id(z):', id(z))
z = z.copyto(mx.gpu(0))
print('id(z):', id(z))
z = z.as_in_context(mx.gpu(0))
print('id(z):', id(z))
print(z)