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

Smrati Kumar Katiyar
Smrati Kumar KatiyarWrite codes at askme.com en Getit Infoservices Pvt. Ltd.

This is a very quick tutorial in numpy for machine learnign and deep learning practitioner.

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)

Recomendados

NUMPY-2.pptx por
NUMPY-2.pptxNUMPY-2.pptx
NUMPY-2.pptxMahendraVusa
30 vistas91 diapositivas
NumPy.pptx por
NumPy.pptxNumPy.pptx
NumPy.pptxEN1036VivekSingh
158 vistas44 diapositivas
arraycreation.pptx por
arraycreation.pptxarraycreation.pptx
arraycreation.pptxsathya930629
8 vistas13 diapositivas
CAP776Numpy (2).ppt por
CAP776Numpy (2).pptCAP776Numpy (2).ppt
CAP776Numpy (2).pptChhaviCoachingCenter
4 vistas88 diapositivas
CAP776Numpy.ppt por
CAP776Numpy.pptCAP776Numpy.ppt
CAP776Numpy.pptkdr52121
17 vistas88 diapositivas
Numpy - Array.pdf por
Numpy - Array.pdfNumpy - Array.pdf
Numpy - Array.pdfAnkitaArjunDevkate
133 vistas21 diapositivas

Más contenido relacionado

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

NUMPY por
NUMPY NUMPY
NUMPY SharmilaChidaravalli
6.3K vistas24 diapositivas
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH... por
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...DineshThallapelly
5 vistas18 diapositivas
CE344L-200365-Lab2.pdf por
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfUmarMustafa13
5 vistas1 diapositiva
Introduction to NumPy por
Introduction to NumPyIntroduction to NumPy
Introduction to NumPyHuy Nguyen
774 vistas41 diapositivas
Introduction to NumPy (PyData SV 2013) por
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)PyData
19.2K vistas41 diapositivas
Scientific Computing with Python - NumPy | WeiYuan por
Scientific Computing with Python - NumPy | WeiYuanScientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuanWei-Yuan Chang
516 vistas77 diapositivas

Similar a Essential numpy before you start your Machine Learning journey in python.pdf(20)

ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH... por DineshThallapelly
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
ACFrOgAabSLW3ZCRLJ0i-To_2fPk_pA9QThyDKNNlA3VK282MnXaLGJa7APKD15-TW9zT_QI98dAH...
Introduction to NumPy por Huy Nguyen
Introduction to NumPyIntroduction to NumPy
Introduction to NumPy
Huy Nguyen774 vistas
Introduction to NumPy (PyData SV 2013) por PyData
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
PyData19.2K vistas
Scientific Computing with Python - NumPy | WeiYuan por Wei-Yuan Chang
Scientific Computing with Python - NumPy | WeiYuanScientific Computing with Python - NumPy | WeiYuan
Scientific Computing with Python - NumPy | WeiYuan
Wei-Yuan Chang516 vistas
Data Manipulation with Numpy and Pandas in PythonStarting with N por OllieShoresna
Data Manipulation with Numpy and Pandas in PythonStarting with NData Manipulation with Numpy and Pandas in PythonStarting with N
Data Manipulation with Numpy and Pandas in PythonStarting with N
OllieShoresna5 vistas
Numpy python cheat_sheet por Zahid Hasan
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
Zahid Hasan391 vistas
Arrays in python por Lifna C.S
Arrays in pythonArrays in python
Arrays in python
Lifna C.S1.5K vistas
Python - Numpy/Pandas/Matplot Machine Learning Libraries por Andrew Ferlitsch
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Andrew Ferlitsch3.5K vistas

Último

CRM stick or twist workshop por
CRM stick or twist workshopCRM stick or twist workshop
CRM stick or twist workshopinfo828217
14 vistas16 diapositivas
AZConf 2023 - Considerations for LLMOps: Running LLMs in production por
AZConf 2023 - Considerations for LLMOps: Running LLMs in productionAZConf 2023 - Considerations for LLMOps: Running LLMs in production
AZConf 2023 - Considerations for LLMOps: Running LLMs in productionSARADINDU SENGUPTA
9 vistas16 diapositivas
LIVE OAK MEMORIAL PARK.pptx por
LIVE OAK MEMORIAL PARK.pptxLIVE OAK MEMORIAL PARK.pptx
LIVE OAK MEMORIAL PARK.pptxms2332always
8 vistas6 diapositivas
PyData Global 2022 - Things I learned while running neural networks on microc... por
PyData Global 2022 - Things I learned while running neural networks on microc...PyData Global 2022 - Things I learned while running neural networks on microc...
PyData Global 2022 - Things I learned while running neural networks on microc...SARADINDU SENGUPTA
5 vistas12 diapositivas
GDG Cloud Community Day 2022 - Managing data quality in Machine Learning por
GDG Cloud Community Day 2022 -  Managing data quality in Machine LearningGDG Cloud Community Day 2022 -  Managing data quality in Machine Learning
GDG Cloud Community Day 2022 - Managing data quality in Machine LearningSARADINDU SENGUPTA
5 vistas11 diapositivas
AvizoImageSegmentation.pptx por
AvizoImageSegmentation.pptxAvizoImageSegmentation.pptx
AvizoImageSegmentation.pptxnathanielbutterworth1
7 vistas14 diapositivas

