SlideShare a Scribd company logo
1 of 35
NUMPY
Numerical Computing in Python
By
Kirti Verma
AP, CSE
LNCTE
1
What is Numpy?
• Numpy, Scipy, and Matplotlib provide MATLAB-like functionality in python.
• Numpy Features:
• Typed multidimentional arrays (matrices)
• Fast numerical computations (matrix math)
• High-level math functions
2
Why do we need NumPy
• Python does numerical computations slowly.
• 1000 x 1000 matrix multiply
• Python triple loop takes > 10 min.
• Numpy takes ~0.03 seconds
import numpy as np
print(np.__version__)
arr=np.array([1,2,3,4,5]) #list as array
print(arr)
print(type(arr))
arr=np.array([1,2,3,4,5])
arr=np.array((1,2,3,4,5)) # tuple as array
3
NumPy Overview
1. Arrays
2. Shaping and transposition
3. Mathematical Operations
4. Indexing and slicing
5. Broadcasting
4
Arrays
Structured lists of numbers.
• Vectors : 1D array
• Matrices: nD matrices
• Images: 3D arrays
• Tensors: Generalised multi dimensional arrays
5
Arrays
Structured lists of numbers.
• Vectors
• Matrices
• Images
• Tensors
• ConvNets
𝑝𝑥
𝑝𝑦
𝑝𝑧
𝑎11 ⋯ 𝑎1𝑛
⋮ ⋱ ⋮
𝑎𝑚1 ⋯ 𝑎𝑚𝑛
6
Arrays
Structured lists of numbers.
• Vectors
• Matrices
• Images
• Tensors
• ConvNets
7
Arrays
Structured lists of numbers.
• Vectors
• Matrices
• Images
• Tensors
• ConvNets
8
Arrays, Basic Properties
import numpy as np
a = np.array([[1,2,3],[4,5,6]],dtype=np.float32)
print a.ndim, a.shape, a.dtype
1. Arrays can have any number of dimensions, including zero (a scalar).
2. Arrays are typed: np.uint8, np.int64, np.float32, np.float64
3. Arrays are dense. Each element of the array exists and has the same type.
9
Arrays, creation
• np.ones, np.zeros
• np.arange
• np.concatenate
• np.astype
• np.zeros_like, np.ones_like
• np.random.random
10
Arrays, creation
• np.ones, np.zeros
• np.arange
• np.concatenate
• np.astype
• np.zeros_like, np.ones_like
• np.random.random
11
Arrays, creation
• np.ones, np.zeros
• np.arange
• np.concatenate
• np.astype
• np.zeros_like, np.ones_like
• np.random.random
12
Arrays, creation
• np.ones, np.zeros
• np.arange
• np.concatenate
• np.astype
• np.zeros_like, np.ones_like
• np.random.random
13
Arrays, creation
• np.ones, np.zeros
• np.arange
• np.concatenate
• np.astype
• np.zeros_like, np.ones_like
• np.random.random
14
Arrays, creation
• np.ones, np.zeros
• np.arange
• np.concatenate
• np.astype
• np.zeros_like, np.ones_like
• np.random.random
15
Arrays, creation
• np.ones, np.zeros
• np.arange
• np.concatenate
• np.astype
• np.zeros_like, np.ones_like
• np.random.random
16
Arrays, danger zone
• Must be dense, no holes.
• Must be one type
• Cannot combine arrays of different shape
17
Shaping
a = np.array([1,2,3,4,5,6])
a = a.reshape(3,2)
a = a.reshape(2,-1)
a = a.ravel()
1. Total number of elements cannot change.
2. Use -1 to infer (when axis shape is not known to as, first option
is mandatory and rest axis are adjusted ) axis shape
3. Row-major by default (MATLAB is column-major)
18
Return values
• Numpy functions return either views or copies.
• Views share data with the original array, like references in Java/C++. Altering
entries of a view, changes the same entries in the original.
• The numpy documentation says which functions return views or copies
• np.copy, np.view make explicit copies and views.
19
Transposition
a = np.arange(10).reshape(5,2)
a = a.T
a = a.transpose((1,0))
np.transpose permutes axes.
a.T transposes the first two axes.
20
Saving and loading arrays
np.savez(‘data.npz’, a=a)
data = np.load(‘data.npz’)
a = data[‘a’]
1. NPZ files can hold multiple arrays
2. np.savez_compressed similar.
21
Image arrays
Images are 3D arrays: width, height, and channels
Common image formats:
height x width x RGB (band-interleaved)
height x width (band-sequential)
Gotchas(commonly done errors in proramming):
Channels may also be BGR (OpenCV does this)
May be [width x height], not [height x width]
22
Saving and Loading Images
SciPy: skimage.io.imread,skimage.io.imsave
height x width x RGB
PIL / Pillow: PIL.Image.open, Image.save
width x height x RGB
OpenCV: cv2.imread, cv2.imwrite
height x width x BGR
23
Mathematical operators
• Arithmetic operations are element-wise
• Logical operator return a bool array
• In place operations modify the array
24
Mathematical operators
• Arithmetic operations are element-wise
• Logical operator return a bool array
• In place operations modify the array
25
Mathematical operators
• Arithmetic operations are element-wise
• Logical operator return a bool array
• In place operations modify the array
26
Mathematical operators
• Arithmetic operations are element-wise
• Logical operator return a bool array
• In place operations modify the array
27
Math, upcasting
Just as in Python and Java, the result of a math operator is cast to the more
general or precise datatype.
uint64 + uint16 => uint64
float32 / int32 => float32
Warning: upcasting does not prevent overflow/underflow. You must manually
cast first.
Use case: images often stored as uint8. You should convert to float32 or float64
before doing math.
28
Math, universal functions
Also called ufuncs
Element-wise
Examples:
• np.exp
• np.sqrt
• np.sin
• np.cos
• np.isnan
29
Math, universal functions
Also called ufuncs
Element-wise
Examples:
• np.exp
• np.sqrt
• np.sin
• np.cos
• np.isnan
30
Indexing
x[0,0] # top-left element
x[0,-1] # first row, last column
x[0,:] # first row (many entries)
x[:,0] # first column (many entries)
Notes:
• Zero-indexing
• Multi-dimensional indices are comma-separated (i.e., a tuple)
31
Indexing, slices and arrays
I[1:-1,1:-1] # select all but one-pixel
border
I = I[:,:,::-1] # swap channel order
I[I<10] = 0 # set dark pixels to black
I[[1,3], :] # select 2nd and 4th row
1. Slices are views. Writing to a slice overwrites the original array.
2. Can also index by a list or boolean array.
32
Python Slicing
Syntax: start:stop:step
a = list(range(10))
a[:3] # indices 0, 1, 2
a[-3:] # indices 7, 8, 9
a[3:8:2] # indices 3, 5, 7
a[4:1:-1] # indices 4, 3, 2 (this one is tricky)
33
Axes
a.sum() # sum all entries
a.sum(axis=0) # sum over rows
a.sum(axis=1) # sum over columns
a.sum(axis=1, keepdims=True)
1. Use the axis parameter to control which axis NumPy operates on
2. Typically, the axis specified will disappear, keepdims keeps all dimensions
34
35

