Back to Mxnet

The NP on MXNet cheat sheet

docs/python_docs/python/tutorials/packages/np/cheat-sheet.md

1.9.18.4 KB
Original Source
<!--- Licensed to the Apache Software Foundation (ASF) under one --> <!--- or more contributor license agreements. See the NOTICE file --> <!--- distributed with this work for additional information --> <!--- regarding copyright ownership. The ASF licenses this file --> <!--- to you under the Apache License, Version 2.0 (the --> <!--- "License"); you may not use this file except in compliance --> <!--- with the License. You may obtain a copy of the License at --> <!--- http://www.apache.org/licenses/LICENSE-2.0 --> <!--- Unless required by applicable law or agreed to in writing, --> <!--- software distributed under the License is distributed on an --> <!--- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY --> <!--- KIND, either express or implied. See the License for the --> <!--- specific language governing permissions and limitations --> <!--- under the License. -->

The NP on MXNet cheat sheet

To begin, import the np and npx module and update MXNet to run in NumPy-like mode.

{.python
from mxnet import np, npx
npx.set_np()  # Change MXNet to the numpy-like mode.

NDArray figure (TODO)

Creating arrays

{.python
np.array([1, 2, 3])  # default datatype is float32
{.python
np.array([(1.5, 2, 3), (4, 5, 6)], dtype='float16')
{.python
np.array([[(15,2,3), (4,5,6)], [(3,2,1), (4,5,6)]], dtype='int32')

Initial placeholders

{.python
np.zeros((3, 4))  # Create an array of zeros
{.python
np.ones((2, 3, 4), dtype='int8')  # Create an array of ones
{.python
np.arange(10, 25, 5)  # Create an array of evenly spaced values (step value)
{.python
# Create an array of evenly spaced values (number of samples)
# np.linspace(0, 2, 9)
{.python
# np.full((2, 2), 7)  # Create a constant array
{.python
# np.eye(2)  # Create a 2X2 identity matrix
{.python
# np.random.random((2, 2))  # Create an array with random values
{.python
np.empty((3,2))  # Create an empty array

I/O

Saving and loading on disk

{.python
# Save one array
a = np.array([1, 2, 3])
npx.save('my_array', a)
npx.load('my_array')
{.python
# Save a list of arrays
b = np.array([4, 6, 8])
npx.savez('my_arrays', *[a, b])
npx.load('my_arrays')

Saving and loading text files

{.python
# np.loadtxt("myfile.txt")
# np.genfromtxt("my_file.csv", delimiter=',')
# np.savetxt("myarray.txt", a, delimiter=" ")

Data types

{.python
# np.int64    # Signed 64-bit integer types
# np.float32  # Standard double-precision floating point
# np.complex  # Complex numbers represented by 128 floats
# np.bool     # Boolean type storing TRUE and FALSE values
# np.object   # Python object type
# np.string_  # Fixed-length string type
# np.unicode_ # Fixed-length unicode type

Inspecting your array

{.python
a.shape # Array dimensions
{.python
len(a) # Length of array
{.python
b.ndim # Number of array dimensions
{.python
b.size # Number of array elements
{.python
b.dtype # Data type of array elements
{.python
# b.dtype.name # Name of data type
{.python
b.astype('int') # Convert an array to a different type

Asking For Help

{.python
# np.info(np.ndarray.dtype)

Array mathematics

Arithmetic operations

{.python
a - b # Subtraction
{.python
np.subtract(a, b) # Subtraction
{.python
b + a # Addition
{.python
np.add(b, a) # Addition
{.python
a / b # Division
{.python
np.divide(a,b) # Division
{.python
a * b # Multiplication
{.python
np.multiply(a, b) # Multiplication
{.python
np.exp(b) # Exponentiation
{.python
np.sqrt(b) # Square root
{.python
np.sin(a) # Sines of an array
{.python
np.cos(b) # Element-wise cosine
{.python
np.log(a) # Element-wise natural logarithm
{.python
a.dot(b) # Dot product

Comparison

Aggregate functions

{.python
a.sum() # Array-wise sum
{.python
# a.min() # Array-wise minimum value
{.python
c = np.array(([[1,2,3], [2,3,4]]))
# c.max(axis=0) # Maximum value of an array row
{.python
# c.cumsum(axis=1) # Cumulative sum of the elements
{.python
a.mean() # Mean
{.python
# b.median() # Median
{.python
# a.corrcoef() # Correlation coefficient
{.python
# np.std(b) # Standard deviation

Copying arrays

{.python
# a.view() # Create a view of the array with the same data
{.python
np.copy(a) # Create a copy of the array
{.python
a.copy() # Create a deep copy of the array

Sorting Arrays

{.python
# a.sort() # Sort an array
{.python
# c.sort(axis=0) # Sort the elements of an array's axis

Subsetting, slicing, indexing

Subsetting

{.python
a[2] # Select the element at the 2nd index 3
{.python
c[0,1] # Select the element at row 1 column 2

Slicing

{.python
a[0:2] # Select items at index 0 and 1
{.python
c[0:2,1] # Select items at rows 0 and 1 in column 1
{.python
c[:1] # Select all items at row 0
{.python
# c[1,...] # Same as [1,:,:]
{.python
a[ : :-1] #Reversed array a array([3, 2, 1])

Boolean Indexing

{.python
# a[a<2] # Select elements from a less than 2

Fancy indexing

{.python
c[[1,0,1,0], [0,1,2,0]] # Select elements (1,0),(0,1),(1,2) and (0,0)
{.python
c[[1,0,1,0]][:,[0,1,2,0]] # Select a subset of the matrix’s rows

Array manipulation

Transposing array

{.python
np.transpose(c) # Permute array dimensions
{.python
c.T # Permute array dimensions

Changing array shape

{.python
# b.ravel() # Flatten the array
{.python
# c.reshape(3,-2) # Reshape, but don’t change data

Adding and removing elements

{.python
# c.resize((6,2)) # Return a new array with shape (6, 2)
{.python
# np.append(h,g) # Append items to an array
{.python
# np.insert(a, 1, 5) # Insert items in an array
{.python
# np.delete(a, [1]) # Delete items from an array

Combining arrays

{.python
np.concatenate((a,b),axis=0) # Concatenate arrays
{.python
# np.vstack((a,b)) # Stack arrays vertically (row-wise)
{.python
# np.r_[e,f] # Stack arrays vertically (row-wise)
{.python
# np.hstack((e,f)) # Stack arrays horizontally (column-wise)
{.python
# np.column_stack((a,d)) # Create stacked column-wise arrays
{.python
# np.c_[a,d] # Create stacked column-wise arrays

Splitting arrays

{.python
# np.hsplit(a,3) # Split the array horizontally at the 3rd index
{.python
# np.vsplit(c,2) # Split the array vertically at the 2nd index

Use GPUs

Prerequisites: A GPU exists and GPU-enabled MXNet is installed.

{.python
npx.num_gpus()  # Query number of GPUs
{.python
npx.gpu(0), npx.gpu(1)  # Context for the first and second GPUs
{.python
gpu_0 = npx.gpu(0) if npx.num_gpus() > 1 else npx.cpu()
g0 = np.zeros((2,3), device=gpu_0)  # Create array on GPU 0
g0
{.python
gpu_1 = npx.gpu(1) if npx.num_gpus() > 2 else npx.cpu()
g1 = np.random.uniform(size=(2,3), device=gpu_1)  # Create array on GPU 1
g1
{.python
# Copy to another GPU
g1.copyto(gpu_0)
{.python
# Return itself if matching the device, otherwise copy
g1.copyto(gpu_0), g1.copyto(gpu_0)
{.python
g1.device  # Query the device an array is on
{.python
## The computation is performed by the devices on which the input arrays are
g0 + g1.copyto(gpu_0)

Auto differentiation

{.python
a.attach_grad() # Allocate gradient for a variable
a.grad # access the gradient

Compute the $\nabla_a b=\exp(2a)^T a$

{.python
from mxnet import autograd

with autograd.record():
    b = np.exp(2*a).dot(a)
b.backward()
a.grad

Acknowledgement

Adapted from www.datacamp.com.