Numpy-Basic Tutorial(Linear Algebra)

*import NumPy as np

  • NumPy stands for Numerical Python 

  • It is a fundamental python package for scientific computing 

  • Can be used for arrays, Linear algebra, Random Numbers, Broadcasting


a= np.array([3,6,9,12])  #print the array.

a/3 # divides all the elements in the array and prints float values


  • Array: it is collection of elements of same data type

  • Create arrays from lists or Tuples

  • Array()

np.array(object, dtype, copy. order, subok,ndmin) #internal parameters

np.array([1,2,3]) #1d array

np.array([1,2,3.0]) # 1d array with different data types, also called upcasting

np.array([[1,2],[3,4]]) #2d array, nested list

np.array([1,2,3], ndimn=2) # prints 2d array without nested list

np.array([1,2,3], dtype=complex) #changes the data type, prints complex values


  • Arange(): creates an array of evenly spaced values.

np.arange([start].stop.[step], dtype=None) #includes start value but excludes stop value

np.arange(1,10) # prints array of 1-10, since we didn’t gave step value it takes step as 1

np.arange(3.0)# we have given the stop value, so it starts from 0 by default and 

np.arange(1,10,2) #starting value 1, stop value is 10 and step is 2

np.arange(20,dtype= “complex”) #prints 0-20 complex numbers


  • zeros(): Creates an array filled with zeros

np.zeros(shape, dtype=float , order= ‘C’)

np.zeros(5) # prints an Array of 5 zeros of float data type.

np.zeros(5,dtype= “int”) # print an array of 5 zeros of integer data type

np.zeros((2,3)) #we have given a tuple of int’s,it prints the matrix of zeros with 2 rows 3 columns 

np.zeros([3,4]) #we have give an list of ints,it prints the matrix of zeros with 3 row, 4 columns 

*order doesn’t affect the o/p, because it is for storing the multi dimensional data 


  • ones(): Creates an array filled with ones 

np.ones(shape, dtype=None, order= “C”)

np.ones(8) #prints an array of  8 ones of float data type

np.ones(7, dtype=’int’) #prints an array of 7 ones of integer data type

np.ones((3,4)) #we have given tuple of integers, it prints the matrix of 1’s with 3 rows and 4 columns


  • empty(): Creates an array without initializing the entries

np.empty(6) #prints an array of 6 arbitrary values of float data type

np.empty([3,4], dtype= “int”) #prints a matrix of values with 3 rows and 4 columns of int data type.


  • linspace(): Creates array of filled evenly spaced values

np.linspace(strat, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)

  • arange() and linspace() will do the same thing but parameters are different and linspace returns ‘num’ evenly space samples and the end point is optionally excluded.

np.linspace(2.0, 3.0, num=5) #prints 5 values in between 2 to 3 which are evenly spaced and prints along with ending point asa float data type 

np.linspace(2.0, 3.0, num=5, endpoint=False) #prints 5 values in between 2 to 3 which are evenly spaced and prints along without ending point as float data type 

np.linspace(2 , 3, num=5,retstep=True) #prints 5 values in between 2 to 3 which are evenly spaced and prints along with ending point and prints step value as well as a float data type


  • eye(): Returns array filled with zeros except in the kth diagonal, whose values are equal to 1.

np.eye(N, M=None, k+0, dtype=<class ‘float’>, order = ‘C’) # n= no.of rows, m= no.of columns 

np.eye(5) #prints 1 in the main diagonal and remaining as zeros with float data type 

np.eye(2,3) # 2 rows , 3 columns

np.eye(4, k=-1) #main diagonal will be zero and 1’s will be printed in below the main diagonal 


  • identity(): Returns the identity array

np.identity(shape, dtype = ‘float’)

np.identity(4) #prints the square identity matrix of float numbers


  • random(): Random number generation 

    • np.rand(): uniformly distributed value.

    • np.randn(): Normally distributed value.

    • np.ranf(): Uniformly distributed floating point numbers.

    • np.randint(): uniformly distributed integers in a given range.