More Related Content

Similar to L 5 Numpy final ppt kirti.pptx

NUMPY [Autosaved] .pptx
NUMPY [Autosaved]                    .pptxNUMPY [Autosaved]                    .pptx
NUMPY [Autosaved] .pptxcoolmanbalu123
 
Lenguaje python en I+D. Numpy, Sympy y Pandas
Lenguaje python en I+D. Numpy, Sympy y PandasLenguaje python en I+D. Numpy, Sympy y Pandas
Lenguaje python en I+D. Numpy, Sympy y PandasJosé Luis Muñoz Meza
 
Python advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmPython advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmJohn(Qiang) Zhang
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functionsjoellivz
 
DAA - chapter 1.pdf
DAA - chapter 1.pdfDAA - chapter 1.pdf
DAA - chapter 1.pdfASMAALWADEE2
 
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessAccelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessIgor Sfiligoi
 
Data Analyzing And Visualization Using Python.pptx
Data Analyzing And Visualization Using Python.pptxData Analyzing And Visualization Using Python.pptx
Data Analyzing And Visualization Using Python.pptxPoojaChavan51
 
Introduction to numpy Session 1
Introduction to numpy Session 1Introduction to numpy Session 1
Introduction to numpy Session 1Jatin Miglani
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfUmarMustafa13
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfArumugam90
 
Arrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsArrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsPrabu U
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshopVinay Kumar
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using javaNarayan Sau
 

