Essential numpy before you start your Machine Learning journey in python Linkedin: https://www.linkedin.com/in/smrati/ Twitter: https://twitter.com/SmratiKatiyar importing numpy Creating a numpy array NumPy offers various ways to create arrays. Here are some of the different methods for creating NumPy arrays: 1. Using Lists or Tuples: You can create a NumPy array from a Python list or tuple. 2. Using NumPy Functions: NumPy provides functions like np.zeros() , np.ones() , np.empty() , and np.full() to create arrays filled with specific values. import numpy as np import numpy as np # Create an array from a list arr_from_list = np.array([1, 2, 3, 4, 5]) # Create an array from a tuple arr_from_tuple = np.array((1, 2, 3, 4, 5)) import numpy as np # Create an array of zeros zeros_array = np.zeros(5) # Create an array of ones ones_array = np.ones(5) # Create an empty array (initialized with random values) empty_array = np.empty(5) # Create an array filled with a specific value
3. Using Ranges: You can create arrays with regularly spaced values using functions like np.arange() and np.linspace() . 4. Using Random Data: NumPy provides functions in the np.random module to generate arrays with random data. 5. Using Identity Matrix: You can create a 2D identity matrix using np.eye() . 6. Using Existing Data: You can create a NumPy array from existing data, such as a Python list or another NumPy array. filled_array = np.full(5, 7) # Creates an array of 5 elements, each with the value 7 import numpy as np # Create an array with values from 0 to 4 (exclusive) range_array = np.arange(0, 5) # Create an array of 5 equally spaced values between 0 and 1 (inclusive) linspace_array = np.linspace(0, 1, 5) import numpy as np # Create an array of random values between 0 and 1 random_array = np.random.rand(5) # Create a 2D array of random integers between 1 and 100 random_int_array = np.random.randint(1, 101, size=(3, 3)) import numpy as np # Create a 3x3 identity matrix identity_matrix = np.eye(3) import numpy as np # Create an array from an existing list existing_list = [1, 2, 3] array_from_list = np.array(existing_list) # Create an array from an existing NumPy array
These are some of the common ways to create NumPy arrays. Depending on your specific needs and data, you can choose the most appropriate method for creating your array. Element wise addition , subtraction , multiplication and division Output: Numpy array and scalar interaction to each element (known as broadcasting) Output: existing_array = np.array([4, 5, 6]) array_from_existing = np.array(existing_array) import numpy as np x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) plus = x + y minus = x - y mut = x * y div = x / y mod = y % x print(plus) print(minus) print(mut) print(div) print(mod) [5 7 9] [-3 -3 -3] [ 4 10 18] [0.25 0.4 0.5 ] [0 1 0] import numpy as np x = np.array([1, 2, 3]) print(x + 2) [3 4 5]
Checking shape and datatype of numpy array Output: Matrix multiplication using numpy array Output: vector, matrix and tensor In NumPy, you can represent vectors, matrices, and tensors using arrays. Here's an explanation of the differences between these three concepts with NumPy examples: 1. Vector: A vector is a one-dimensional array that represents a list of numbers or values. It has a single row (or column) of elements. In NumPy, you can create a vector using a 1D array. import numpy as np x = np.array([1, 2, 3]) y = np.array([1.7, 2, 3]) print(x.shape) print(x.dtype) print(y.dtype) (3,) int64 float64 import numpy as np x = np.array([[1, 2, 3], [1, 2, 3]]) y = np.array([[1, 2], [1, 2], [1, 2]]) print(x.shape) print(y.shape) print(np.matmul(x, y)) (2, 3) (3, 2) [[ 6 12] [ 6 12]] import numpy as np
2. Matrix: A matrix is a two-dimensional array where each element is identified by two indices (rows and columns). In NumPy, you can create a matrix using a 2D array. 3. Tensor: A tensor is a multi-dimensional array with more than two dimensions. It can have three or more dimensions. In NumPy, you can create tensors using arrays with more than two dimensions. In the examples above: vector is a 1D NumPy array with shape (5,) . matrix is a 2D NumPy array with shape (3, 3) . tensor is a 3D NumPy array with shape (2, 2, 2) . To summarize, the key difference between these concepts is their dimensionality: Vectors are 1D arrays. Matrices are 2D arrays. Tensors are multi-dimensional arrays with three or more dimensions. Broadcasting Broadcasting in NumPy is a powerful feature that allows you to perform operations on arrays of different shapes, making them compatible for element-wise operations without explicitly creating new arrays to match their shapes. In simple terms, broadcasting helps NumPy "stretch" smaller arrays to make them compatible with larger arrays, so you can perform operations on them efficiently. Here's a simplified explanation of broadcasting with an example: Suppose you have two NumPy arrays: # Creating a vector vector = np.array([1, 2, 3, 4, 5]) import numpy as np # Creating a matrix matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) import numpy as np # Creating a tensor (3D example) tensor = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
1. Array A with shape (3, 3) : 2. Array B with shape (1, 3) : Now, you want to add these two arrays together element-wise. Normally, you would need arrays with the same shape for element-wise addition, but broadcasting allows you to perform this operation without explicitly copying or reshaping the smaller array. Here's how broadcasting works in this case: 1. NumPy identifies that the dimensions of the arrays are not the same. 2. It checks if the dimensions are compatible for broadcasting by comparing them from the right side (trailing dimensions). 3. In this example, the dimensions are compatible because the size of the last dimension of array B (which is 3) matches the size of the corresponding dimension in array A . 4. NumPy effectively "stretches" or "broadcasts" the smaller array B to match the shape of the larger array A , making it look like this: 5. Now, NumPy can perform element-wise addition between the two arrays: So, broadcasting allows you to perform operations between arrays of different shapes by automatically making them compatible, without the need for manual reshaping or copying of data. This makes your code more concise and efficient when working with NumPy arrays. Access element in numpy arrays Accessing elements in NumPy arrays is straightforward and involves specifying the indices of the elements you want to retrieve. NumPy supports several ways to access elements, including basic A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [10, 20, 30] B = [[10, 20, 30], [10, 20, 30], [10, 20, 30]] Result = A + B = [[1+10, 2+20, 3+30], [4+10, 5+20, 6+30], [7+10, 8+20, 9+30]] = [[11, 22, 33], [14, 25, 36], [17, 28, 39]]
indexing, slicing, and fancy indexing. Let's go through each of these methods: 1. Basic Indexing: To access a single element in a NumPy array, you can use square brackets and specify the row and column (or just a single index for 1D arrays). 2. Slicing: You can access multiple elements or subarrays using slicing. Slicing allows you to specify a range of indices. 3. Boolean Indexing (Fancy Indexing): You can use boolean arrays to filter elements based on a condition. 4. Integer Array Indexing (Fancy Indexing): You can use integer arrays to access elements by specifying the indices explicitly. import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Access a single element element = arr[0, 1] # Accesses the element at row 0, column 1 (value: 2) import numpy as np arr = np.array([0, 1, 2, 3, 4, 5]) # Access a slice of elements subarray = arr[2:5] # Retrieves elements from index 2 to 4 (values: [2, 3, 4]) # Access a subarray of a 2D array subarray_2d = arr[1:3, 1:3] # Retrieves a 2x2 subarray from the original 2D array import numpy as np arr = np.array([1, 2, 3, 4, 5]) # Create a boolean mask mask = (arr % 2 == 0) # Use the mask to access elements that meet the condition even_numbers = arr[mask] # Retrieves elements [2, 4]
5. Negative Indexing: You can use negative indices to access elements from the end of an array. Remember that indexing in NumPy is zero-based, meaning the first element is accessed using index 0. Additionally, indexing and slicing can be applied to both 1D and multidimensional (2D, 3D, etc.) arrays, with different syntax for each dimension. import numpy as np arr = np.array([10, 20, 30, 40, 50]) # Create an array of indices indices = np.array([1, 3]) # Use the indices to access specific elements selected_elements = arr[indices] # Retrieves elements [20, 40] import numpy as np arr = np.array([1, 2, 3, 4, 5]) # Access the last element using negative indexing last_element = arr[-1] # Retrieves the last element (value: 5)

