NumPy: from basic to advance
NumPy: from basic to advance
What isFrom
numpy? Basics to Advanced
NumPy is a Python library that provides powerful and
versatile array computations, mathematical functions,
NumPy is a Python library that provides powerful and versatile array computations,
and other toolsfunctions,
mathematical for various scientific
and other tools domains.
for various scientific domains. It isIt isused
widely
widely used in data
in data science, machine science, machine
learning, and scientific computing.learning, and
NumPy offers comprehensive
mathematical functions, random number generators, linear algebra routines, Fourier
scientific computing. NumPy offers
transforms, and more.
comprehensive mathematical functions, random number
generators, linear algebra routines, Fourier transforms,
and more.
Numpy Vs Pandas
NumPy Pandas
Provides powerful and versatile array Built on top of NumPy and provides high-performance, fast, easy-to-use
computations, mathematical functions, and data structures, and data analysis tools for manipulating numeric data and
other tools for various scientific domains time series.
Offers comprehensive mathematical Offers powerful data analysis tools like DataFrame and Series, which
functions, random number generators, linear provide rich time series functionality, data alignment, NA-friendly
algebra routines, Fourier transforms, and statistics, groupby, merge and join methods, and lots of other
more. conveniences
Provides high-performance multidimensional Consumes more memory than NumPy but is more memory-efficient than
arrays and tools to deal with them other Python data analysis libraries.
Is used to perform scientific computing Is used for data manipulation and analysis
[1 2 3 4 5]
# type of array
print(type(a))
<class 'numpy.ndarray'>
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
#create 2D array
#create 2D array
b = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(b)
[[ 1 2 3 4 5]
[ 6 7 8 9 10]]
# create 3D array
c = np.array([[[1, 2, 3], [4,5,6]], [[7,8,9], [10,11,12]]])
print(c)
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
#here 1,15 is the range means give me 3 numbers having values between 1-15
np.random.randint(1,15,3)
array([11, 4, 7])
array([[7, 1, 8],
[8, 4, 2],
[5, 9, 7]])
# bool datatype
np.array([1, 2, 3, 4, 5], dtype=bool)
array([ 0, 3, 6, 9, 12])
[[[ 0 1]
[ 2 3]]
[[ 4 5]
[ 6 7]]
[[ 8 9]
[10 11]]]
array([[1, 5],
[2, 6],
[3, 7],
[4, 8]])
trans.reshape(4,2)
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
array([[1, 2, 3, 4, 5, 6],
[7, 8, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
#Returns number of elements in arr
arr=np.array([1,2,3,4,6,7,9])
arr.size
array([1, 2, 3, 4, 6, 7, 9, 0, 1, 2, 4, 5])
array([1, 2, 4, 3, 4, 6, 7, 9, 0, 1, 2, 4, 5])
array([1, 2, 3, 4, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
array([[1, 2, 3, 4, 5],
[7, 8, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
abs(-1)
add.accumulate(array([1.,2.,3.,4.]))
multiply.accumulate(array([1.,2.,3.,4.]))
add.accumulate(array([[1,2,3],[4,5,6]]), axis = 0)
array([[1, 2, 3],
[5, 7, 9]])
add.accumulate(array([[1,2,3],[4,5,6]]), axis = 1)
array([[ 1, 3, 6],
[ 4, 9, 15]])
array([-0.2, 4.2])
array([-0.2, 4.2])
False
allclose(array([1e10,1e-7]), array([1.00001e10,1e-8]))
False
# in radians
angle(1+1j)
0.7853981633974483
# in degrees
angle(1+1j,deg=True)
45.0
True
a.tolist()
Parameters
----------
none
Returns
-------
y : object, or list of object, or list of list of object, or ...
The possibly nested list of array elements.
Notes
-----
The array may be recreated via ``a = np.array(a.tolist())``, although this
may sometimes lose precision.
Examples
--------
For a 1D array, ``a.tolist()`` is almost the same as ``list(a)``,
except that ``tolist`` changes numpy scalars to Python scalars:
>>> a = np.array(1)
>>> list(a)
Traceback (most recent call last):
...
TypeError: iteration over a 0-d array
>>> a.tolist()
1
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
# sum over all axes except axis=1, result has same shape as original
apply_over_axes(sum, a, [0,2])
array([[[ 60],
[ 92],
[124]]])
array([0, 1, 2, 3, 4])
arange(5.0)
array([1.57079633, 0. ])
arccosh(array([e, 10.0]))
array([1.65745445, 2.99322285])
arcsin(array([0, 1]))
array([0. , 1.57079633])
arcsinh(array([e, 10.0]))
array([1.72538256, 2.99822295])
arctan(array([0, 1]))
array([0. , 0.78539816])
array([0. , 1.57079633])
arctanh(array([0, -0.5]))
array([ 0. , -0.54930614])
30
a = array([[10,50,30],[60,20,40]])
maxindex = a.argmax()
maxindex
a.ravel()[maxindex]
60
array([2, 0, 8, 4, 1])
array([0, 1, 2, 4, 8])
array([[1, 1, 0],
[0, 0, 1]], dtype=int64)
abs(array([-1.2, 1.2]))
array([1.2, 1.2])
abs(1.2+1j)
1.5620499351813308
(7,)
[1, 2, 3, 4, 6, 7, 9]
#Copies arr to new memory
np.copy(arr)
array([1, 2, 3, 4, 6, 7, 9])
#Sorts arr
arr.sort()
arr
array([1, 2, 3, 4, 6, 7, 9])
array([1, 2, 3, 4, 6, 7, 9])
array([1, 2, 3, 4, 6, 7, 9, 0, 1, 2, 4, 5])
array([1, 2, 3, 4, 6, 7, 9, 1, 2, 3, 4, 6, 7, 9, 0, 1, 2, 4, 5])
array([[1, 2, 3, 4, 1, 2, 3, 4],
[5, 6, 7, 8, 5, 6, 7, 8]])
Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/fontdata.js
What is Numpy?
NumPy is the fundamental package for scientific computing in Python.
It is a Python library that provides a multidimensional array object, various derived objects
(such as masked arrays and matrices), and an assortment of routines for fast operations on
arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete
Fourier transforms, basic linear algebra, basic statistical operations, random simulation and
much more.
At the core of the NumPy package, is the ndarray object. This encapsulates n-dimensional
arrays of homogeneous data types
[ 2 4 56 422 32 1]
In [4]: type(a)
Out[4]: numpy.ndarray
[[45 34 22 2]
[24 55 3 22]]
dtype
The desired data-type for the array. If not given, then the type willbe determined as the
minimum type required to hold the objects in thesequence.
In [8]: np.array([11,23,44] , dtype =bool) # Here True becoz , python treats Non -zero
The elements in a NumPy array are all required to be of the same data type, and thus will be
the same size in memory.
NumPy arrays facilitate advanced mathematical and other types of operations on large
numbers of data. Typically, such operations are executed more efficiently and with less code
than is possible using Python’s built-in sequences.
A growing plethora of scientific and mathematical Python-based packages are using NumPy
arrays; though these typically support Python-sequence input, they convert such input to
NumPy arrays prior to processing, and they often output NumPy arrays.
arange
Out[10]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24])
reshape
Both of number products should be equal to umber of Items present inside the array.
you can initialize the values and create values . ex: in deep learning weight shape
In [16]: np.zeros((3,4))
linspace
It is also called as Linearly space , Linearly separable,in a given range at equal distance it
creates points.
In [19]: np.linspace(-2,12,6)
identity
indentity matrix is that diagonal items will be ones and evrything will be zeros
In [21]: np.identity(6)
Array Attributes
In [22]: a1 = np.arange(10) # 1D
a1
[[4, 5],
[6, 7]]])
ndim
To findout given arrays number of dimensions
In [25]: a1.ndim
Out[25]: 1
In [26]: a2.ndim
Out[26]: 2
In [27]: a3.ndim
Out[27]: 3
shape
gives each item consist of no.of rows and np.of column
Out[28]: (10,)
Out[29]: (3, 4)
In [30]: a3.shape # first ,2 says it consists of 2D arrays .2,2 gives no.of rows and c
Out[30]: (2, 2, 2)
size
gives number of items
In [31]: a3
[[4, 5],
[6, 7]]])
Out[32]: 8
In [33]: a2
In [34]: a2.size
Out[34]: 12
item size
Memory occupied by the item
In [35]: a1
Out[36]: 4
Out[37]: 8
Out[38]: 4
dtype
gives data type of the item
In [39]: print(a1.dtype)
print(a2.dtype)
print(a3.dtype)
int32
float64
int32
In [41]: x.astype(int)
Array operations
In [42]: z1 = np.arange(12).reshape(3,4)
z2 = np.arange(12,24).reshape(3,4)
In [43]: z1
In [44]: z2
scalar operations
Scalar operations on Numpy arrays include performing addition or subtraction, or multiplication
on each element of a Numpy array.
In [45]: # arithmetic
z1 + 2
In [46]: # Subtraction
z1 - 2
In [47]: # Multiplication
z1 * 2
In [48]: # power
z1 ** 2
In [49]: ## Modulo
z1 % 2
relational Operators
The relational operators are also known as comparison operators, their main function is to
return either a true or false based on the value of operands.
In [50]: z2
In [52]: z2 > 20
Vector Operation
We can apply on both numpy array
In [53]: z1
In [54]: z2
In [55]: # Arthemetic
z1 + z2 # both numpy array Shape is same , we can add item wise
In [56]: z1 * z2
In [57]: z1 - z2
In [58]: z1 / z2
Array Functions
In [59]: k1 = np.random.random((3,3))
k1 = np.round(k1*100)
k1
In [60]: # Max
np.max(k1)
Out[60]: 98.0
In [61]: # min
np.min(k1)
Out[61]: 24.0
In [62]: # sum
np.sum(k1)
Out[62]: 462.0
Out[63]: 1297293445324800.0
In Numpy
localhost:8888/notebooks/ NumPy Fundamentals ( Prudhvi Vardhan Notes).ipynb 10/29
5/26/23, 4:29 PM NumPy Fundamentals ( Prudhvi Vardhan Notes) - Jupyter Notebook
0 = column , 1 = row
In [67]: # mean
k1
In [68]: np.mean(k1)
Out[68]: 51.333333333333336
In [70]: # median
np.median(k1)
Out[70]: 49.0
Out[72]: 19.89416441516903
In [74]: # variance
np.var(k1)
Out[74]: 395.77777777777777
Trignometry Functions
In [76]: np.cos(k1)
In [77]: np.tan(k1)
dot product
The numpy module of Python provides a function to perform the dot product of two arrays.
In [78]: s2 = np.arange(12).reshape(3,4)
s3 = np.arange(12,24).reshape(4,3)
In [79]: s2
In [80]: s3
In [82]: np.exp(s2)
1. round
The numpy.round() function rounds the elements of an array to the nearest integer or to the
specified number of decimals.
[1. 3. 4. 5.]
In [84]: #randomly
np.round(np.random.random((2,3))*100)
2. floor
localhost:8888/notebooks/ NumPy Fundamentals ( Prudhvi Vardhan Notes).ipynb 13/29
5/26/23, 4:29 PM NumPy Fundamentals ( Prudhvi Vardhan Notes) - Jupyter Notebook
The numpy.floor() function returns the largest integer less than or equal to each element of an
array.
[1. 2. 3. 4.]
3. Ceil
The numpy.ceil() function returns the smallest integer greater than or equal to each element of
an array.
[2. 3. 4. 5.]
In [91]: p1 = np.arange(10)
p2 = np.arange(12).reshape(3,4)
p3 = np.arange(8).reshape(2,2,2)
In [92]: p1
In [93]: p2
In [94]: p3
[[4, 5],
[6, 7]]])
Indexing on 1D array
In [95]: p1
Out[96]: 9
Out[97]: 0
indexing on 2D array
In [98]: p2
Out[100]: 6
Out[101]: 11
Out[102]: 4
indexing on 3D ( Tensors)
In [103]: p3
[[4, 5],
[6, 7]]])
Out[106]: 5
EXPLANATION :Here 3D is consists of 2 ,2D array , so Firstly we take 1 because our desired is
5 is in second matrix which is 1 .and 1 row so 0 and second column so 1
Out[109]: 2
EXPLANATION :Here firstly we take 0 because our desired is 2, is in first matrix which is 0 .
and 2 row so 1 and first column so 0
Out[110]: 0
Here first we take 0 because our desired is 0, is in first matrix which is 0 . and 1 row so 0 and
first column so 0
Out[113]: 6
EXPLANATION : Here first we take because our desired is 6, is in second matrix which is 1 .
and second row so 1 and first column so 0
Slicing
Slicing on 1D
In [114]: p1
EXPLANATION :Here First we take , whatever we need first item ,2 and up last(4) + 1 which 5
.because last element is not included
Slicing on 2D
In [121]: p2
EXPLANATION :Here 0 represents first row and (:) represnts Total column
p2[:,2]
EXPLANATION :Here we want all rows so (:) , and we want 3rd column so 2
EXPLANATION :Here first [1:3] we slice 2 second row is to third row is not existed which is 2
and Secondly , we take [1:3] which is same as first:we slice 2 second row is to third row is not
included which is 3
EXPLANATION : Here we take (:) because we want all rows , second(:2) for alternate value,
and (:) for all columns and (:3) jump for two steps
EXPLANATION : Here we take (:) because we want all rows , second(:2) for alternate value,
and (1) for we want from second column and (:2) jump for two steps and ignore middle one
EXPLANATION : Here we take (1) because we want second row , second(:) for total column,
(:3) jump for two steps and ignore middle ones
In [159]:
p2[0:2] # first fetched rows
EXPLANATION : 0:2 selects the rows from index 0 (inclusive) to index 2 (exclusive), which
means it will select the first and second rows of the array. , is used to separate row and column
selections. 1::2 selects the columns starting from index 1 and selects every second column. So
it will select the second and fourth columns of the array.
Slicing in 3D
In [172]: p3 = np.arange(27).reshape(3,3,3)
p3
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
EXPLANATION : Along the first axis, (::2) selects every second element. This means it will
select the subarrays at indices 0 and 2
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
In [186]: p3[0,1,:]
EXPLANATION : 0 represnts first matrix , 1 represents second row , (:) means total
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
In [191]: p3[1,:,1]
EXPLANATION : 1 respresnts middle column , (:) all columns , 1 represnts middle column
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
EXPLANATION : Here we go through 3 stages , where 2 for last array , and (1:) from second
row to total rows , and (1:) is for second column to total columns
In [197]: # Fetch o, 2, 18 , 20
p3
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
EXPLANATION : Here we take (0::2) first adn last column , so we did jump using this, and we
took (0) for first row , and we (::2) ignored middle column
Iterating
In [208]: p1
0
1
2
3
4
5
6
7
8
9
In [209]: p2
[0 1 2 3]
[4 5 6 7]
[ 8 9 10 11]
In [210]: p3
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[0 1 2]
[3 4 5]
[6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]
print all items in 3D using nditer ----> first convert in to 1D and applying Loop
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Reshaping
In [217]: p2
In [219]: np.transpose(p2)
In [221]: p3
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
In [223]: p3.T
[[ 1, 10, 19],
[ 4, 13, 22],
[ 7, 16, 25]],
[[ 2, 11, 20],
[ 5, 14, 23],
[ 8, 17, 26]]])
Ravel
In [225]: p2
In [224]: p2.ravel()
In [226]: p3
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
In [227]: p3.ravel()
Stacking
Stacking is the concept of joining arrays in NumPy. Arrays having the same dimensions can be
stacked
In [231]: w1
In [232]: w2
In [236]: np.hstack((w1,w2))
In [238]: w2
In [239]: np.vstack((w1,w2))
Splitting
Out[242]: [array([[0],
[4],
[8]]),
array([[1],
[5],
[9]]),
array([[ 2],
[ 6],
[10]]),
array([[ 3],
[ 7],
[11]])]
In [ ]:
The elements in a NumPy array are all required to be of the same data type, and thus will be
the same size in memory.
NumPy arrays facilitate advanced mathematical and other types of operations on large
numbers of data. Typically, such operations are executed more efficiently and with less code
than is possible using Python’s built-in sequences.
A growing plethora of scientific and mathematical Python-based packages are using NumPy
arrays; though these typically support Python-sequence input, they convert such input to
NumPy arrays prior to processing, and they often output NumPy arrays.
List
2.0619215965270996
Numpy
0.1120920181274414
Out[3]: 120.35911871666826
so ,Numpy is Faster than Normal Python programming ,we can see in above Example.
because Numpy uses C type array
List
Out[4]: 89095160
Numpy
In [5]: R = np.arange(10000000)
sys.getsizeof(R)
Out[5]: 40000104
Out[6]: 20000104
Out[8]: 5
Fancy Indexing
Fancy indexing allows you to select or modify specific elements based on complex conditions
or combinations of indices. It provides a powerful way to manipulate array data in NumPy.
In [11]: w
Boolean indexing
It allows you to select elements from an array based on a Boolean condition. This allows you
to extract only the elements of an array that meet a certain condition, making it easy to perform
operations on specific subsets of data.
In [16]: G = np.random.randint(1,100,24).reshape(6,4)
In [17]: G
In [19]: # Where is True , it gives result , everything other that removed.we got value
G[G > 50]
Out[19]: array([64, 51, 75, 86, 53, 60, 95, 75, 79, 98, 87, 58, 56, 93])
Out[21]: array([64, 50, 8, 86, 6, 60, 50, 98, 34, 58, 56, 26])
Here we used (&) bitwise Not logical(and) , because we are working with boolean values
In [23]: # Result
G [(G > 50 ) & (G % 2 == 0)]
In [25]: # Result
G[~(G % 7 == 0)] # (~) = Not
Out[25]: array([64, 51, 75, 50, 8, 86, 6, 53, 60, 50, 95, 75, 79, 34, 45, 87, 58,
26, 93, 17])
Broadcasting
Used in Vectorization
The term broadcasting describes how NumPy treats arrays with different shapes during
arithmetic operations.
The smaller array is “broadcast” across the larger array so that they have compatible shapes.
[[0 1 2]
[3 4 5]]
[[ 6 7 8]
[ 9 10 11]]
[[ 6 8 10]
[12 14 16]]
[[0 1 2]
[3 4 5]]
[[0 1 2]]
[[0 2 4]
[3 5 7]]
Broadcasting Rules
1. Make the two arrays have the same number of dimensions.
If the numbers of dimensions of the two arrays are different, add new dimensions with size
1 to the head of the array with the smaller dimension.
If the sizes of each dimension of the two arrays do not match, dimensions with size 1 are
stretched to the size of the other array.
If there is a dimension whose size is not 1 in either of the two arrays, it cannot be
broadcasted, and an error is raised.
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
In [29]: print(b) # 1 D
[0 1 2]
[[ 0 2 4]
[ 3 5 7]
[ 6 8 10]
[ 9 11 13]]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[0 1 2]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9360/470058718.py in <module>
7 print(b)
8
----> 9 print(a+b)
ValueError: operands could not be broadcast together with shapes (3,4) (3,)
EXPLANATION : Arthematic Operation not possible because , Here a = (3,4) is 2D and b =(3)
is 1D so did converted (3) to (1,3) and streched to (3,3) but , a is not equals to b . so it got failed
In [32]: a = np.arange(3).reshape(1,3)
b = np.arange(3).reshape(3,1)
print(a)
print(b)
print(a+b)
[[0 1 2]]
[[0]
[1]
[2]]
[[0 1 2]
[1 2 3]
[2 3 4]]
In [33]: a = np.arange(3).reshape(1,3)
b = np.arange(4).reshape(4,1)
print(a)
print(b)
print(a + b)
[[0 1 2]]
[[0]
[1]
[2]
[3]]
[[0 1 2]
[1 2 3]
[2 3 4]
[3 4 5]]
In [34]: a = np.array([1])
# shape -> (1,1) streched to 2,2
b = np.arange(4).reshape(2,2)
# shape -> (2,2)
print(a)
print(b)
print(a+b)
[1]
[[0 1]
[2 3]]
[[1 2]
[3 4]]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9360/1200695402.py in <module>
7 print(b)
8
----> 9 print(a+b)
ValueError: operands could not be broadcast together with shapes (3,4) (4,3)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[0 1]
[2 3]]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9360/2417388683.py in <module>
6 print(b)
7
----> 8 print(a+b)
ValueError: operands could not be broadcast together with shapes (4,4) (2,2)
In [37]: k = np.arange(10)
In [38]: k
In [39]: np.sum(k)
Out[39]: 45
In [40]: np.sin(k)
sigmoid
In [45]: k = np.arange(100)
sigmoid(k)
In [47]: actual
Out[47]: array([17, 4, 4, 24, 18, 44, 22, 25, 17, 39, 3, 34, 37, 12, 47, 22, 37,
9, 47, 38, 27, 46, 47, 34, 8])
In [48]: predicted
Out[48]: array([47, 31, 30, 17, 7, 22, 1, 16, 1, 24, 16, 7, 6, 37, 18, 15, 2,
33, 25, 33, 9, 17, 36, 7, 16])
mse(actual,predicted)
Out[50]: 469.0
In [51]: # detailed
actual-predicted
Out[51]: array([-30, -27, -26, 7, 11, 22, 21, 9, 16, 15, -13, 27, 31,
-25, 29, 7, 35, -24, 22, 5, 18, 29, 11, 27, -8])
In [52]: (actual-predicted)**2
Out[52]: array([ 900, 729, 676, 49, 121, 484, 441, 81, 256, 225, 169,
729, 961, 625, 841, 49, 1225, 576, 484, 25, 324, 841,
121, 729, 64], dtype=int32)
In [53]: np.mean((actual-predicted)**2)
Out[53]: 469.0
In [56]: np.isnan(S)
Out[57]: array([nan])
Plotting Graphs
In [60]: y = x
In [61]: y
In [63]: # y = x^2
x = np.linspace(-10,10,100)
y = x**2
plt.plot(x,y)
In [64]: # y = sin(x)
x = np.linspace(-10,10,100)
y = np.sin(x)
plt.plot(x,y)
In [65]: # y = xlog(x)
x = np.linspace(-10,10,100)
y = x * np.log(x)
plt.plot(x,y)
C:\Users\user\AppData\Local\Temp/ipykernel_9360/2564014901.py:3: RuntimeWarni
ng: invalid value encountered in log
y = x * np.log(x)
In [66]: # sigmoid
x = np.linspace(-10,10,100)
y = 1/(1+np.exp(-x))
plt.plot(x,y)
In [ ]:
Meshgrid
Meshgrids are a way to create coordinate matrices from coordinate vectors. In NumPy,
the meshgrid function is used to generate a coordinate grid given 1D coordinate arrays. It
produces two 2D arrays representing the x and y coordinates of each point on the grid
In [2]: x = np.linspace(0,10,100)
y = np.linspace(0,10,100)
In [3]: f = x**2+y**2
Plot
In [4]: plt.figure(figsize=(4,2))
plt.plot(f)
plt.show()
In [5]: x = np.arange(3)
y = np.arange(3)
In [6]: x
In [7]: y
Generating a meshgrid:
In [9]: xv
In [10]: yv
In [11]: P = np.linspace(-4, 4, 9)
V = np.linspace(-5, 5, 11)
print(P)
print(V)
In [13]: print(P_1)
In [14]: print(V_1)
These arrays, xv and yv, each seperately give the x and y coordinates on a 2D grid. You can do
normal numpy operations on these arrays:
In [16]: x = np.linspace(-2,2,100)
y = np.linspace(-1,1,100)
xv, yv = np.meshgrid(x, y)
f = np.exp(-xv**2-yv**2)
Note: pcolormesh is typically the preferable function for 2D plotting, as opposed to imshow or
pcolor, which take longer.)
x = np.linspace(-4, 4, 9)
plt.colorbar()
plt.show()
plt.colorbar()
plt.show()
C:\Users\user\AppData\Local\Temp/ipykernel_3612/3873722910.py:1: RuntimeWarni
ng: invalid value encountered in true_divide
sine = (np.sin(x_1**2 + y_1**2))/(x_1**2 + y_1**2)
We observe that x_1 is a row repeated matrix whereas y_1 is a column repeated matrix. One
row of x_1 and one column of y_1 is enough to determine the positions of all the points as the
other values will get repeated over and over.
In [26]: x_1
Out[26]: array([[-4., -3., -2., -1., 0., 1., 2., 3., 4.]])
In [27]: y_1
Out[27]: array([[-5.],
[-4.],
[-3.],
[-2.],
[-1.],
[ 0.],
[ 1.],
[ 2.],
[ 3.],
[ 4.],
[ 5.]])
The shape of x_1 changed from (11, 9) to (1, 9) and that of y_1 changed from (11, 9) to (11, 1)
The indexing of Matrix is however different. Actually, it is the exact opposite of Cartesian
indexing.
np.sort
Return a sorted copy of an array.
Out[28]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
In [31]: b = np.random.randint(1,100,24).reshape(6,4) # 2D
b
Out[32]: array([10, 12, 15, 33, 39, 44, 46, 53, 60, 66, 68, 74, 76, 87, 98])
Out[36]: array([98, 87, 76, 74, 68, 66, 60, 53, 46, 44, 39, 33, 15, 12, 10])
np.append
The numpy.append() appends values along the mentioned axis at the end of the array
In [37]: # code
a
Out[37]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
In [38]: np.append(a,200)
Out[38]: array([ 46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74,
10, 98, 200])
In [39]: b # on 2D
Out[42]: array([ 6., 51., 40., 85., 35., 28., 91., 68., 27., 30., 6., 4., 18.,
48., 48., 15., 35., 45., 99., 17., 42., 29., 88., 31., 1., 1.,
1., 1., 1., 1.])
In [43]: np.append(b,np.ones((b.shape[0],1)),axis=1)
np.concatenate
numpy.concatenate() function concatenate a sequence of arrays along an existing axis.
In [45]: # code
c = np.arange(6).reshape(2,3)
d = np.arange(6,12).reshape(2,3)
In [46]: c
In [47]: d
np.unique
With the help of np.unique() method, we can get the unique values from an array given as
parameter in np.unique() method.
In [50]: # code
e = np.array([1,1,2,2,3,3,4,4,5,5,6,6])
In [51]: e
In [52]: np.unique(e)
np.expand_dims
With the help of Numpy.expand_dims() method, we can get the expanded dimensions of an
array
In [53]: #code
a
Out[53]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
In [57]: a.shape # 1 D
Out[57]: (15,)
Out[56]: array([[46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98]])
Out[61]: (15, 1)
np.where
The numpy.where() function returns the indices of elements in an input array where the given
condition is satisfied.
In [62]: a
Out[62]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
np.argmax
The numpy.argmax() function returns indices of the max element of the array in a particular
axis.
arg = argument
In [68]: # code
a
Out[68]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
Out[69]: 14
In [71]: b # on 2D
In [75]: # np.argmin
a
Out[75]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
In [76]: np.argmin(a)
Out[76]: 13
On Statistics:
np.cumsum
numpy.cumsum() function is used when we want to compute the cumulative sum of array
elements over a given axis.
In [77]: a
Out[77]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
In [79]: np.cumsum(a)
Out[79]: array([ 46, 99, 114, 158, 191, 230, 306, 366, 434, 446, 533, 599, 673,
683, 781], dtype=int32)
In [85]: b
In [86]: np.cumsum(b)
Out[86]: array([ 6, 57, 97, 182, 217, 245, 336, 404, 431, 461, 467, 471, 489,
537, 585, 600, 635, 680, 779, 796, 838, 867, 955, 986], dtype=int32)
Out[88]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
In [89]: np.cumprod(a)
np.percentile
numpy.percentile()function used to compute the nth percentile of the given data (array
elements) along the specified axis.
In [90]: a
Out[90]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
Out[91]: 98.0
Out[92]: 10.0
Out[93]: 53.0
In [94]: np.median(a)
Out[94]: 53.0
np.histogram
Numpy has a built-in numpy.histogram() function which represents the frequency of data
distribution in the graphical form.
In [95]: a
Out[95]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
np.corrcoef
Return Pearson product-moment correlation coefficients.
In [102]: salary
In [103]: experience
Utility functions
np.isin
With the help of numpy.isin() method, we can see that one array having values are checked in
a different numpy array having different elements with different sizes.
In [105]: # code
a
Out[105]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
Out[107]: array([False, False, False, False, False, False, False, True, False,
False, False, False, False, True, False])
In [108]: a[np.isin(a,items)]
np.flip
The numpy.flip() function reverses the order of array elements along the specified axis,
preserving the shape of the array.
In [109]: # code
a
Out[109]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
Out[110]: array([98, 10, 74, 66, 87, 12, 68, 60, 76, 39, 33, 44, 15, 53, 46])
In [111]: b
In [112]: np.flip(b)
np.put
The numpy.put() function replaces specific elements of an array with given values of p_array.
Array indexed works on flattened array.
In [115]: # code
a
Out[115]: array([46, 53, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
In [117]: a
Out[117]: array([110, 530, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74,
10, 98])
np.delete
The numpy.delete() function returns a new array with the deletion of sub-arrays along with the
mentioned axis.
In [118]: # code
a
Out[118]: array([110, 530, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74,
10, 98])
Out[119]: array([530, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74, 10,
98])
Out[120]: array([530, 44, 39, 76, 60, 68, 12, 87, 66, 74, 10, 98])
Set functions
np.union1d
np.intersect1d
np.setdiff1d
np.setxor1d
np.in1d
In [121]: m = np.array([1,2,3,4,5])
n = np.array([3,4,5,6,7])
In [122]: # Union
np.union1d(m,n)
In [123]: # Intersection
np.intersect1d(m,n)
In [127]: np.setdiff1d(n,m)
In [131]: m[np.in1d(m,1)]
Out[131]: array([1])
In [130]: np.in1d(m,10)
np.clip
numpy.clip() function is used to Clip (limit) the values in an array.
In [132]: # code
a
Out[132]: array([110, 530, 15, 44, 33, 39, 76, 60, 68, 12, 87, 66, 74,
10, 98])
Out[133]: array([50, 50, 15, 44, 33, 39, 50, 50, 50, 15, 50, 50, 50, 15, 50])
it clips the minimum data to 15 and replaces everything below data to 15 and maximum
to 50
np.swapaxes
In [138]: arr
In [139]: swapped_arr
Original array:
[[1 2 3]
[4 5 6]]
Swapped array:
[[1 4]
[2 5]
[3 6]]
In [ ]:
https://t.me/AIMLDeepThaught
localhost:8888/notebooks/ Numpy Tricks ( Prudhvi Vardhan Notes).ipynb 20/20
Python Library – NumPy
NumPy is a general-purpose array-processing Python library which provides handy methods/functions for
working n-dimensional arrays. NumPy is a short form for “Numerical Python“. It provides various
computing tools such as comprehensive mathematical functions, and linear algebra routines.
In [3]: a = np.arange(15).reshape(3,5)
a
a.shape (3, 5) a.ndim 2 a.dtype.name 'int64' a.itemsize 8 a.size 15 type(a) <class 'numpy.ndarray'> b =
np.array([6, 7, 8]) b array([6, 7, 8]) type(b) <class 'numpy.ndarray'>
In [4]: # Shape
a.shape
Out[4]: (3, 5)
In [5]: # dimension
a.ndim
Out[5]: 2
Out[6]: dtype('int32')
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [7]: # item size
a.size
Out[7]: 15
In [8]: # type
print(type(a))
<class 'numpy.ndarray'>
Array Creation
In [9]: b = np.array([2,4,6,8])
b
Shape : (4,)
Size : 4
Data Type : int32
Type : <class 'numpy.ndarray'>
Shape : (4,)
Size : 4
Data Type : float64
Type : <class 'numpy.ndarray'>
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [13]: # 2 dimension array creation
d = np.array([(1,3,5,7),(2,4,6,8)])
d
Shape : (2, 4)
Size : 8
Data Type : int32
Type : <class 'numpy.ndarray'>
Out[16]: dtype('complex128')
In [17]: ab = np.zeros((3,4))
ab
In [18]: ac = np.ones((2,4))
ac
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [19]: # data type, shape, size
print(f"Zeros Array\nData Type : {ab.dtype}")
print(f"Item Size : {ab.size}")
print(f"Shape : {ab.shape}\n")
print(f"Ones Array\nData Type : {ac.dtype}")
print(f"Item Size : {ac.size}")
print(f"Shape : {ac.shape}")
Zeros Array
Data Type : float64
Item Size : 12
Shape : (3, 4)
Ones Array
Data Type : float64
Item Size : 8
Shape : (2, 4)
Ones Array
[[1 1 1]
[1 1 1]
[1 1 1]]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [22]: three = np.zeros((3,3))
three[1,1] = 5
inone = np.ones((5,5))
inone[1:-1,1:4] = three
print(f"Zeros with 5 \n\n{three}\n")
print(f"Ones & Zeros with 5 \n\n{inone}")
Zeros with 5
[[0. 0. 0.]
[0. 5. 0.]
[0. 0. 0.]]
[[1. 1. 1. 1. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 5. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 1. 1. 1. 1.]]
[[0. 0. 0. 0. 0.]
[0. 1. 1. 1. 0.]
[0. 1. 0. 1. 0.]
[0. 1. 1. 1. 0.]
[0. 0. 0. 0. 0.]]
[[1. 1. 1.]
[1. 0. 1.]
[1. 1. 1.]]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [25]: # copy numpy
onn = np.ones((3,2), dtype='int8')
onc = onn.copy()
onc[1,:] = 0
print('Original - \n', onn)
print('\nCopy - \n', onc)
Original -
[[1 1]
[1 1]
[1 1]]
Copy -
[[1 1]
[0 0]
[1 1]]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [31]: rng_reshape = np.arange(15).reshape(5,3)
rng_reshape
Shape : (4,)
Size : 4
Data Type : int32
Type : <class 'numpy.ndarray'>
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [37]: zeros_like = np.zeros_like(x_like)
zeros_like
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
Basic Operations
In [44]: a = np.array([10,20,30,40])
b = np.arange(4) Download Machine Learning Study Material:
add = a + b https://t.me/AIMLDeepThaught
sub = a - b # Subtraction (a-b)
mul = a * b
print(f"Array A : {a}\nArray B : {b}\n")
print(f"Addition (a+b)\n{add}\n")
print(f"Subtraction (a-b)\n{sub}\n")
print(f"Multiplication (a*b)\n{mul}\n")
Addition (a+b)
[10 21 32 43]
Subtraction (a-b)
[10 19 28 37]
Multiplication (a*b)
[ 0 20 60 120]
In [47]: a = np.array([[1,1],
[0,1]])
b = np.array([[2,0],
[3,4]])
a * b # elementwise product
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [48]: # matrix product
a @ b
In [51]: b += a
b
---------------------------------------------------------------------------
UFuncTypeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_10432\1729391664.py in <module>
----> 1 a += b # b is not automatically converted to integer type
2
3 a
In [53]: a = np.array([10,15,20,25,30])
a.sum()
Out[53]: 100
In [54]: a.min()
Out[54]: 10
In [55]: a.max()
Out[55]: 30
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [56]: b = np.arange(12).reshape(3, 4)
b
Universal Function
In [65]: a = np.array([10,20,30])
np.exp(a)
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [66]: np.sqrt(81)
Out[66]: 9.0
In [67]: b = np.array([4,9,16,25])
x = np.sqrt(b)
x
In [68]: y = np.array([1.,-2.,3.,-3.])
np.add(x, y)
[2 4 6 8]
(4,)
Out[71]: 8
[[1 2 3 4]
[5 6 7 8]]
(2, 4)
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [75]: b[1, 2] # print 7
Out[75]: 7
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
(2, 2, 3)
In [77]: c[0]
In [78]: c[1]
In [79]: c[0,0]
In [80]: c[1,0]
Out[81]: 6
In [82]: c[:, 1, 0]
Out[85]: dtype('<U16')
In [86]: b = np.array([100,200,300])
b.dtype
Out[86]: dtype('int32')
Out[87]: dtype('float64')
Out[88]: dtype('bool')
Out[89]: dtype('complex128')
The copy owns the data and any changes made to the copy will not affect original array, and any changes
made to the original array will not affect the copy.
The view does not own the data and any changes made to the view will affect the original array, and any
changes made to the original array will affect the view.
In [90]: a = np.array([1,2,3,4,5])
x = a.copy()
a[1] = 10
print(a)
print(x)
[ 1 10 3 4 5]
[1 2 3 4 5]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [91]: a = np.array([1,2,3,4,5])
x = a.copy()
x[1] = 7
print(a)
print(x)
[1 2 3 4 5]
[1 7 3 4 5]
In [92]: a = np.array([1,2,3,4,5])
x = a.view()
a[1] = 10
print(a)
print(x)
[ 1 10 3 4 5]
[ 1 10 3 4 5]
In [93]: a = np.array([1,2,3,4,5])
x = a.view()
x[-1] = 20
print(a)
print(x)
[ 1 2 3 4 20]
[ 1 2 3 4 20]
In [94]: a = np.arange((12))
a
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [96]: a3 = a.reshape(2,3,2) # Reshape 1D to 3D array
a3
[[ 6, 7],
[ 8, 9],
[10, 11]]])
a Shape: (12,)
a2 Shape: (4, 3)
a3 Shape: (2, 3, 2)
In [98]: for i in a:
print(i)
0
1
2
3
4
5
6
7
8
9
10
11
[0 1 2]
[3 4 5]
[6 7 8]
[ 9 10 11]
[[0 1]
[2 3]
[4 5]]
[[ 6 7]
[ 8 9]
[10 11]]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
NumPy Array Join
In [101]: a = np.array([1,2,3])
b = np.array([4,5,6])
ab = np.concatenate((a, b))
ab
In [102]: a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
ab = np.concatenate((a, b))
ab
In [103]: a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
ab = np.concatenate((a, b), axis=1)
ab
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [105]: a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
ab = np.hstack((a,b))
ab
In [106]: a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
ab = np.hstack((a, b))
ab
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [110]: a = np.array([1, 2, 3, 4, 5, 6])
ab = np.array_split(a, 3)
ab
In [112]: ab[0]
In [113]: ab[1]
In [114]: ab[2]
Out[114]: array([5])
In [115]: ab[3]
Out[115]: array([6])
2D Arrays Split
In [116]: a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]
ab = np.array_split(a, 2)
ab
In [117]: ab[0]
In [119]: a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]
ab = np.array_split(a, 3)
ab
In [120]: ab[0]
In [121]: ab[1]
In [122]: ab[2]
In [123]: a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
ab = np.array_split(a, 4)
ab
In [124]: ab[0]
In [125]: ab[1]
In [126]: ab[2]
Out[128]: [array([[1],
[4],
[7]]),
array([[2],
[5],
[8]]),
array([[3],
[6],
[9]])]
In [129]: a = np.array([[1,2],[3,4],[5,6]])
ab = np.hsplit(a, 2)
ab
Out[129]: [array([[1],
[3],
[5]]),
array([[2],
[4],
[6]])]
https://t.me/AIMLDeepThaught
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [130]: a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
ab = np.where(a == 5)
ab
Out[134]: 2
Out[135]: 7
Out[136]: 6
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [137]: a = np.array([6, 7, 8, 9, 10, 11, 12, 13])
ab = np.searchsorted(a, [1,3,8,9,10])
ab
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [143]: arr = np.array([1, 2, 3, 4, 5, 6, 7])
# Create an empty list
filter_arr = []
# go through each element in arr
for element in arr:
# if the element is completely divisble by 2, set the value to True, otherwise False
if element % 2 == 0:
filter_arr.append(True)
else:
filter_arr.append(False)
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
Random Numbers in NumPy
In [147]: x = random.randint(100)
print(x)
39
In [148]: x = random.rand()
x
Out[148]: 0.33150184362238155
[92 25 61]
In [150]: # Generate a 2-D array with 2 rows, each row containing 3 random integers from 0 to 100:
x = random.randint(100, size=(2,3))
x
In [152]: # Generate a 2-D array with 3 rows, each row containing 2 random numbers:
x = random.rand(3, 2)
print(x)
[[0.94764137 0.43819239]
[0.52815542 0.01067087]
[0.72109457 0.10579046]]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [153]: # Return one of the values in an array:
x = random.choice([3, 5, 7, 9])
print(x)
In [154]: # The choice() method also allows you to return an array of values.
# Add a size parameter to specify the shape of the array.
x = random.choice([3, 5, 7, 9], size=(3, 5))
print(x)
[[9 7 5 7 3]
[5 5 7 7 5]
[3 3 5 3 5]]
Data Distribution is a list of all possible values, and how often each value occurs. Such lists are important
when working with statistics and data science. The random module offer methods that returns randomly
generated data distributions.
ExampleGet your own Python Server Generate a 1-D array containing 100 values, where each value
has to be 3, 5, 7 or 9.
[5 7 3 7 7 7 3 7 7 7 7 7 7 5 7 3 7 7 5 7 5 5 7 3 7 7 5 7 7 7 7 7 5 7 5 7 7
7 7 7 7 7 7 7 7 7 7 5 5 5 5 5 7 7 7 7 7 5 7 3 3 7 5 5 7 7 7 5 5 5 5 5 5 5
7 7 5 7 7 5 5 7 5 7 7 5 7 7 7 7 7 7 7 7 5 7 3 5 5 7]
In [156]: # Same example as above, but return a 2-D array with 3 rows, each containing 5 values.
x = random.choice([3, 5, 7, 9], p=[0.1, 0.3, 0.6, 0.0], size=(3, 5))
print(x)
[[7 7 5 5 3]
[5 5 7 7 3]
[7 5 7 7 3]]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
Random Permutations of Elements
Shuffling Arrays
[1 2 4 3 5]
[1 5 4 2 3]
In [160]: # Generate a random normal distribution of size 2x3 with mean at 3 and standard deviation
x = random.normal(loc=3, scale=2, size=(2, 3))
print(x)
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [161]: import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot(random.normal(size=1000), hist=False)
plt.show()
C:\Users\User\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning:
`distplot` is a deprecated function and will be removed in a future version. Please ada
pt your code to use either `displot` (a figure-level function with similar flexibility)
or `kdeplot` (an axes-level function for kernel density plots).
warnings.warn(msg, FutureWarning)
Binomial Distribution
[ 8 11 7 9 11 11 11 14 7 7]
C:\Users\User\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning:
`distplot` is a deprecated function and will be removed in a future version. Please ada
pt your code to use either `displot` (a figure-level function with similar flexibility)
or `kdeplot` (an axes-level function for kernel density plots).
warnings.warn(msg, FutureWarning)
[0 2 1 1 1 1 2 0 3 2]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [166]: from numpy import random
import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot(random.poisson(lam=2, size=1000), kde=False)
plt.show()
C:\Users\User\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning:
`distplot` is a deprecated function and will be removed in a future version. Please ada
pt your code to use either `displot` (a figure-level function with similar flexibility)
or `histplot` (an axes-level function for histograms).
warnings.warn(msg, FutureWarning)
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [167]: from numpy import random
import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot(random.poisson(lam=3, size=1000))
plt.show()
Uniform Distribution
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
Visualization of Uniform Distribution
C:\Users\User\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning:
`distplot` is a deprecated function and will be removed in a future version. Please ada
pt your code to use either `displot` (a figure-level function with similar flexibility)
or `kdeplot` (an axes-level function for kernel density plots).
warnings.warn(msg, FutureWarning)
https://t.me/AIMLDeepThaught
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [170]: sns.distplot(random.uniform(size=30), hist=False)
plt.show()
C:\Users\User\anaconda3\lib\site-packages\seaborn\distributions.py:2619: FutureWarning:
`distplot` is a deprecated function and will be removed in a future version. Please ada
pt your code to use either `displot` (a figure-level function with similar flexibility)
or `kdeplot` (an axes-level function for kernel density plots).
warnings.warn(msg, FutureWarning)
NumPy ufuncs
In [171]: x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
z = []
for i, j in zip(x, y):
z.append(i + j)
print(z)
[5, 7, 9, 11]
In [172]: x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
z = np.add(x, y) # add() function
print(z)
[ 5 7 9 11]
[6 8 10 12]
In [175]: print(type(np.add))
<class 'numpy.ufunc'>
In [176]: print(type(np.concatenate))
<class 'function'>
add is ufunc
In [178]: try:
if type(np.blahblah) == np.ufunc:
print('blahblah is ufunc')
else:
print('blahblah is not ufunc')
except:
print('blahblah is not ufunc in NumPy.')
NumPy Arithmetic
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [179]: a = np.array([10,20,30,40])
b = np.array([100,200,300,400])
add = np.add(a, b)
print(add)
In [180]: a = np.array([10,20,30,40])
b = np.array([100,200,300,400])
subtract = np.subtract(b, a)
print(subtract)
In [181]: a = np.array([10,20,30,40])
b = np.array([100,200,300,400])
multiply = np.multiply(a, b)
print(multiply)
In [182]: a = np.array([10,20,30,40])
b = np.array([100,200,300,400])
divide = np.divide(b, a)
print(divide)
In [183]: a = np.array([10,20,30,40])
b = np.array([1,2,3,4])
power = np.power(a, b)
print(power)
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [184]: a = np.array([10,20,30,40])
b = np.array([3,4,6,7])
mod = np.mod(a, b)
print(mod)
[1 0 0 5]
In [185]: a = np.array([10,20,30,40])
b = np.array([3,4,6,7])
remainder = np.remainder(a, b)
print(remainder)
[1 0 0 5]
[-3. 3.]
[-3. 3.]
[-3. 4.]
[-4. 3.]
[-3. 4.]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
NumPy Logs
In [191]: import numpy as np
ab = np.arange(1, 6)
log2 = np.log2(ab)
print(log2)
In [192]: ab = np.arange(1, 6)
log10 = np.log10(ab)
print(log10)
In [193]: ab = np.arange(1, 6)
log = np.log(ab)
print(log)
NumPy does not provide any function to take log at any base, so we can use the frompyfunc() function
along with inbuilt function math.log() with two input parameters and one output parameter
1.7005483074552052
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
NumPy Products
24
40320
[ 24 1680]
[ 5 12 21 32]
[ 2 6 24 120]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [200]: a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
x = np.cumprod([a , b])
print(x)
[[ 1 2 6 24]
[ 5 30 210 1680]]
[[ 1 2 3 4]
[ 5 12 21 32]
[ 45 120 231 384]]
NumPy Differences
E.g. for [1, 2, 3, 4], the discrete difference would be [2-1, 3-2, 4-3] = [1, 1, 1]
[ 5 10 -20]
E.g. for [1, 2, 3, 4], the discrete difference with n = 2 would be [2-1, 3-2, 4-3] = [1, 1, 1] , then, since n=2, we
will do it once more, with the new result: [1-1, 1-1] = [0, 0]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [204]:
a = np.array([10, 15, 25, 5])
diff = np.diff(a, n=2)
print(diff)
[ 5 -30]
[0 0]
The Lowest Common Multiple is the smallest number that is a common multiple of two numbers.
In [206]: num1 = 4
num2 = 6
x = np.lcm(num1, num2)
print(x)
12
The reduce() method will use the ufunc, in this case the lcm() function, on each element, and reduce the
array by one dimension.
18
Returns: 18 because that is the lowest common multiple of all three numbers (36=18, 63=18 and 9*2=18).
In [208]: num1 = 6
num2 = 9
x = np.gcd(num1, num2)
print(x)
3
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
Returns: 3 because that is the highest number both numbers can be divided by (6/3=2 and 9/3=3).
The reduce() method will use the ufunc, in this case the gcd() function, on each element, and reduce the
array by one dimension.
Returns: 4 because that is the highest number all values can be divided by.
NumPy provides the ufuncs sin(), cos() and tan() that take values in radians and produce the
corresponding sin, cos and tan values.
In [210]: x = np.sin(np.pi/2)
print(x)
1.0
In [214]: x = np.arcsin(1.0)
print(x)
1.5707963267948966
In [217]: # Hypotenues
base = 3
perp = 4
x = np.hypot(base, perp)
print(x)
5.0
NumPy provides the ufuncs sinh(), cosh() and tanh() that take values in radians and produce the
corresponding sinh, cosh and tanh values.
In [218]: x = np.sinh(np.pi/2)
x
Out[218]: 2.3012989023072947
In [219]: x = np.cosh(np.pi/2)
x
Out[219]: 2.5091784786580567
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [220]: x = np.tanh(np.pi/2)
x
Out[220]: 0.9171523356672744
Finding Angles
Numpy provides ufuncs arcsinh(), arccosh() and arctanh() that produce radian values for corresponding
sinh, cosh and tanh values given.
In [221]: x = np.arcsinh(1.0)
print(x)
0.881373587019543
[1 2 3 4 5 6 7]
[1 2 3 4 5 6]
[3 4]
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js
In [225]: a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
x = np.setdiff1d(a, b, assume_unique=True)
print(x)
[1 2]
[1 2 5 6]
Download Machine
Learning Study
Material:
Loading [MathJax]/jax/output/HTML-CSS/fonts/STIX-Web/fontdata.js