Similar to L 5 Numpy final ppt kirti.pptx (20)

NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
 
NUMPY [Autosaved] .pptx
NUMPY [Autosaved]                    .pptxNUMPY [Autosaved]                    .pptx
NUMPY [Autosaved] .pptx
 
Lenguaje python en I+D. Numpy, Sympy y Pandas
Lenguaje python en I+D. Numpy, Sympy y PandasLenguaje python en I+D. Numpy, Sympy y Pandas
Lenguaje python en I+D. Numpy, Sympy y Pandas
 
‏‏Lecture 2.pdf
‏‏Lecture 2.pdf‏‏Lecture 2.pdf
‏‏Lecture 2.pdf
 
NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
 
NUMPY-2.pptx
NUMPY-2.pptxNUMPY-2.pptx
NUMPY-2.pptx
 
Python advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmPython advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithm
 
Introduction to Matlab - Basic Functions
Introduction to Matlab - Basic FunctionsIntroduction to Matlab - Basic Functions
Introduction to Matlab - Basic Functions
 
DAA - chapter 1.pdf
DAA - chapter 1.pdfDAA - chapter 1.pdf
DAA - chapter 1.pdf
 
05-stack_queue.ppt
05-stack_queue.ppt05-stack_queue.ppt
05-stack_queue.ppt
 
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory AccessAccelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
Accelerating Key Bioinformatics Tasks 100-fold by Improving Memory Access
 
Data Analyzing And Visualization Using Python.pptx
Data Analyzing And Visualization Using Python.pptxData Analyzing And Visualization Using Python.pptx
Data Analyzing And Visualization Using Python.pptx
 
Introduction to numpy Session 1
Introduction to numpy Session 1Introduction to numpy Session 1
Introduction to numpy Session 1
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdf
 
Arrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsArrays with Numpy, Computer Graphics
Arrays with Numpy, Computer Graphics
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
recursion.ppt
recursion.pptrecursion.ppt
recursion.ppt
 
Mat lab workshop
Mat lab workshopMat lab workshop
Mat lab workshop
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using java
 

More from Kirti Verma

L-5 BCEProcess management.ppt
L-5 BCEProcess management.pptL-5 BCEProcess management.ppt
L-5 BCEProcess management.pptKirti Verma
 
L-3 BCE OS FINAL.ppt
L-3 BCE OS FINAL.pptL-3 BCE OS FINAL.ppt
L-3 BCE OS FINAL.pptKirti Verma
 
L-4 BCE Generations of Computers final.ppt
L-4 BCE Generations of Computers final.pptL-4 BCE Generations of Computers final.ppt
L-4 BCE Generations of Computers final.pptKirti Verma
 
L-1 BCE computer fundamentals final kirti.ppt
L-1 BCE computer fundamentals final kirti.pptL-1 BCE computer fundamentals final kirti.ppt
L-1 BCE computer fundamentals final kirti.pptKirti Verma
 
BCE L-4 Data Type In C++.ppt
BCE L-4 Data Type In C++.pptBCE L-4 Data Type In C++.ppt
BCE L-4 Data Type In C++.pptKirti Verma
 
BCE L-3 overview of C++.ppt
BCE L-3 overview of C++.pptBCE L-3 overview of C++.ppt
BCE L-3 overview of C++.pptKirti Verma
 
BCE L-2 Algorithms-and-Flowchart-ppt.ppt
BCE L-2 Algorithms-and-Flowchart-ppt.pptBCE L-2 Algorithms-and-Flowchart-ppt.ppt
BCE L-2 Algorithms-and-Flowchart-ppt.pptKirti Verma
 
BCE L-1 Programmimg languages.pptx
BCE L-1  Programmimg languages.pptxBCE L-1  Programmimg languages.pptx
BCE L-1 Programmimg languages.pptxKirti Verma
 
BCE L-1 networking fundamentals 111.pptx
BCE L-1  networking fundamentals 111.pptxBCE L-1  networking fundamentals 111.pptx
BCE L-1 networking fundamentals 111.pptxKirti Verma
 
BCE L-2 e commerce.pptx
BCE L-2 e commerce.pptxBCE L-2 e commerce.pptx
BCE L-2 e commerce.pptxKirti Verma
 
