In [1]:
import mxnet as mx
In [2]:
# Set a random seed
mx.random.seed(1)
In [3]:
# Create an NDArray without any values initialized.
x = mx.nd.empty(shape=(3, 4))
x
Out[3]:
In [4]:
# Create an NDArray of zeros
x = mx.nd.zeros(shape=(3, 5))
x
Out[4]:
In [5]:
# Create an NDArray of ones
x = mx.nd.ones(shape=(3, 4))
x
Out[5]:
In [6]:
# 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[6]:
In [7]:
# Shape of the array
y.shape
Out[7]:
In [8]:
x.shape
Out[8]:
In [9]:
# Size of the array, which is equal to the product
y.size
Out[9]:
In [10]:
# Element-wise addition
x + y
Out[10]:
In [11]:
# Element-wise multiplication
x * y
Out[11]:
In [12]:
# Exponentiation
mx.nd.exp(y)
Out[12]:
In [13]:
# Dot product
mx.nd.dot(x, y.T)
Out[13]:
In order to perform efficient in-place operations, we should avoid:
y = y + x
Instead, we should use:
y[:] = y + x
In [14]:
# 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 [15]:
# Correct
print('id(y):', id(y))
y[:] = y + x
print('id(y):', id(y))
In [16]:
# Element-wise addition
mx.nd.elemwise_add(x, y, out=y)
Out[16]:
In [17]:
# Another accepted notation is '+='
print('id(x):', id(x))
x += y
print('id(x):', id(x))
In [18]:
x
Out[18]:
In [19]:
# Single-dimensional slicing
x[1:3]
Out[19]:
In [20]:
# Multi-dimensional slicing
In [21]:
x[1:2, 1:3]
Out[21]:
In [22]:
# Assigning new values
x[1:2,1:3] = 5
In [23]:
x
Out[23]:
In [24]:
x = mx.nd.ones(shape=(3, 3))
x
Out[24]:
In [25]:
y = mx.nd.arange(3)
y
Out[25]:
In [26]:
x + y
Out[26]:
Broadcasting prefers to duplicate along the left most axis.
In [27]:
y = y.reshape(shape=(3, 1))
In [28]:
x + y
Out[28]:
In [29]:
a = x.asnumpy()
type(a)
Out[29]:
In [30]:
y = mx.nd.array(a)
type(y)
Out[30]:
In [31]:
# An array initialized on the GPU
z = mx.nd.ones(shape=(3, 3), ctx=mx.gpu(0))
z
Out[31]:
In [32]:
# Copying an NDArray from one context to another
x_gpu = x.copyto(mx.gpu(0))
x_gpu
Out[32]:
In [33]:
x_gpu + z
Out[33]:
In [34]:
# Checking the context of an NDArray
x_gpu.context
Out[34]:
In [35]:
x.context
Out[35]:
In [36]:
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)