1) rand()

np.random.rand(d0,d1,d2,.....) # prints the random values in a given shape.

np.random.rand(5) # prints an array of 5 random values.

np.random.rand(4,5) # print the matrix with 4 rows and 5 columns of random values.


2) randn()

np.random.randn(d0,d1,d2,.....) # returns a sample from the standard normal distribution.

np.random.randn() # prints single random value

np.random.randn(5) # prints 5 random values from the Standard normal distribution


3) ranf() 

np.random.ranf(size) # returns random floats in half open interval

np.random.ranf(5) # prints 5 random float values

5*np.random.random_sample(3,3)


4)randint()

np.random.randint(low, high=None, size=None, dtype= ‘1’)# returns a random integer from low to high in half open interval.

np.random.randint(1, size =10) #2 is assigned to low, generates 10 random values, we get 0,1 because high value is not mentioned 

np.random.randint(5, size =(2,4)) # prints random values 2d array with 2 rows and 4 columns 


  • Attributes of arrays 

    • Dimension: N-dimensional array, if you want to know the dimension of an array

We can use ‘ndim’ attribute

a=ap.array([1,2,3,4]) 

a.ndim #prints the dimension of the array.

  •  Shape: tuple of elements indicating the number of elements that are stored along each dimension of the array.

a=np.zeros(5)

A.shape #prints 5 number of elements in array

b= np.array([[1,2],[3,4]])

b.shape # prints the number of rows and number of columns (2,2)

  • Size: This will tell the total number of elements in the array.

b= np.array([[1,2],[3,4]])

b.size #prints the number of elements in the 2 d array (4) 

  • Dtype: Describes the data types 

  • Itemsize: the size of each element in bytes.


INDEXING 

  • We can access the element of the array through the index, we can access the single value of the array through the index

  • Array follows Zero-based indexing i.e, the first element index is zero. We can also use negative indexing for arrays


a=np.array([1,2,3,4,5]) #1D array with list

a[3] # prints 4
a[-2] #prints 4 again

b=np.array([[1,2],[3,4]]) #2D array with list

b.[0][0] # zero row , zero column , prints 1

b.[1] #prints row ([3,4])

c=np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]], [[13,14,15,16], [17,18,19,20], [21,22,23,24]])

c[0][0][1] #zero i, zero j, 1 k, prints 2

c[-2][-3][-3] # prints -2


SLICING 

  • To retrieve a collection of arrays, we use slicing.

a[start : stop: step]

a=np.array([1,2,3,4])

a[1:4] # prints ([2,3,4]) , step=1 by default

a[1::2] #prints ([2,4]), it prints every second element from starting point

a[:] #prints entire array

b[start : end: step, start:end:step]

b=np.array([[1,2],[2,3],[3,4]])

b[1:,1:] #prints ([[3],[4]])

c[start : end: step, start : end : step, start : end : step] #number of matrices, rows, columns 

c=np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]], [[13,14,15,16], [17,18,19,20], [21,22,23,24]])

c[:,:,1] #prints ([[[1],[5],[9]],[[13],[17][21]])


ARITHMETIC OPERATION 

  • We can do addition, subtraction, multiplication, division on arrays 

  • Arithmetic operations on arrays are applied element by element in arrays 

a=np.array([1,2,3,4])

a+2 #add 2 to the each element of array ([3,4,5,6])

  • Similarly subtraction, multiplication, division

b=np.array([6,7,8,9])

a+b #prints sum of two array ([7,9,11,13])

  • Similarly subtraction, multiplication, division

  • Similarly for 2-D arrays of same shape as well

  1. a+b = np.add(a,b)

  2. a-b = np.subtract(a,b)

  3. a*b = np.multiply(a,b)

  4. a/b = np.divide(a,b)

  5. a%b = np.mod(a,b)

  6. a**b = np.power(a,b)