BCE L-3omputer security Basics.pptx
BCE L-3omputer security Basics.pptxBCE L-3omputer security Basics.pptx
BCE L-3omputer security Basics.pptxKirti Verma
 
L 2 Introduction to Data science final kirti.pptx
L 2 Introduction to Data science final kirti.pptxL 2 Introduction to Data science final kirti.pptx
L 2 Introduction to Data science final kirti.pptxKirti Verma
 
Pandas Dataframe reading data Kirti final.pptx
Pandas Dataframe reading data  Kirti final.pptxPandas Dataframe reading data  Kirti final.pptx
Pandas Dataframe reading data Kirti final.pptxKirti Verma
 
L 8 introduction to machine learning final kirti.pptx
L 8 introduction to machine learning final kirti.pptxL 8 introduction to machine learning final kirti.pptx
L 8 introduction to machine learning final kirti.pptxKirti Verma
 
L 6.1 complete scikit libraray.pptx
L 6.1 complete scikit libraray.pptxL 6.1 complete scikit libraray.pptx
L 6.1 complete scikit libraray.pptxKirti Verma
 
L 7Complete Machine learning.pptx
L 7Complete Machine learning.pptxL 7Complete Machine learning.pptx
L 7Complete Machine learning.pptxKirti Verma
 
Introduction to python history and platforms
Introduction to python history and platformsIntroduction to python history and platforms
Introduction to python history and platformsKirti Verma
 
Informed Search Techniques new kirti L 8.pptx
Informed Search Techniques new kirti L 8.pptxInformed Search Techniques new kirti L 8.pptx
Informed Search Techniques new kirti L 8.pptxKirti Verma
 
Production System l 10.pptx
Production System l 10.pptxProduction System l 10.pptx
Production System l 10.pptxKirti Verma
 
Breath first Search and Depth first search
Breath first Search and Depth first searchBreath first Search and Depth first search
Breath first Search and Depth first searchKirti Verma
 

More from Kirti Verma (20)

L-5 BCEProcess management.ppt
L-5 BCEProcess management.pptL-5 BCEProcess management.ppt
L-5 BCEProcess management.ppt
 
L-3 BCE OS FINAL.ppt
L-3 BCE OS FINAL.pptL-3 BCE OS FINAL.ppt
L-3 BCE OS FINAL.ppt
 
L-4 BCE Generations of Computers final.ppt
L-4 BCE Generations of Computers final.pptL-4 BCE Generations of Computers final.ppt
L-4 BCE Generations of Computers final.ppt
 
L-1 BCE computer fundamentals final kirti.ppt
L-1 BCE computer fundamentals final kirti.pptL-1 BCE computer fundamentals final kirti.ppt
L-1 BCE computer fundamentals final kirti.ppt
 
BCE L-4 Data Type In C++.ppt
BCE L-4 Data Type In C++.pptBCE L-4 Data Type In C++.ppt
BCE L-4 Data Type In C++.ppt
 
BCE L-3 overview of C++.ppt
BCE L-3 overview of C++.pptBCE L-3 overview of C++.ppt
BCE L-3 overview of C++.ppt
 
BCE L-2 Algorithms-and-Flowchart-ppt.ppt
BCE L-2 Algorithms-and-Flowchart-ppt.pptBCE L-2 Algorithms-and-Flowchart-ppt.ppt
BCE L-2 Algorithms-and-Flowchart-ppt.ppt
 
BCE L-1 Programmimg languages.pptx
BCE L-1  Programmimg languages.pptxBCE L-1  Programmimg languages.pptx
BCE L-1 Programmimg languages.pptx
 
BCE L-1 networking fundamentals 111.pptx
BCE L-1  networking fundamentals 111.pptxBCE L-1  networking fundamentals 111.pptx
BCE L-1 networking fundamentals 111.pptx
 
BCE L-2 e commerce.pptx
BCE L-2 e commerce.pptxBCE L-2 e commerce.pptx
BCE L-2 e commerce.pptx
 
BCE L-3omputer security Basics.pptx
BCE L-3omputer security Basics.pptxBCE L-3omputer security Basics.pptx
BCE L-3omputer security Basics.pptx
 
L 2 Introduction to Data science final kirti.pptx
L 2 Introduction to Data science final kirti.pptxL 2 Introduction to Data science final kirti.pptx
L 2 Introduction to Data science final kirti.pptx
 
