Workshop - 01: An Introduction to Numpy PDF
Document Details

Uploaded by IngeniousGrossular3278
Herald College Kathmandu
2024
Siman Giri
Tags
Summary
This workshop provides an introduction to the Python library Numpy. It covers the key features and functionalities of Numpy, including array manipulation, array mathematics and linear algebra operations.
Full Transcript
5CS037 - Concepts and Technologies of AI. Week - 01 - Workshop - 01 Introduction to Numpy. From Python List to Numpy Arrays: Why? Siman Giri Workshop - 01...
5CS037 - Concepts and Technologies of AI. Week - 01 - Workshop - 01 Introduction to Numpy. From Python List to Numpy Arrays: Why? Siman Giri Workshop - 01 November - 5 - 2024 Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 2 / 49 Outline 1 Background - What is Numpy? 2 n-Dimensional Array. 3 Array Mathematics With Numpy. 4 Matrix Operation with Numpy. 5 Linear Algebra with Numpy. 6 Final Slide. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 3 / 49 Background - What is Numpy? 1. Introduction to Numpy. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 4 / 49 Background - What is Numpy? 1.1 What is Numpy? Numpy is an open-source add-on modules to python which provides common mathematical and numerical routines in pre-compiled, fast functions. The NumPy(Numeric Python) package provides basic routines for manipulating large arrays and matrices of numeric data. The SciPy(Scientific python) package extends the functionality of NumPy with a substantial collection of useful algorithms. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 5 / 49 Background - What is Numpy? 1.2 Why NumPy? Some of the key features of NumPy are: 1 N-dimensional Array Object {ndarray}. The ndarray is NumPy’s core data structure, allowing the storage and manipulation of large datasets efficiently. Arrays in NumPy can have multiple dimensions (1D, 2D, or higher), which makes it versatile for various applications like matrices and tensors. NumPy supports reshaping (reshape) and flattening arrays to modify their structure without changing the data. The resize function allows for adjusting the size of arrays dynamically, enabling flexibility in handling data dimensions. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 6 / 49 Background - What is Numpy? 1.2.1 Why NumPy? (Continued) Some of the key features of NumPy are: 2 Broadcasting and Vectorized Operations. Broadcasting enables operations on arrays of different shapes and sizes without requiring explicit loops or reshaping. With vectorized operations, NumPy enables performing element-wise computations on entire arrays without the need for Python loops. This feature allows for element-wise operations between arrays even when they don’t have the same dimensions, as long as their shapes are compatible. This leads to significantly faster and more efficient computation, especially with large datasets, since NumPy leverages optimized C and Fortran code under the hood. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 7 / 49 Background - What is Numpy? 1.2.2 Why NumPy? (Continued) Some of the key features of NumPy are: 3 Pre-compiled Mathematical Functions Statistical Tools: NumPy provides a comprehensive library of mathematical, logical, and statistical functions such as mean, median, std, sum, min, max, log, exp, and many more. These functions allow for efficient, high-level mathematical operations across entire arrays. Linear Algebra Operations: NumPy includes a rich set of linear algebra functions, such as matrix multiplication, dot products, determinants, eigenvalues, and more. The numpy.linalg module allows for complex linear algebra computations, essential for machine learning, scientific simulations, and data analysis. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 8 / 49 Background - What is Numpy? 1.2.3 Why NumPy? (Continued) Some of the key features of NumPy are: 4 Integration with Other Libraries NumPy is the foundation for many scientific computing libraries, such as Pandas, SciPy, and scikit-learn, and is fully compatible with them. This integration facilitates seamless data manipulation, analysis, and machine learning model building. 5 Compatibility with GPU Computing (CuPy) While NumPy itself doesn’t support GPU acceleration, libraries like CuPy provide a nearly identical API that can leverage GPUs. This allows for accelerated computations, making NumPy-compatible code run faster on hardware like NVIDIA GPUs. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 9 / 49 Background - What is Numpy? 1.3 Numpys are Fast: Let’s Verify!! Observe the output: Figure: Was the Numpy Faster? Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 10 / 49 Background - What is Numpy? 1.3.1 Numpys are Fast: Let’s Verify!! Now Try This: Figure: Was the Numpy Faster? Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 11 / 49 n-Dimensional Array. Getting Started with Numpy. 2. Array Creation and Manipulation. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 12 / 49 n-Dimensional Array. 2.1 Numpy - Array: Introduction. The Central feature of Numpy is the array object class. Arrays are similar to lists in Python, except that every element of an array must be of the same dtype. Arrays make operations with large amounts of numeric data very fast and are generally more efficient than lists. Example ( Importing Numpy and Creating Arrays of Zeros): 1 import numpy as np 2 # initialize an all zero array with size 2 X 3: 3 zeros_arr = np. zeros ((2 ,3) ) 4 print ( " A zeros array is \ n " , zeros_arr , " with dimensions " , zeros_arr. shape , " \ n " ) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 13 / 49 n-Dimensional Array. 2.2 Numpy - Array: Type. zero - dimensional arrays: A scalar value represented as a NumPy array with no axes, created using np.array(5). one - dimensional arrays: A linear array of elements, created using np.array([1, 2, 3]), representing a single row or column. Multi or n-dimensional array: An array with multiple dimensions (axes), created using np.array([[1, 2], [3, 4]]) for 2D, and can be extended to higher dimensions as needed. 1 import numpy as np 2 # Create and display zero , one , and n - dimensional arrays 3 zero_dim_array = np. array (5) 4 one_dim_array = np. array ([1 , 2 , 3]) 5 n_dim_array = np. array ([[1 , 2] , [3 , 4]]) 6 for arr in [ zero_dim_array , one_dim_array , n_dim_array ]: 7 print ( f " Array :\ n { arr }\ nDimension : { arr. ndim }\ nData type : { arr. dtype }\ n " ) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 14 / 49 n-Dimensional Array. 2.3 Numpy - Array Dimension: Shape. The function array.shape returns the shape of an array of any dimension.{i.e. a tuple representing the size of each dimension of the array.} 1 For 1-D array: it returns the number of elements in array as (number of elem,) 2 For a 2-D array, it will return (number of rows,number of columns) rows are normally represented asaxis = 0 cols. are normally represented asaxis = 1 3 For a n-D array, it will return (depth, height and width), where shape is depth (number of matrices) shape is height (number of rows) shape is width (number of columns) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 15 / 49 n-Dimensional Array. 2.3.1 Array Dimensions: Shape - Sample Code. Code Implementation: 1 import numpy as np 2 # Create arrays of different dimensions 3 array_0d = np. array (5) 4 array_1d = np. array ([1 , 2 , 3 , 4 , 5]) 5 array_2d = np. array ([[1 , 2 , 3] , [4 , 5 , 6]]) 6 array_3d = np. array ([[[1 , 2] , [3 , 4]] , [[5 , 6] , [7 , 8]]]) 7 # Print arrays with shapes 8 for i , arr in enumerate ([ array_0d , array_1d , array_2d , array_3d ]) : 9 print ( f " { i } D Array :\ n { arr }\ nShape : { arr. shape }\ n " ) 10 Expected Outputs: 1 # Expected Output array_0d : Shape : () 2 # Expected output array_1d : Shape : (5 ,) 3 # Expected Output array_2d : Shape : (2 , 3) 4 # Expected Output array_3d : Shape : (2 , 2 , 2) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 16 / 49 n-Dimensional Array. 2.3.2 Array Dimensions: reshape. reshape(): The reshape method in NumPy changes the shape of an array without altering its data, as long as the total number of elements remains the same before and after reshaping. Example: An array with shape (2, 3) (6 elements) can be reshaped to any shape with 6 elements, like (3, 2) or (1, 6), but reshaping to (4, 2) would raise an error because it needs 8 elements. 1 import numpy as np 2 array = np. array ([[1 , 2 , 3] , [4 , 5 , 6]]) # Shape (2 , 3) 3 reshaped_array = array. reshape (3 , 2) # Reshape to (3 , 2) , keeping 6 elements 4 print ( " Original Shape : " , array. shape , " \ nReshaped Shape : " , reshaped_array. shape ) 5 # Expected Outputs : 6 Original Shape : (2 , 3) 7 Reshaped Shape : (3 , 2) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 17 / 49 n-Dimensional Array. 2.4 How to create an Array? 1 Using in-built function - Arrays with Evenly spaced values: arange: syntax of arange: arange([start,]stop[,step],[,dtype=None]) 1 import numpy as np 2 a = np. arange (1 , 10) 3 print ( a ) 4 x = range (1 , 10) 5 print ( x ) # x is an iterator 6 print ( list ( x ) ) 7 # further arange examples : 8 x = np. arange (10.4) 9 print ( x ) 10 x = np. arange (0.5 , 10.4 , 0.8) 11 print ( x ) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 18 / 49 n-Dimensional Array. 2.4 How to create an Array? 1 Using in-built function - Arrays with Evenly spaced values: linspace: The Syntax is: linpspace(start,stop,num=50,endpoint=True,retstep=False) 1 import numpy as np 2 # 50 values between 1 and 10: 3 print ( np. linspace (1 , 10) ) 4 # 7 values between 1 and 10: 5 print ( np. linspace (1 , 10 , 7) ) 6 # excluding the endpoint : 7 print ( np. linspace (1 , 10 , 7 , endpoint = False ) ) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 19 / 49 n-Dimensional Array. 2.4 How to create an Array? 2 Creating or Initializing Arrays with Ones, Zeros and Empty np.ones: Creates an array of ones as specified by shape. The Syntax is: np.ones(shape, dtype=None) np.zeros: Creates an array of zeros as specified by shape. np.zeros(shape, dtype=None). np.empty: Creates an array of uninitialized values of the specified shape. np.empty(shape, dtype=None). np.eye(N): Creates an identity matrix of shape (N, N) filled with ones on the diagonal and zeros elsewhere. 1 import numpy as np 2 # Create arrays of specified shapes 3 ones_array = np. ones ((2 , 3) ) # Shape : (2 , 3) 4 zeros_array = np. zeros ((3 , 2) ) # Shape : (3 , 2) 5 empty_array = np. empty ((2 , 2) ) # Shape : (2 , 2) 6 identity_matrix = np. eye (3) # Shape : (3 , 3) 7 print ( ones_array , zeros_array , empty_array , identity_matrix , sep = ’\ n \ n ’) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 20 / 49 n-Dimensional Array. 2.4 How to create an Array? 3 By Manipulating Existing Array: np.array: It can be used to create an array from any array-like object, such as lists, tuples, or other arrays. This method converts the input to a NumPy array if it isn’t one already. Example: 1 import numpy as np 2 array_from_list = np. array ([1 , 2 , 3]) # [1 2 3] 3 array_from_tuple = np. array ((4 , 5 , 6) ) # [4 5 6] 4 ar r a y _ f r o m _ n e ste d_ li st = np. array ([[1 , 2 , 3] , [4 , 5 , 6]]) # [[1 2 3] [4 5 6]] 5 print ( array_from_list , array_from_tuple , array_from_nested_list , sep = ’\ n ’) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 21 / 49 n-Dimensional Array. 2.4 How to create an Array? 3 By Manipulating Existing Array: Shape of an existing array: np.zeros(existing_array.shape): Creates an array of zeros with the same shape as existing array. np.ones(existing_array.shape) : Creates an array of ones with the same shape. np.empty(existing_array.shape): Creates an uninitialized array with the same shape, which may contain random values. Example: 1 import numpy as np 2 # Existing Array of Shape :(2 ,3) 3 arr = np. array ([[1 , 2 , 3] , [4 , 5 , 6]]) 4 # Creating Array with Shape of existing array : 5 zeros , ones , empty = np. zeros ( arr. shape ) , np. ones ( arr. shape ) , np. empty ( arr. shape ) # Shape : (2 ,3) 6 print ( arr , zeros , ones , empty , sep = ’\ n ’) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 22 / 49 n-Dimensional Array. 2.4 How to create an Array? 3 By Manipulating Existing Array: Arithmetic Operations: Perform element-wise operations to create a modified array. Copying an Array: Creates an independent copy of the array. Slicing an Array: Creates a view or sub-array of the original array. Example: 1 import numpy as np 2 array = np. array ([1 , 2 , 3]) 3 # Multiplies each element by 2 , result : [2 , 4 , 6] 4 new_array = array * 2 5 # Creates a new array with the same elements 6 copied_array = np. copy ( array ) 7 # Slices elements from index 1 to 3 , result : 8 sliced_array = array [1:2] Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 23 / 49 n-Dimensional Array. 2.4 How to create an Array? 4 By combining or joining existing arrays: Horizontal Stack: np.hstack((array1, array2)) combines arrays in a row-wise manner, aligning them side by side. Vertical Stack: np.vstack((array1, array2)) stacks arrays on top of each other, aligning them in a column-wise manner. Column Stack: np.column_stack((array1, array2)) stacks 1D arrays as columns into a 2D array. Example: 1 import numpy as np 2 arr1 = np. array ([[1 , 2] , [3 , 4]]) # Shape : (2 , 2) 3 arr2 = np. array ([[5 , 6] , [7 , 8]]) # Shape : (2 , 2) 4 # Stacking examples 5 hstacked = np. hstack (( arr1 , arr2 ) ) 6 # Output hstack : [[1 2 5 6] [3 4 7 8]] 7 vstacked = np. vstack (( arr1 , arr2 ) ) 8 # Output vstack [[1 2] [3 4] [5 6] [7 8]] 9 colstacked = np. column_stack (( arr1 , arr2 ) ) 10 # Output column stack : [[1 5] [2 6]] 11 print ( hstacked , vstacked , colstacked , sep = ’\ n ’) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 24 / 49 n-Dimensional Array. 2.4 How to create an Array? 4 By combining or joining existing arrays: Shape Compatibility: For horizontal stacking (np.hstack) and concatenation with axis=1, arrays must have the same number of rows. For vertical stacking (np.vstack) and concatenation with axis=0, arrays must have the same number of columns. If the shapes don’t align correctly for these operations, NumPy will raise a ValueError. Figure: Visualization of Stacking Operation. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 25 / 49 n-Dimensional Array. 2.4 How to create an Array? 4 By combining or joining existing arrays: Concatenate: np.concatenate((array1, array2), axis=0) joins arrays along a specified axis. axis = 0: Concatenate along the rows (vertical stacking). This means the arrays are stacked on top of each other. The number of columns must match across the arrays. axis = 1: Concatenate along the column (horizontal stacking). This means the arrays are placed side by side. The number of rows must match across the arrays. Example: 1 import numpy as np 2 arr1 = np. array ([[1 , 2] , [3 , 4]]) # Shape : (2 , 2) 3 arr2 = np. array ([[5 , 6] , [7 , 8]]) # Shape : (2 , 2) 4 concat_axis0 = np. concatenate (( arr1 , arr2 ) , axis =0) 5 # Concatenate along axis 0 ( vertical ) Shape : (4 , 2) 6 concat_axis1 = np. concatenate (( arr1 , arr2 ) , axis =1) 7 # Concatenate along axis 1 ( horizontal ) Shape : (2 , 4) 8 print ( concat_axis0 , concat_axis1 , sep = ’\ n ’) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 26 / 49 n-Dimensional Array. 2.4 How to create an Array? 4 By combining or joining existing arrays: Concatenate: A Visual Representation. Figure: For 2D-Dimensional Array. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 27 / 49 n-Dimensional Array. 2.4 How to create an Array? 4 By combining or joining existing arrays: Concatenate: A Visual Representation. Figure: For 3D-Dimensional Array. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 28 / 49 n-Dimensional Array. Getting Started with Numpy. 3. Indexing and Slicing. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 29 / 49 n-Dimensional Array. 3.1 Indexing for Numpy Arrays. 1 Indexing: Accessing a specific element or set of elements from an array using its position (or index). For 1D Array: Indexed with a single index.[-] For 2D Array: Indexed with two indices. [row, column] For 3D Array: Indexed with three indices [width, row, column]. You can slice each dimension using [:] notation to extract subarrays. Figure: Indexing in Arrays. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 30 / 49 n-Dimensional Array. 3.1 Indexing for Numpy Arrays. 2 Slicing: Extracting a subset of an array by specifying a range of indices along one or more axes. For 1D Array: Figure: Syntax for various Slicing technique across 1D Array. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 31 / 49 n-Dimensional Array. 3.1 Indexing for Numpy Arrays. 2 Slicing: Extracting a subset of an array by specifying a range of indices along one or more axes. For 2D Array: Figure: Syntax for various Slicing technique across 2D Array. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 32 / 49 n-Dimensional Array. 3.2 Slicing for Numpy Arrays. 2 Slicing: Extracting a subset of an array by specifying a range of indices along one or more axes. For 3D Array: Figure: Syntax for various Slicing technique across 3D Array. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 33 / 49 n-Dimensional Array. 3.3 Code Example: Slicing and Indexing. 1 import numpy as np 2 # Arrays 3 arr1d = np. array ([0 , 1 , 2 , 3 , 4 , 5]) 4 arr2d = np. array ([[0 , 1 , 2] , [3 , 4 , 5] , [6 , 7 , 8]]) 5 arr3d = np. array ([[[0 , 1] , [2 , 3]] , [[4 , 5] , [6 , 7]] , [[8 , 9] , [10 , 11]]]) 6 # Slicing examples 7 print ( " Basic : " , arr1d [1:4] , arr2d [1:3 , 0:2] , arr3d [1:2 , 0:2 , 1:2]) 8 # Output Basic : arr1d :[1 2 3] arr2d :[[3 4] [6 7]] arr3d :[[ ]] 9 print ( " Step : " , arr1d [1:5:2] , arr2d [::2 , 1::2] , arr3d [::2 , ::2 , 1::2]) 10 # Output : Step : [1 3] [ ] [[ ]] These are only representative example, for more check out numpy documentation. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 34 / 49 Array Mathematics With Numpy. Starting with Numpy. 1.Array Mathematics. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 35 / 49 Array Mathematics With Numpy. 4.1 Array Math: Introduction to Universal Functions. One of the core features of NumPy that makes working with ndarray so efficient and convenient is vectorization. 1 Vectorization: Vectorization in NumPy refers to the process of replacing explicit Python loops with optimized, low-level code to perform operations on entire arrays at once. This approach leverages NumPy’s internal implementation, which is written in C, to execute computations much faster than looping over elements in Python. NumPy provides vectorized functions for performing element-wise operations implicitly via so-called ufuncs which is short for “universal functions”. The ufuncs for basic arithmetic operations are add, subtract, divide, multiply, power, and exp (exponential). Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 36 / 49 Array Mathematics With Numpy. 4.1.1 Array Math: Elementary operations with unfuncs| 1 import numpy as np 2 arr1 = np. array ([1 , 2 , 3]) 3 arr2 = np. array ([4 , 5 , 6]) 4 print ( " Add : " , np. add ( arr1 , arr2 ) ) # Output Add : [5 7 9] 5 print ( " Subtract : " , np. subtract ( arr1 , arr2 ) ) 6 # Output Subtract : [ -3 -3 -3] 7 print ( " Divide : " , np. divide ( arr1 , arr2 ) ) 8 # Output Divide : [0.25 0.4 0.5 ] 9 print ( " Multiply : " , np. multiply ( arr1 , arr2 ) ) 10 # Output Multiply : [ 4 10 18] 11 print ( " Power : " , np. power ( arr1 , arr2 ) ) 12 # Output Power : [ 1 32 729] 13 print ( " Exp : " , np. exp ( arr1 ) ) 14 # Output Exp : [ 2.71828183 7.3890561 20.08553692] 1 Vectorization: However, NumPy uses operator overloading so that we can use mathematical operators (+, -, /, *, and **) directly: Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 37 / 49 Array Mathematics With Numpy. 4.2 Array Math: Mostly Used ufuncs|. 1 Vectorization: Figure: Commonly Used Universal Functions. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 38 / 49 Array Mathematics With Numpy. 4.3 Array Math: Broadcasting. All aforementioned element-wise operation is possible due to broadcasting functionalities of numpy. 2 Broadcasting: Broadcasting allows to perform vectorized operations between two arrays even if their dimensions do not match. Example: Adding a scalar to numpy array: Figure: Example Broadcasting Operation - 1. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 39 / 49 Array Mathematics With Numpy. 4.3.1 Array Math: Broadcasting. All aforementioned element-wise operation is possible due to broadcasting functionalities of numpy. 2 Broadcasting: Broadcasting allows to perform vectorized operations between two arrays even if their dimensions do not match. Example: Adding two array: Figure: Example Broadcasting Operation - 2. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 40 / 49 Array Mathematics With Numpy. 4.3.2 Array Math: Broadcasting. All aforementioned element-wise operation is possible due to broadcasting functionalities of numpy. 2 Broadcasting: Broadcasting allows to perform vectorized operations between two arrays even if their dimensions do not match.Dimension doesn’t mean shape, Broadcasting only works with same shape. Example: Cautions: Figure: Example Broadcasting Operation - 3. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 41 / 49 Matrix Operation with Numpy. Matrices and Numpy. 5.Matrix Multiplications. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 42 / 49 Matrix Operation with Numpy. 5.1 Array Math: Matrix Multiplications Matrix multiplication is a fundamental operation in linear algebra and is widely used in areas like machine learning.In NumPy, matrix multiplication can be performed in multiple ways, depending on the types of arrays and the desired outcome. 1 Methods for Matrix Multiplication: Using np.dot: Computes the dot product of two arrays (for 1D vectors, it computes their inner product; for 2D matrices, it performs matrix multiplication). Syntax: np.dot(A, B) Using the @ Operator: This is a shorthand for matrix multiplication and is equivalent to np.dot. Syntax: A @ B Using np.matmul Similar to np.dot, but specifically for matrix multiplication (does not perform element-wise multiplication). Syntax: np.matmul(A, B) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 43 / 49 Matrix Operation with Numpy. 5.1.1 Array Math: Matrix Multiplications 2 Cautions for Matrix Multiplications: Shape Requirements: For two matrices A and B to be multiplied, the number of columns in A must equal the number of rows in B. For instance, if A is of shape (m,n) and B is of shape (n,p), the result will be of shape (m,p). Broadcasting: Matrix multiplication doesn’t support broadcasting in the same way element-wise operations do. Both matrices need to have compatible shapes for multiplication. 3 Example: 1 import numpy as np 2 # Define two matrices 3 A = np. array ([[1 , 2 , 3] , [4 , 5 , 6]]) 4 B = np. array ([[7 , 8] , [9 , 10] , [11 , 12]]) 5 # Matrix multiplication using np. dot 6 result_dot = np. dot (A , B ) 7 print ( " Result with np. dot :\ n " , result_dot ) # Output shape : (2 , 2) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 44 / 49 Matrix Operation with Numpy. 5.1.2 Array Math: Matrix Multiplications 3 Example: 1 import numpy as np 2 # Define two matrices 3 A = np. array ([[1 , 2 , 3] , [4 , 5 , 6]]) 4 B = np. array ([[7 , 8] , [9 , 10] , [11 , 12]]) 5 # Matrix multiplication using @ operator 6 result_at = A @ B 7 print ( " Result with @ operator :\ n " , result_at ) # Output shape : (2 , 2) 8 # Matrix multiplication using np. matmul 9 result_matmul = np. matmul (A , B ) 10 print ( " Result with np. matmul :\ n " , result_matmul ) # Output shape : (2 , 2) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 45 / 49 Linear Algebra with Numpy. Linear Algebra with Numpy. 6.Introduction to np.linalg| Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 46 / 49 Linear Algebra with Numpy. 6.1 Linear Algebra with Numpy. NumPy provides a powerful suite of linear algebra functions that make it easier to perform operations commonly used in mathematics,and Machine Learning. Here’s an overview of some key functions with examples. 1 Matrix Inversion: Finds the inverse of a square matrix (if it exists). Syntax: np.linalg.inv(A) 2 Determinant: Computes the determinant of a matrix. Syntax: np.linalg.det(A) 3 Norms: Computes matrix/vector norms (e.g., Euclidean norm). Syntax: np.linalg.norm(A, ord=) 4 Solving Linear Systems: Solves equations of the form Ax = B. Syntax: np.linalg.solve(A, B) Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 47 / 49 Linear Algebra with Numpy. 6.1 Linear Algebra with Numpy. Sample Code Implementations: 1 import numpy as np 2 A = np. array ([[1 , 2] , [3 , 4]]) 3 B = np. array ([5 , 6]) 4 print ( " Inverse :\ n " , np. linalg. inv ( A ) ) 5 # Output : Inverse : [[ -2. 1. ] , [ 1.5 -0.5]] 6 print ( " Determinant : " , np. linalg. det ( A ) ) 7 # Output : Determinant : -2.0 8 print ( " Frobenius Norm : " , np. linalg. norm (A , ’ fro ’) ) 9 # Output : Frobenius Norm : 5.4772 10 print ( " 2 - Norm ( Euclidean ) : " , np. linalg. norm ( A ) ) 11 # Outptut : 2 - Norm ( Euclidean ) : 5.4772 12 print ( " Solution x : " , np. linalg. solve (A , B ) ) 13 # Output : Solution x : [ -4. 4.5] Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 48 / 49 Final Slide. Towards Worksheet - 1. Thank You. Siman Giri (Workshop - 01) Introduction to Numpy. November - 5 - 2024 49 / 49