Essential numpy before you start your Machine Learning journey in python.pdf

  • 1.
    Essential numpy beforeyou start your Machine Learning journey in python Linkedin: https://www.linkedin.com/in/smrati/ Twitter: https://twitter.com/SmratiKatiyar importing numpy Creating a numpy array NumPy offers various ways to create arrays. Here are some of the different methods for creating NumPy arrays: 1. Using Lists or Tuples: You can create a NumPy array from a Python list or tuple. 2. Using NumPy Functions: NumPy provides functions like np.zeros() , np.ones() , np.empty() , and np.full() to create arrays filled with specific values. import numpy as np import numpy as np # Create an array from a list arr_from_list = np.array([1, 2, 3, 4, 5]) # Create an array from a tuple arr_from_tuple = np.array((1, 2, 3, 4, 5)) import numpy as np # Create an array of zeros zeros_array = np.zeros(5) # Create an array of ones ones_array = np.ones(5) # Create an empty array (initialized with random values) empty_array = np.empty(5) # Create an array filled with a specific value
  • 2.
    3. Using Ranges: Youcan create arrays with regularly spaced values using functions like np.arange() and np.linspace() . 4. Using Random Data: NumPy provides functions in the np.random module to generate arrays with random data. 5. Using Identity Matrix: You can create a 2D identity matrix using np.eye() . 6. Using Existing Data: You can create a NumPy array from existing data, such as a Python list or another NumPy array. filled_array = np.full(5, 7) # Creates an array of 5 elements, each with the value 7 import numpy as np # Create an array with values from 0 to 4 (exclusive) range_array = np.arange(0, 5) # Create an array of 5 equally spaced values between 0 and 1 (inclusive) linspace_array = np.linspace(0, 1, 5) import numpy as np # Create an array of random values between 0 and 1 random_array = np.random.rand(5) # Create a 2D array of random integers between 1 and 100 random_int_array = np.random.randint(1, 101, size=(3, 3)) import numpy as np # Create a 3x3 identity matrix identity_matrix = np.eye(3) import numpy as np # Create an array from an existing list existing_list = [1, 2, 3] array_from_list = np.array(existing_list) # Create an array from an existing NumPy array
  • 3.
    These are someof the common ways to create NumPy arrays. Depending on your specific needs and data, you can choose the most appropriate method for creating your array. Element wise addition , subtraction , multiplication and division Output: Numpy array and scalar interaction to each element (known as broadcasting) Output: existing_array = np.array([4, 5, 6]) array_from_existing = np.array(existing_array) import numpy as np x = np.array([1, 2, 3]) y = np.array([4, 5, 6]) plus = x + y minus = x - y mut = x * y div = x / y mod = y % x print(plus) print(minus) print(mut) print(div) print(mod) [5 7 9] [-3 -3 -3] [ 4 10 18] [0.25 0.4 0.5 ] [0 1 0] import numpy as np x = np.array([1, 2, 3]) print(x + 2) [3 4 5]
  • 4.
    Checking shape anddatatype of numpy array Output: Matrix multiplication using numpy array Output: vector, matrix and tensor In NumPy, you can represent vectors, matrices, and tensors using arrays. Here's an explanation of the differences between these three concepts with NumPy examples: 1. Vector: A vector is a one-dimensional array that represents a list of numbers or values. It has a single row (or column) of elements. In NumPy, you can create a vector using a 1D array. import numpy as np x = np.array([1, 2, 3]) y = np.array([1.7, 2, 3]) print(x.shape) print(x.dtype) print(y.dtype) (3,) int64 float64 import numpy as np x = np.array([[1, 2, 3], [1, 2, 3]]) y = np.array([[1, 2], [1, 2], [1, 2]]) print(x.shape) print(y.shape) print(np.matmul(x, y)) (2, 3) (3, 2) [[ 6 12] [ 6 12]] import numpy as np
  • 5.
    2. Matrix: A matrixis a two-dimensional array where each element is identified by two indices (rows and columns). In NumPy, you can create a matrix using a 2D array. 3. Tensor: A tensor is a multi-dimensional array with more than two dimensions. It can have three or more dimensions. In NumPy, you can create tensors using arrays with more than two dimensions. In the examples above: vector is a 1D NumPy array with shape (5,) . matrix is a 2D NumPy array with shape (3, 3) . tensor is a 3D NumPy array with shape (2, 2, 2) . To summarize, the key difference between these concepts is their dimensionality: Vectors are 1D arrays. Matrices are 2D arrays. Tensors are multi-dimensional arrays with three or more dimensions. Broadcasting Broadcasting in NumPy is a powerful feature that allows you to perform operations on arrays of different shapes, making them compatible for element-wise operations without explicitly creating new arrays to match their shapes. In simple terms, broadcasting helps NumPy "stretch" smaller arrays to make them compatible with larger arrays, so you can perform operations on them efficiently. Here's a simplified explanation of broadcasting with an example: Suppose you have two NumPy arrays: # Creating a vector vector = np.array([1, 2, 3, 4, 5]) import numpy as np # Creating a matrix matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) import numpy as np # Creating a tensor (3D example) tensor = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
  • 6.
    1. Array Awith shape (3, 3) : 2. Array B with shape (1, 3) : Now, you want to add these two arrays together element-wise. Normally, you would need arrays with the same shape for element-wise addition, but broadcasting allows you to perform this operation without explicitly copying or reshaping the smaller array. Here's how broadcasting works in this case: 1. NumPy identifies that the dimensions of the arrays are not the same. 2. It checks if the dimensions are compatible for broadcasting by comparing them from the right side (trailing dimensions). 3. In this example, the dimensions are compatible because the size of the last dimension of array B (which is 3) matches the size of the corresponding dimension in array A . 4. NumPy effectively "stretches" or "broadcasts" the smaller array B to match the shape of the larger array A , making it look like this: 5. Now, NumPy can perform element-wise addition between the two arrays: So, broadcasting allows you to perform operations between arrays of different shapes by automatically making them compatible, without the need for manual reshaping or copying of data. This makes your code more concise and efficient when working with NumPy arrays. Access element in numpy arrays Accessing elements in NumPy arrays is straightforward and involves specifying the indices of the elements you want to retrieve. NumPy supports several ways to access elements, including basic A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [10, 20, 30] B = [[10, 20, 30], [10, 20, 30], [10, 20, 30]] Result = A + B = [[1+10, 2+20, 3+30], [4+10, 5+20, 6+30], [7+10, 8+20, 9+30]] = [[11, 22, 33], [14, 25, 36], [17, 28, 39]]
  • 7.
    indexing, slicing, andfancy indexing. Let's go through each of these methods: 1. Basic Indexing: To access a single element in a NumPy array, you can use square brackets and specify the row and column (or just a single index for 1D arrays). 2. Slicing: You can access multiple elements or subarrays using slicing. Slicing allows you to specify a range of indices. 3. Boolean Indexing (Fancy Indexing): You can use boolean arrays to filter elements based on a condition. 4. Integer Array Indexing (Fancy Indexing): You can use integer arrays to access elements by specifying the indices explicitly. import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Access a single element element = arr[0, 1] # Accesses the element at row 0, column 1 (value: 2) import numpy as np arr = np.array([0, 1, 2, 3, 4, 5]) # Access a slice of elements subarray = arr[2:5] # Retrieves elements from index 2 to 4 (values: [2, 3, 4]) # Access a subarray of a 2D array subarray_2d = arr[1:3, 1:3] # Retrieves a 2x2 subarray from the original 2D array import numpy as np arr = np.array([1, 2, 3, 4, 5]) # Create a boolean mask mask = (arr % 2 == 0) # Use the mask to access elements that meet the condition even_numbers = arr[mask] # Retrieves elements [2, 4]
  • 8.
    5. Negative Indexing: Youcan use negative indices to access elements from the end of an array. Remember that indexing in NumPy is zero-based, meaning the first element is accessed using index 0. Additionally, indexing and slicing can be applied to both 1D and multidimensional (2D, 3D, etc.) arrays, with different syntax for each dimension. import numpy as np arr = np.array([10, 20, 30, 40, 50]) # Create an array of indices indices = np.array([1, 3]) # Use the indices to access specific elements selected_elements = arr[indices] # Retrieves elements [20, 40] import numpy as np arr = np.array([1, 2, 3, 4, 5]) # Access the last element using negative indexing last_element = arr[-1] # Retrieves the last element (value: 5)