BROADCASTING 

 

  • Can we perform arithmetic operations on arrays of different shapes and sizes?

  • Broad Casting allows us to perform arithmetic operations on arrays of different sizes or shapes.

  • Broadcasting will stretch the value/array to0 the required shape, the performs arithmetic operation

  • BroadCasting Rules 

    • The size of each dimension should be the same

    • The size of one of the dimension should be one

  1. If the two arrays differ in their number of dimensions, the shape of the one earth fewer dimension is padded with ones on its leading side(left side)

  2. If the shape of the two arrays does not match in any dimensions, the array with a shape equal to 1 in that dimension is stretched to match the other shape.

  3. If in any dimension the size disagrees and neither equal to 1, an error is raised.


a=np.array([10,20,30])

b=np.array([1,2,3,4])

a+b # raises error due to broadcasting error 


a=np.array([[1,2],[3,4],[5,6]]) 

b=np.array([10,20])

a.shape #prints(3,2)

b.shape #prints(2,)

a+b #prints suum of the arrays


Because 

  1. Rule 1: According to Rule 1, if there are two different dimensions, we need to add 1 for the b array.

a=(3,2) b=(1,2)

  1. Rule 2: Right values of both the arrays were matched(2=2), (3!=1)

  2. Rule 3:According to rule 3, any one of the dimension should be 1, in b array it is (1,2) it satisfied 

  3. Hence, we will get output in higher dimensions.


ARRAY MANIPULATION


  • reshape(): Gives the new shape to the array without changing the array data.

np.reshape(array, shape, order=’C’)

a=np.arange(10) #prints array of 0-10 

b=np.reshape(a,(5,2)) # changes 1D array to 2D array without changing data (row-wise )

b=np.reshape(a,(5,2), order=’F’) # changes 1D array to 2D array without changing data (column-wise) 

  • The size of the array is nothing but the product of the shape 

  • When we change the shape the size should remain the same, that shouldn’t change.


  • resize(): This array will change the data of the array 

  • If the size of the new array is larger than the original array, then it makes the repeated copies of data

np.resize(array, shape)

a = np.arange(5) #creates a 1d array from 0 to 5 

np.resize(a,(2,3)) #changes the shape and size of the array without 



FLATTEN

  • flatten(): Returns the copy of array which collapsed into 1 Dimension

  • If we give 2d or 3d array it makes a copy of array collapsed into 1d 

array.flatten(order= ‘C’)

a=np.array([[[1,2,3],[3,4,5]].[[6,7,8],[9,10,11]]])

a.flatten()

  • This gives the copy of the array in 1D, it converts 3D to 1D in row-wise

a.flatten(order= “F”)

  • This gives the copy of array in 1D, columns wise 

  • ravel(): Also used to flatten the array, but copy is made only if needed 

np.ravel(array, order= ‘C’)

a.ravel() # This also flatten the given array.



TRANSPOSE AND SWAPAXES

  • transpose(): Rearrange the dimension of the array

np.transpose(array, axes=None)

a = np.arange(1,11).reshape(5,2) #prints the matrix with 5 rows and 2 columns

np.transpose(a) # transposes the matrix into 2 row and 5 columns 

  • It just reverses the shape of the array or matrix 

  • If we apply transpose on 1D array we get the same array 

a.T # this also transposes the matrix 


  • swapaxes(): This is used to interchange any two axes of a given array.

np.swapaxes(array, axis1,axis2)

a=np.([[1,2],[3,4]])

np.swapaxes(a,0,1) #swaps 1st column into 1st row, 2nd column into 2nd row

  • This will be useful when we are dealing with a 3D or 4D array when we want to change the two columns


made with 💓 by G. Sai Dheeraj

Comments

Popular posts from this blog

Object Detection Using OpenCV and Transfer Learning.

Path Detection based on Bird Eye view with OpenCV module

Traffic signs recognition with convolutional Neural networks