Pandas Dataframe reading data Kirti final.pptx
Pandas Dataframe reading data  Kirti final.pptxPandas Dataframe reading data  Kirti final.pptx
Pandas Dataframe reading data Kirti final.pptx
 
L 8 introduction to machine learning final kirti.pptx
L 8 introduction to machine learning final kirti.pptxL 8 introduction to machine learning final kirti.pptx
L 8 introduction to machine learning final kirti.pptx
 
L 6.1 complete scikit libraray.pptx
L 6.1 complete scikit libraray.pptxL 6.1 complete scikit libraray.pptx
L 6.1 complete scikit libraray.pptx
 
L 7Complete Machine learning.pptx
L 7Complete Machine learning.pptxL 7Complete Machine learning.pptx
L 7Complete Machine learning.pptx
 
Introduction to python history and platforms
Introduction to python history and platformsIntroduction to python history and platforms
Introduction to python history and platforms
 
Informed Search Techniques new kirti L 8.pptx
Informed Search Techniques new kirti L 8.pptxInformed Search Techniques new kirti L 8.pptx
Informed Search Techniques new kirti L 8.pptx
 
Production System l 10.pptx
Production System l 10.pptxProduction System l 10.pptx
Production System l 10.pptx
 
Breath first Search and Depth first search
Breath first Search and Depth first searchBreath first Search and Depth first search
Breath first Search and Depth first search
 

Recently uploaded

Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 

Recently uploaded (20)

Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 

