0% found this document useful (0 votes)
0 views31 pages

Numpy

NumPy is a powerful library for numerical computations in Python, offering fast performance for operations like matrix multiplication compared to standard Python. It supports various data types and provides functionalities for creating and manipulating arrays, including indexing, slicing, and mathematical operations. NumPy's efficiency stems from its ability to handle large datasets and perform operations in a more optimized manner than traditional Python lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views31 pages

Numpy

NumPy is a powerful library for numerical computations in Python, offering fast performance for operations like matrix multiplication compared to standard Python. It supports various data types and provides functionalities for creating and manipulating arrays, including indexing, slicing, and mathematical operations. NumPy's efficiency stems from its ability to handle large datasets and perform operations in a more optimized manner than traditional Python lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

NUMPY Numerical Packages

WHAT IS NUMPY (NUMERICAL PYTHON)


• A powerful N-dimensional array object.

•Fast numerical computations


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
3
WHY IS NUMPY FASTER?
NUMPY DATATYPES
NumPy supports a wider variety of data types than are built-in to the Python
language by default. They are defined by the numpy.dtype class and include:
• intc (same as a C integer) and intp (used for indexing)
• int8, int16, int32, int64
• uint8, uint16, uint32, uint64
• float16, float32, float64
• complex64, complex128
• bool_, int_, float_, complex_ are shorthand for defaults.
These can be used as functions to cast literals or sequence types, as well as
arguments to numpy functions that accept the dtype keyword argument.
NUMPY OVERVIEW
1. Arrays
2. Shaping and transposition
3. Mathematical Operations
4. Indexing and slicing

6
ARRAYS
Structured lists of numbers.
𝑝𝑥
Vectors
𝑝𝑦
Matrices
𝑝𝑧
Images
Tensors 𝑎11 ⋯ 𝑎1𝑛
ConvNets ⋮ ⋱ ⋮
𝑎𝑚1 ⋯ 𝑎𝑚𝑛

7
ARRAYS
Structured lists of numbers.
Vectors
Matrices
Images
Tensors
ConvNets

8
ARRAYS
Structured lists of numbers.
Vectors
Matrices
Images
Tensors
ConvNets

9
NUMPY ARRAYS
There are a couple of mechanisms for creating arrays in NumPy:
• Conversion from other Python structures (e.g., lists, tuples).
• Built-in NumPy array creation (e.g., arange, ones, zeros, etc.).
• Reading arrays from disk, either from standard or custom formats (e.g. reading in
from a CSV file).
• and others …
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.diag
np.arange
np.concatenate
np.astype
np.zeros_like, np.ones_like
np.random.random

13
ARRAYS, CREATION
np.ones, np.zeros, np.diag
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.diag
np.arange
np.concatenate
np.astype
np.zeros_like, np.ones_like
np.random.random

16
ARRAYS, CREATION
np.ones, np.zeros
np.arange
np.concatenate
np.astype
np.zeros_like, np.ones_like
np.random.random

17
ARRAYS, CREATION
np.ones, np.zeros
np.arange
np.concatenate
np.astype
np.zeros_like, np.ones_like
np.random.random

18
ARRAYS, DANGER ZONE
Must be dense, no holes.
Must be one type
Cannot combine arrays of different shape

19
INDEXING
Single-dimension indexing is accomplished as usual.
>>> x = np.arange(10)
>>> x[2]
2 0 1 2 3 4 5 6 7 8 9
>>> x[-2]
8
Multi-dimensional arrays support multi-dimensional indexing.
>>> x.shape = (2,5) # now x is 2-dimensional
>>> x[1,3]
0 1 2 3 4
8
5 6 7 8 9
>>> x[1,-1]
9
INDEXING
Using fewer dimensions to index will result in a subarray.

>>> x[0]
array([0, 1, 2, 3, 4])

This means that x[i, j] == x[i][j] but the second method is less efficient.
INDEXING
x[0,0] # top-left element 1 2 3
4 5 6
7 8 9

x[0,-1] # first row, last column 1 2 3


4 5 6
7 8 9
x[0,:] # first row (many entries) 1 2 3
4 5 6
7 8 9

x[:,0] # first column (many entries) 1 2 3


4 5 6
7 8 9

Notes:
Zero-indexing
Multi-dimensional indices are comma-separated 22
SLICING
>>> x = np.arange(10)

#from start to 4th position #return elements at even place