Último(20)

CRM stick or twist workshop por info828217
CRM stick or twist workshopCRM stick or twist workshop
CRM stick or twist workshop
info82821714 vistas
AZConf 2023 - Considerations for LLMOps: Running LLMs in production por SARADINDU SENGUPTA
AZConf 2023 - Considerations for LLMOps: Running LLMs in productionAZConf 2023 - Considerations for LLMOps: Running LLMs in production
AZConf 2023 - Considerations for LLMOps: Running LLMs in production
LIVE OAK MEMORIAL PARK.pptx por ms2332always
LIVE OAK MEMORIAL PARK.pptxLIVE OAK MEMORIAL PARK.pptx
LIVE OAK MEMORIAL PARK.pptx
ms2332always8 vistas
PyData Global 2022 - Things I learned while running neural networks on microc... por SARADINDU SENGUPTA
PyData Global 2022 - Things I learned while running neural networks on microc...PyData Global 2022 - Things I learned while running neural networks on microc...
PyData Global 2022 - Things I learned while running neural networks on microc...
GDG Cloud Community Day 2022 - Managing data quality in Machine Learning por SARADINDU SENGUPTA
GDG Cloud Community Day 2022 -  Managing data quality in Machine LearningGDG Cloud Community Day 2022 -  Managing data quality in Machine Learning
GDG Cloud Community Day 2022 - Managing data quality in Machine Learning
Games, Queries, and Argumentation Frameworks: Time for a Family Reunion por Bertram Ludäscher
Games, Queries, and Argumentation Frameworks: Time for a Family ReunionGames, Queries, and Argumentation Frameworks: Time for a Family Reunion
Games, Queries, and Argumentation Frameworks: Time for a Family Reunion
Running PostgreSQL in a Kubernetes cluster: CloudNativePG por Nick Ivanov
Running PostgreSQL in a Kubernetes cluster: CloudNativePGRunning PostgreSQL in a Kubernetes cluster: CloudNativePG
Running PostgreSQL in a Kubernetes cluster: CloudNativePG
Nick Ivanov7 vistas
Pydata Global 2023 - How can a learnt model unlearn something por SARADINDU SENGUPTA
Pydata Global 2023 - How can a learnt model unlearn somethingPydata Global 2023 - How can a learnt model unlearn something
Pydata Global 2023 - How can a learnt model unlearn something
Product Research sample.pdf por AllenSingson
Product Research sample.pdfProduct Research sample.pdf
Product Research sample.pdf
AllenSingson35 vistas
Lack of communication among family.pptx por ahmed164023
Lack of communication among family.pptxLack of communication among family.pptx
Lack of communication among family.pptx
ahmed16402316 vistas
Analytics Center of Excellence | Data CoE |Analytics CoE| WNS Triange por RNayak3
Analytics Center of Excellence | Data CoE |Analytics CoE| WNS TriangeAnalytics Center of Excellence | Data CoE |Analytics CoE| WNS Triange
Analytics Center of Excellence | Data CoE |Analytics CoE| WNS Triange
RNayak35 vistas
4_4_WP_4_06_ND_Model.pptx por d6fmc6kwd4
4_4_WP_4_06_ND_Model.pptx4_4_WP_4_06_ND_Model.pptx
4_4_WP_4_06_ND_Model.pptx
d6fmc6kwd47 vistas
Data about the sector workshop por info828217
Data about the sector workshopData about the sector workshop
Data about the sector workshop
info82821729 vistas
6498-Butun_Beyinli_Cocuq-Daniel_J.Siegel-Tina_Payne_Bryson-2011-259s.pdf por 10urkyr34
6498-Butun_Beyinli_Cocuq-Daniel_J.Siegel-Tina_Payne_Bryson-2011-259s.pdf6498-Butun_Beyinli_Cocuq-Daniel_J.Siegel-Tina_Payne_Bryson-2011-259s.pdf
6498-Butun_Beyinli_Cocuq-Daniel_J.Siegel-Tina_Payne_Bryson-2011-259s.pdf
10urkyr347 vistas

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

  • 1. 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
  • 2. 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
  • 3. 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]
  • 4. 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
  • 5. 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]]])
  • 6. 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]]
  • 7. 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]
  • 8. 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)