L 5 Numpy final ppt kirti.pptx

  • 1. NUMPY Numerical Computing in Python By Kirti Verma AP, CSE LNCTE 1
  • 2. What is Numpy? • Numpy, Scipy, and Matplotlib provide MATLAB-like functionality in python. • Numpy Features: • Typed multidimentional arrays (matrices) • Fast numerical computations (matrix math) • High-level math functions 2
  • 3. Why do we need NumPy • Python does numerical computations slowly. • 1000 x 1000 matrix multiply • Python triple loop takes > 10 min. • Numpy takes ~0.03 seconds import numpy as np print(np.__version__) arr=np.array([1,2,3,4,5]) #list as array print(arr) print(type(arr)) arr=np.array([1,2,3,4,5]) arr=np.array((1,2,3,4,5)) # tuple as array 3
  • 4. NumPy Overview 1. Arrays 2. Shaping and transposition 3. Mathematical Operations 4. Indexing and slicing 5. Broadcasting 4
  • 5. Arrays Structured lists of numbers. • Vectors : 1D array • Matrices: nD matrices • Images: 3D arrays • Tensors: Generalised multi dimensional arrays 5
  • 6. Arrays Structured lists of numbers. • Vectors • Matrices • Images • Tensors • ConvNets 𝑝𝑥 𝑝𝑦 𝑝𝑧 𝑎11 ⋯ 𝑎1𝑛 ⋮ ⋱ ⋮ 𝑎𝑚1 ⋯ 𝑎𝑚𝑛 6
  • 7. Arrays Structured lists of numbers. • Vectors • Matrices • Images • Tensors • ConvNets 7
  • 8. Arrays Structured lists of numbers. • Vectors • Matrices • Images • Tensors • ConvNets 8
  • 9. Arrays, Basic Properties import numpy as np a = np.array([[1,2,3],[4,5,6]],dtype=np.float32) print a.ndim, a.shape, a.dtype 1. Arrays can have any number of dimensions, including zero (a scalar). 2. Arrays are typed: np.uint8, np.int64, np.float32, np.float64 3. Arrays are dense. Each element of the array exists and has the same type. 9
  • 10. Arrays, creation • np.ones, np.zeros • np.arange • np.concatenate • np.astype • np.zeros_like, np.ones_like • np.random.random 10
  • 11. Arrays, creation • np.ones, np.zeros • np.arange • np.concatenate • np.astype • np.zeros_like, np.ones_like • np.random.random 11
  • 12. Arrays, creation • np.ones, np.zeros • np.arange • np.concatenate • np.astype • np.zeros_like, np.ones_like • np.random.random 12
  • 13. Arrays, creation • np.ones, np.zeros • np.arange • np.concatenate • np.astype • np.zeros_like, np.ones_like • np.random.random 13
  • 14. Arrays, creation • np.ones, np.zeros • np.arange • np.concatenate • np.astype • np.zeros_like, np.ones_like • np.random.random 14
  • 15. Arrays, creation • np.ones, np.zeros • np.arange • np.concatenate • np.astype • np.zeros_like, np.ones_like • np.random.random 15
  • 16. Arrays, creation • np.ones, np.zeros • np.arange • np.concatenate • np.astype • np.zeros_like, np.ones_like • np.random.random 16
  • 17. Arrays, danger zone • Must be dense, no holes. • Must be one type • Cannot combine arrays of different shape 17
  • 18. Shaping a = np.array([1,2,3,4,5,6]) a = a.reshape(3,2) a = a.reshape(2,-1) a = a.ravel() 1. Total number of elements cannot change. 2. Use -1 to infer (when axis shape is not known to as, first option is mandatory and rest axis are adjusted ) axis shape 3. Row-major by default (MATLAB is column-major) 18
  • 19. Return values • Numpy functions return either views or copies. • Views share data with the original array, like references in Java/C++. Altering entries of a view, changes the same entries in the original. • The numpy documentation says which functions return views or copies • np.copy, np.view make explicit copies and views. 19
  • 20. Transposition a = np.arange(10).reshape(5,2) a = a.T a = a.transpose((1,0)) np.transpose permutes axes. a.T transposes the first two axes. 20
  • 21. Saving and loading arrays np.savez(‘data.npz’, a=a) data = np.load(‘data.npz’) a = data[‘a’] 1. NPZ files can hold multiple arrays 2. np.savez_compressed similar. 21
  • 22. Image arrays Images are 3D arrays: width, height, and channels Common image formats: height x width x RGB (band-interleaved) height x width (band-sequential) Gotchas(commonly done errors in proramming): Channels may also be BGR (OpenCV does this) May be [width x height], not [height x width] 22
  • 23. Saving and Loading Images SciPy: skimage.io.imread,skimage.io.imsave height x width x RGB PIL / Pillow: PIL.Image.open, Image.save width x height x RGB OpenCV: cv2.imread, cv2.imwrite height x width x BGR 23
  • 24. Mathematical operators • Arithmetic operations are element-wise • Logical operator return a bool array • In place operations modify the array 24
  • 25. Mathematical operators • Arithmetic operations are element-wise • Logical operator return a bool array • In place operations modify the array 25
  • 26. Mathematical operators • Arithmetic operations are element-wise • Logical operator return a bool array • In place operations modify the array 26
  • 27. Mathematical operators • Arithmetic operations are element-wise • Logical operator return a bool array • In place operations modify the array 27
  • 28. Math, upcasting Just as in Python and Java, the result of a math operator is cast to the more general or precise datatype. uint64 + uint16 => uint64 float32 / int32 => float32 Warning: upcasting does not prevent overflow/underflow. You must manually cast first. Use case: images often stored as uint8. You should convert to float32 or float64 before doing math. 28
  • 29. Math, universal functions Also called ufuncs Element-wise Examples: • np.exp • np.sqrt • np.sin • np.cos • np.isnan 29
  • 30. Math, universal functions Also called ufuncs Element-wise Examples: • np.exp • np.sqrt • np.sin • np.cos • np.isnan 30
  • 31. Indexing x[0,0] # top-left element x[0,-1] # first row, last column x[0,:] # first row (many entries) x[:,0] # first column (many entries) Notes: • Zero-indexing • Multi-dimensional indices are comma-separated (i.e., a tuple) 31
  • 32. Indexing, slices and arrays I[1:-1,1:-1] # select all but one-pixel border I = I[:,:,::-1] # swap channel order I[I<10] = 0 # set dark pixels to black I[[1,3], :] # select 2nd and 4th row 1. Slices are views. Writing to a slice overwrites the original array. 2. Can also index by a list or boolean array. 32
  • 33. Python Slicing Syntax: start:stop:step a = list(range(10)) a[:3] # indices 0, 1, 2 a[-3:] # indices 7, 8, 9 a[3:8:2] # indices 3, 5, 7 a[4:1:-1] # indices 4, 3, 2 (this one is tricky) 33
  • 34. Axes a.sum() # sum all entries a.sum(axis=0) # sum over rows a.sum(axis=1) # sum over columns a.sum(axis=1, keepdims=True) 1. Use the axis parameter to control which axis NumPy operates on 2. Typically, the axis specified will disappear, keepdims keeps all dimensions 34
  • 35. 35