Numpy Tutorial

Disclaimer: Everything I write here is from my personal experience. I learned programming mostly by practicing and through working. There can be many other ways to do this. I feel comfortable doing stuffs in these ways. This doesn't mean this is the best approach. Infact, I think in most cases there are better ways to do these. But, I hope these will be helpful for many beginner programmers.

Import python numpy library to your local machine. Adding "as np" simply ensures that you don't need to write "numpy" each time you use numpy, rather writing "np" would be enough.

Create a numpy array

if you want to create a new matrix and you know the size of the matrix, the best way is to create a matrix where all values are zero. writing np.zeros((nyumber of elements in first axis, number of elements in second axis, number of elements in third axis, .......)) is the way to do this. Here, I am showing a 2d matrix first

Similarly we can create a matrix where all the values are "1".

We can create a matrix with "zeros" and where shapes are similar to bMatrix by calling "np.zeros_like(matrix_name)". A similar function exists for "ones" also: "np.ones_like(matrix name)

Shape of a matrix and reshaping

If we want to know the shape of the matrix we can call "shape". It would be like "matrix_name.shape"

If we just want to get number of rows we can use "dMatrix.shape[0]", to get column number we have to write "dMatrix.shape[1]", if there is a third axis we can write "dMatrix.shape[2]"

Now if we want, we can reshape the matrix with "reshape" attribute. For example we want to reshape the dMatrix in (25, 1) shape.

Transposing a matrix is rather simple. just write "matrix_name.T"

Matrix operations and broadcasting

lets create a matrix where each value equals to 5. you can simply do that by adding 5 to a zero matrix or multiplying a "one" matrix with 5. This is known as "Broadcasting"

now if we want to add these two matrix we can write "all_5 + all_7". we can also subtract, multiply or divide in this way.

If the shape of the matrices are different such operation will not work. However, we can do operation with two matrices if one of them have same length on either axis and other axis have length 1.

Matrix arange

We can initiate a matrix with values from 1 to 100 in single row by calling "np.arange(first number, last number, step size)"

Reshape the 100 numbers in 10 by 10 form.

Matrix random initialization

We want to randomly initiate a 10 by 10 matrix. call np.random.rand(size of first axis, size of second axis, .....)

If we want to create a matrix with only integer values, we need to call "np.random.randint(lowest number, highest number, size of array)"