NumPy allows us to do complex computations involving multi-dimensional arrays and matrices, generate randomness, and also perform more simple functions we encounter every day. NumPy will serve as a sort of Swiss army knife for math.
x = [2,8] x+1
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-1-5f383590cd77> in <module>() 1 x = [2,8] ----> 2 x+1 TypeError: can only concatenate list (not "int") to list
What I'm going to do then is redefine x as a numpy array.
# The first thing you need to do is import it import numpy as np #And the way I do this is with np, or numpy, dot array. x = np.array([2,8])
Now x is a numpy array with elements 1 and 5. and we can do all sort of things to a numpy array among them operations like addition, subtraction, multiplication and addition
x+1
array([3, 9])
x-3
array([-1, 5])
x*5
array([10, 40])
y = np.array([2,5])
# I can do x + y since it's element-wise it would be: 2+2, 5+8 x+y
array([ 4, 13])
# x-y x - y
array([0, 3])
#x * y x*y
array([ 4, 40])
x/y
array([1. , 1.6])
Above operations gives me an element-wise operation.
# zero matrix with 3 rows and 4 columns np.zeros([3,4])
array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])
# ones matrix with 4 rows and 3 columns np.ones([4,3])
array([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.], [1., 1., 1.]])
NumPy also contains methods for making random matrices. Now the way I do this is via np.random, which contains several functions, including random again.
#random matrix with 3 rows and 4 columns, Return random floats in the half-open interval [0.0, 1.0). np.random.random([3,4])
array([[0.19562252, 0.91895081, 0.35372375, 0.22609342], [0.43723989, 0.54199647, 0.21732799, 0.30470941], [0.50318549, 0.66145526, 0.18323291, 0.35377885]])
def randomization(n): A = np.random.random([n,1]) return A
randomization(3)
array([[0.07700537], [0.58158776], [0.27861762]])