Numpy Basics
Array Declaration
Create a rank-1 vector
x = np.array([1, 2, 3])Check its shape
x.shapeDeclare a zero vector/matrix, which all elements are 0.
x = np.zeros((2, 2))
# [0, 0]
# [0, 0]Declare a one vector/matrix, which all elements are 1.
x = np.ones((2, 2))
# [1, 1]
# [1, 1]Create an identity matrix
I = np.eyes(3)
# [1 0 0]
# [0 1 0]
# [0 0 1]Create a random matrix, values are ranging from 0 to 1
Create a random matrix that is normally distributed
Array Indexing
Declare an array and then slice the first two rows and columns 1 and 2
Slice of an array is a view into the same underlying data structure, thus modifying it will also modify the original.
You can also mix integer indexing with slice indexing. However, doing so will yield an array of lower rank than the original array.
Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric data types that you can use to construct arrays.
Array Math
Declaring your numpy array, as float64
Element-wise sum
Element-wise difference
Element-wise product
Element-wise division
Element-wise square root
Inner dot product of two vectors
Matrix product of two 2D vectors, which are basically matrices
Sum an array/vector along all axis
Sum an array/vector along an axis
Perform transpose of a matrix
Array Broadcasting
Suppose that we want to add a constant vector to each row of a matrix
However, there is an even better way in numpy! We can perform the stacking method without actually creating multiple copies of v.
Image Operations
We need to shift gear a little bit and introduce scipy. Scientifc Python library provides some basic functions to work with images. For example, it has functions to read images from disk into numpy arrays, to write numpy arrays to disk as images, and to resize images.
Plots
Plots are essential in machine learning, it helps us with understanding our data and monitoring the training progress of a model. Thus, matplotlib comes in handy! The most important function in matplotlib is plot which allows you to plot 2D data, but of course there are other types of plot functions.

With just a little bit of extra work, we can easily plot multiple lines at once. We can also add title, legend, and axis labels.

You can plot different things in the same figure using the subplot function.

We can also display images in numpy. A slight gotcha with imshow is that it only accepts uint8 data type. We need to explicitly cast the image to uint8 before displaying it.

Display multiple images on a grid.

Last updated