An Essential Guide to Numpy for Machine Learning in Python

Now as you might have guessed there would be many products which haven't been bought even a single time till now and thus a vast majority of elements would be Zero.Sparse Matrices store only non zero elements and assume all other values will be zero, leading to significant computational savings.#Load Libraryimport numpy as np#Create a Matrixmatrix = np.array([[0,0],[0,1],[3,0]])print(matrix)#Create Compressed Sparse Row(CSR) matrixmatrix_sparse = sparse.csr_matrix(matrix)print(matrix_sparse)4) Selecting ElementsWhen you need to select one or more element in a vector or matrix#Load Libraryimport numpy as np#Create a vector as a Rowvector_row = np.array([ 1,2,3,4,5,6 ])#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])print(matrix)#Select 3rd element of Vectorprint(vector_row[2])#Select 2nd row 2nd columnprint(matrix[1,1])#Select all elements of a vectorprint(vector_row[:])#Select everything up to and including the 3rd elementprint(vector_row[:3])#Select the everything after the 3rd elementprint(vector_row[3:])#Select the last elementprint(vector[-1])#Select the first 2 rows and all the columns of the matrixprint(matrix[:2,:])#Select all rows and the 2nd column of the matrixprint(matrix[:,1:2])5) Describing a MatrixWhen you want to know about the shape size and dimensions of a Matrix.import numpy as np#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])#View the Number of Rows and Columnsprint(matrix.shape)#View the number of elements (rows*columns)print(matrix.size)#View the number of Dimensions(2 in this case)print(matrix.ndim)6) Applying operations to elementsYou want to apply some function to multiple elements in an array.Numpy’s vectorize class converts a function into a function that can apply to multiple elements in an array or slice of an array.#Load Libraryimport numpy as np#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])print(matrix)#Create a function that adds 100 to somethingadd_100 =lambda i: i+100#Convert it into a vectorized functionvectorized_add_100= np.vectorize(add_100)#Apply function to all elements in matrixprint(vectorized_add_100(matrix))7) Finding the max and min valuesWe use Numpy’s max and min functions:#Load Libraryimport numpy as np#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])print(matrix)#Return the max elementprint(np.max(matrix))#Return the min elementprint(np.min(matrix))#To find the max element in each columnprint(np.max(matrix,axis=0))#To find the max element in each rowprint(np.max(matrix,axis=1))8) Calculating Average, Variance and Standard deviationWhen you want to calculate some descriptive statistics about an array.#Load Libraryimport numpy as np#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])print(matrix)#Meanprint(np.mean(matrix))#Standard Dev.print(np.std(matrix))#Varianceprint(np.var(matrix))9) Reshaping ArraysWhen you want to reshape an array(changing the number of rows and columns) without changing the elements.#Load Libraryimport numpy as np#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])print(matrix)#Reshapeprint(matrix.reshape(9,1))#Here -1 says as many columns as needed and 1 rowprint(matrix.reshape(1,-1))#If we provide only 1 value Reshape would return a 1-d array of that lengthprint(marix.reshape(9))#We can also use the Flatten method to convert a matrix to 1-d arrayprint(matrix.flatten())10) Transposing a vector or a MatrixBy transposing you interchange the rows and columns of a Matrix#Load Libraryimport numpy as np#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])print(matrix)#Transpose the matrixprint(matrix.T)11) Finding the Determinant and Rank of a MatrixThe rank of a Matrix is the number of dimensions of the vector space spanned by its rows or columns.#Load Libraryimport numpy as np#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])print(matrix)#Calculate the Determinantprint(np.linalg.det(matrix))#Calculate the Rankprint(np.linalg.matrix_rank(matrix))12) Getting the Diagonal of a MatrixWhen you need to extract only the diagonal elements of a matrix#Load Libraryimport numpy as np#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])print(matrix)#Print the Principal diagonalprint(matrix.diagonal())#Print the diagonal one above the Principal diagonalprint(matrix.diagonal(offset=1))#Print the diagonal one below Principal diagonalprint(matrix.diagonal(offset=-1))13) Calculating the trace of a MatrixTrace of a Matrix is the sum of elements on the Principal Diagonal of the Matrix.#Load Libraryimport numpy as np#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])print(matrix)#Print the Traceprint(matrix.trace())14) Finding Eigenvalues and EigenvectorsEigenvectors are widely used in Machine Learning libraries..Intutively given a linear transformation represented by a matrix,A, eigenvectors are vectors that when that transformation is applied, change only in scale(not direction).More formallyAv=KvHere A is a square matrix, K contains the eigenvalues and v contains the eigenvectors.#Load Libraryimport numpy as np#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])print(matrix)# Calculate the Eigenvalues and Eigenvectors of that Matrixeigenvalues ,eigenvectors=np.linalg.eig(matrix)print(eigenvalues)print(eigenvectors)15) Calculating Dot Products#Load Libraryimport numpy as np#Create vector-1vector_1 = np.array([ 1,2,3 ])#Create vector-2vector_1 = np.array([ 4,5,6 ])#Calculate Dot Productprint(np.dot(vector_1,vector_2))#Alternatively you can use @ to calculate dot productsprint(vector_1 @ vector_2)16) Adding, Subtracting and Multiplying Matrices#Load Libraryimport numpy as np#Create Matrix-1matrix_1 = np.array([[1,2,3],[4,5,6],[7,8,9]])#Create Matrix-2matrix_2 = np.array([[7,8,9],[4,5,6],[1,2,3]])#Add the 2 Matricesprint(np.add(matrix_1,matrix_2))#Subtractionprint(np.subtract(matrix_1,matrix_2))#Multiplication(Element wise, not Dot Product)print(matrix_1*matrix_2)17) Inverting a MatrixThis is used when you want to calculate the inverse of a Square Matrix#Load Libraryimport numpy as np#Create a Matrixmatrix = np.array([[1,2,3],[4,5,6],[7,8,9]])print(matrix)#Calculate its inverseprint(np.linalg.inv(matrix))18) Generating Random valuesNumpy offers a wide variety of means to generate Random Numbers.Moreover, It can sometimes be useful to return the same random numbers to get predictable, repeatable results..We can do so by setting the ‘Seed’ (An Integer) of the pseudorandom generator..Random processes with the same seed would always produce the same result.#Load Libraryimport numpy as np#Set seednp.random.seed(1)#Generate 3 random integers b/w 1 and 10print(np.random.randint(0,11,3))#Draw 3 numbers from a normal distribution with mean 1.0 and std 2.0print(np.random.normal(1.0,2.0,3))So this pretty much covers all the standard Numpy Operations which would be required for you to kickstart your Machine Learning journey with Python..For others I hope this was a good refresher to your pre-existing knowledge in the domain.. More details

Leave a Reply