#!/usr/bin/env python # coding: utf-8 # # Data Manipulation with Ndarray # # Importing `np` (numpy-like) module and `npx` (numpy extensions) module from MXNet. # In[1]: from mxnet import np, npx # Invoke the experimental numpy-compatible feature in MXNet npx.set_np() # Create a vector and query its attributes # In[2]: x = np.arange(12) x # In[3]: x.shape # In[4]: x.size # More ways to construct arrays # In[5]: np.zeros((3, 4)) # In[6]: np.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) # In[7]: np.random.normal(0, 1, size=(3, 4)) # Elemental-wise operators # In[8]: x = np.array([1, 2, 4, 8]) y = np.ones_like(x) * 2 print('x =', x) print('x + y', x + y) print('x - y', x - y) print('x * y', x * y) print('x ** y', x ** y) print('x / y', x / y) # Matrix multiplication. # In[9]: x = np.arange(12).reshape((3,4)) y = np.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]) np.dot(x, y.T) # Concatenate arrays along a particular axis. # In[10]: np.concatenate([x, y], axis=0), np.concatenate([x, y], axis=1) # Broadcast Mechanism # In[11]: a = np.arange(3).reshape((3, 1)) b = np.arange(2).reshape((1, 2)) print('a:\n', a) print('b:\n', b) a + b # Indexing and Slicing # # In[12]: print('x[-1] =\n', x[-1]) print('x[1:3] =\n', x[1:3]) print('x[1:3, 2:4] =\n', x[1:3, 2:4]) print('x[1,2] =', x[1,2]) # `mxnet.numpy.ndarray` and `numpy.ndarray` # In[13]: a = x.asnumpy() print(type(a)) b = np.array(a) print(type(b))