>>> x[:5] >>> x[: : 2]
array([0, 1, 2, 3, 4]) array([0, 2, 4, 6, 8])

#from 4th position to end


>>> x[4:] #reverse the array
array([4, 5, 6, 7, 8, 9]) >>> x[::-1]
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
#from 4th to 6th position
>>> x[4:7]
array([4, 5, 6])
AXES
a.sum() # sum all entries
a.sum(axis=0) # jumlah tiap kolom
a.sum(axis=1) # jumlah tiap baris
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

24
AXES
a.mean() # meam all entries
a.mean(axis=0) # rata rata tiap kolom
a.mean(axis=1) # rata rata tiap baris

25
BOOLEAN SLICING
arr = np.arange(10) # membuat array berisi angka 0-10
arr.mean() # rata-rata semua elemen
arr> arr.mean() # boolean array
arr[arr> arr.mean()] # ambil baris yang bernilai true (nilai elemen > rata rata)
There are also some built-in
methods of ndarray objects.

Universal functions which


may also be applied
include exp, sqrt, add, sin,
cos, etc…

ARRAY >>> a = np.random.random((2,3))


>>> a
OPERATIONS array([[ 0.68166391, 0.98943098, 0.69361582],
[ 0.78888081, 0.62197125, 0.40517936]])
>>> a.sum()
4.1807421388722164
>>> a.min()
0.4051793610379143
>>> a.max(axis=0)
array([ 0.78888081, 0.98943098, 0.69361582])
>>> a.min(axis=1)
array([ 0.68166391, 0.40517936])
ARRAY OPERATIONS
>>> a = np.arange(5) Basic operations apply element-wise. The
>>> b = np.arange(5) result is a new array with the resultant
>>> a+b elements.
array([0, 2, 4, 6, 8])
>>> a-b Operations like *= and += will modify the
array([0, 0, 0, 0, 0]) existing array.
>>> a**2
array([ 0, 1, 4, 9, 16])
>>> a>3
array([False, False, False, False, True], dtype=bool)
>>> 10*np.sin(a)
array([ 0., 8.41470985, 9.09297427, 1.41120008, -7.56802495])
>>> a*b
array([ 0, 1, 4, 9, 16])
A = np.identity(3)
>>> a = np.ones(4).reshape(2,2)
>>> a
array([[ 1., 1.],
[ 1., 1.]])
ARRAY OPERATIONS >>> a[1,0] = 1

>>> I = np.identity(2)
>>> I
array([[ 1., 0.],
Since multiplication is done [ 0., 1.]])
element-wise, you need to >>> I[1,0] = 0
specifically perform a dot product
to perform matrix multiplication. >>> b = np.arange(4).reshape(2,2)
>>> b
array([[0, 1],
[2, 3]])
>>> a*b
array([[ 0., 1.],
[ 2., 3.]])
>>> np.dot(a,b)
array([[ 2., 4.],
[ 2., 4.]])
•For array, '*' means element-wise multiplication,
and the dot() function is used for matrix multiplication.
ARRAY OPERATIONS
>>> a = np.floor(10*np.random.random((3,4)))
>>> print a
[[ 9. 8. 7. 9.]
An array shape can be [ 7. 5. 9. 7.]
manipulated by a number of [ 8. 2. 7. 5.]]
methods. >>> a.shape
(3, 4)
>>> a.ravel()
resize(size) will modify an array([ 9., 8., 7., 9., 7., 5., 9., 7., 8., 2., 7., 5.])
array in place. >>> a.shape = (6,2)
>>> print a
[[ 9. 8.]
reshape(size) will return a
[ 7. 9.]
copy of the array with a new [ 7. 5.]
shape. [ 9. 7.]
[ 8. 2.]
[ 7. 5.]]
>>> a.transpose()
array([[ 9., 7., 7., 9., 8., 7.],
[ 8., 9., 5., 7., 2., 5.]])
Test Yourself
Seorang guru menyimpan nilai ujian 12 siswa yang terbagi dalam 4 kelompok. Setiap kelompok
terdiri dari 3 siswa
Kelompok 1: 65, 70, 75
Kelompok 2: 60, 55, 58
Kelompok 3: 80, 85, 82
Kelompok 4: 70, 68, 72

Tuliskan nilai tersebut menjadi array berukuran 4 x 3


Lakukan slicing untuk membuat array baru yang memuat kelompok yang memiliki rata rata lebih
besar dari rata rata keseluruhan siswa

You might also like