DEV Community

Cover image for NumPy for Machine Learning & Deep Learning
arju10
arju10

Posted on

NumPy for Machine Learning & Deep Learning

Additional Resources

Numpy For Machine Learning & Deep Learning

Numpy

Numpy is a python library used to work with arrays and stands for Numarical python. It works on linear algebra, fourier transform, and matrices domain.
Numpy is faster than list because numpy provides array object.

Numpy Functions:

Note: To use numpy always import it.

import numpy as np // Here, numpy is imported as np
Enter fullscreen mode Exit fullscreen mode

Create Numpy array

1. zeros(): It creates a array with zeros. Example:

array_zeros = np.zeros((3,3))
print("Array of Zeros: \n", array_zeros)
Enter fullscreen mode Exit fullscreen mode

Output

Array of Zeros:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

2. ones(): It creates a array with ones. Example:

array_ones = np.ones((2,2))
print("Array of ones: \n",array_ones)
Enter fullscreen mode Exit fullscreen mode

Output

Array of ones:
[[1. 1.]
[1. 1.]]

3. full(): It creates a array with all elements as 7. Example:

array_full = np.full((2,2),7)
print("Array with all elements as 7 : \n",array_full)
Enter fullscreen mode Exit fullscreen mode

Output

Array with all elements as 7 :
[[7 7]
[7 7]]

4. range(): It creates a array between 0 to 20. Example:

array_range = np.arange(20)
print("Array with range of numbers : ",array_range)
Enter fullscreen mode Exit fullscreen mode

Output

Array with range of numbers :
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]

Array Indexing [row:column]

import numpy as np

# Create a 2D array
array_2d = np.array(
    [
        [1,2,3],
        [4,5,6],
        [7,8,9]
    ]
)
Enter fullscreen mode Exit fullscreen mode

1. Accessing Individual elements:

# Accessing individual elements
element = array_2d[1,2] # Accessing element at row 1, column 2

print("Element at (1,2) : ", element)
Enter fullscreen mode Exit fullscreen mode

Output
Element at (1,2) : 6

2. Slicing Row:

row_slice = array_2d[0, : ] # First row
print("First Row : ", row_slice)
Enter fullscreen mode Exit fullscreen mode

Output
First Row : [1 2 3]

3. Slicing Column:

column_slice = array_2d[:, 1] # Second Column
print("Second Column: ", column_slice)
Enter fullscreen mode Exit fullscreen mode

Output
Second Column: [2 5 8]

Boolean Indexing

import numpy as np

# Create a array
array = np.array(
    [10,20,30,40,60,80]
)

# Boolean Indexing
greater_than_20 = array[array > 20]

print("Elements greater than 20 : ",greater_than_20)
Enter fullscreen mode Exit fullscreen mode

Output
Elements greater than 20 : [30 40 60 80]

Top comments (0)