Tutorial-2 Basic NumPy (2)
Tutorial-2 Basic NumPy (2)
March 1, 2025
1.1 Introduction
In this tutorial, we will cover: 1. Basics of NumPy: Arrays, their creation, and manipulation. 2.
Array operations: Mathematical, statistical, and logical. 3. Reshaping, indexing, and slicing arrays.
4. Working with real-world medical data examples. 5. Saving and loading data for reproducible
research. 6. Interactive quiz to reinforce learning.
1
2 NumPy Functionality Table
Function/Method
Description Example Output
np.array() Creates an array from a list or np.array([1, 2, 3]) [1, 2, 3]
tuple.
np.zeros() Creates an array of all zeros with a np.zeros((2, 2)) [[0., 0.], [0.,
specified shape. 0.]]
np.ones() Creates an array of all ones with a np.ones((2, 3)) [[1., 1., 1.],
specified shape. [1., 1., 1.]]
np.arange() Creates an array with evenly np.arange(0, 10, 2) [0, 2, 4, 6, 8]
spaced values within a range.
np.linspace() Creates an array with evenly np.linspace(0, 1, [0., 0.25, 0.5,
spaced values over a range. 5) 0.75, 1.]
np.reshape() Reshapes an array to a new shape. np.array([1, 2, 3, [[1, 2], [3,
4]).reshape(2, 2) 4]]
np.mean() Calculates the mean of array np.mean([1, 2, 3, 2.5
elements. 4])
np.median() Calculates the median of array np.median([1, 2, 3, 2.5
elements. 4])
np.std() Calculates the standard deviation. np.std([1, 2, 3, 1.118
4])
np.sum() Sums array elements. np.sum([1, 2, 3, 10
4])
np.max() Finds the maximum value in an np.max([1, 2, 3, 4
array. 4])
np.min() Finds the minimum value in an np.min([1, 2, 3, 1
array. 4])
np.sort() Sorts an array. np.sort([3, 1, 2]) [1, 2, 3]
np.unique() Finds unique elements in an array. np.unique([1, 2, 2, [1, 2, 3]
3])
Generates random numbers
np.random.rand() np.random.rand(2, Random 2x2
between 0 and 1. 2) array
Generates random integers within
np.random.randint() np.random.randint(0, Random integers
a range. 10, (2, 2)) 2x2 array
Solves a linear equation system.
np.linalg.solve() np.linalg.solve([[2, Solution array
3], [3, 2]], [8,
7])
np.save() Saves an array to a binary file. np.save('file.npy', Saves to file
arr)
np.load() Loads an array from a binary file. np.load('file.npy') Loaded array
2
3 Topics to be Covered in This Tutorial
In the table above, we will explore a few commonly used functions as a starting point to avoid
complexity. Later on, you can try them all on your own.
1. np.array()
2. np.zeros()
3. np.ones()
4. np.arange()
5. np.linspace()
6. np.reshape()
7. np.mean()
8. np.median()
9. np.std()
10. np.sum()
11. np.max()
12. np.min()
13. np.sort()
14. np.random.rand()
15. np.linalg.solve()
16. np.save()
17. np.load()
3.1 We will use simple examples to demonstrate how some of these function
works…
[ ]:
The np.array() function is used to create an array from a list or tuple. Arrays are the building
blocks of NumPy.
[13]: # Example: Creating a 1D array
array = np.array([1, 2, 3, 4])
print("Array:", array)
Array: [1 2 3 4]
3
Explanation: - np.array([1, 2, 3, 4]): Converts the list [1, 2, 3, 4] into a NumPy array.
- Output: [1, 2, 3, 4]
Zeros Array:
[[0. 0. 0.]
[0. 0. 0.]]
Explanation: - np.zeros((2, 3)): Creates a 2x3 array filled with zeros. - Output: [[0., 0.,
0.], [0., 0., 0.]]
Ones Array:
[[1. 1.]
[1. 1.]
[1. 1.]]
Explanation: - np.ones((3, 2)): Creates a 3x2 array filled with ones. - Output: [[1., 1.],
[1., 1.], [1., 1.]]
The np.arange() function creates an array with evenly spaced values within a given range.
Range Array: [0 2 4 6 8]
Explanation: - np.arange(0, 10, 2): Generates values from 0 to 9 with a step of 2. - Output:
[0, 2, 4, 6, 8]
4
4.0.5 5. Generating Evenly Spaced Values Using np.linspace()
The np.linspace() function generates evenly spaced numbers over a specified interval.
[17]: # Example: Generating 5 evenly spaced values between 0 and 1
linspace_array = np.linspace(0, 1, 5)
print("Linspace Array:", linspace_array)
Original Array: [1 2 3 4]
Reshaped Array:
[[1 2]
[3 4]]
Explanation: - original_array.reshape(2, 2): Converts the 1D array [1, 2, 3, 4] to a 2x2
array. - Output: [[1, 2], [3, 4]]
5
4.0.8 8. Calculating the Median with np.median()
The np.median() function calculates the median of the array elements. The median is the middle
value when the data is sorted.
[20]: # Example: Calculating the median of an array
array = np.array([1, 2, 3, 4, 5])
median_value = np.median(array)
print("Median:", median_value)
Median: 3.0
Explanation: - np.median([1, 2, 3, 4, 5]): Calculates the median of the array elements. -
Output: 3.0
The np.std() function calculates the standard deviation of the array elements, which measures
the spread or dispersion of the data.
[21]: # Example: Calculating the standard deviation of an array
array = np.array([1, 2, 3, 4, 5])
std_dev = np.std(array)
print("Standard Deviation:", std_dev)
The np.sum() function calculates the sum of all elements in the array.
[22]: # Example: Summing the elements of an array
array = np.array([1, 2, 3, 4, 5])
sum_value = np.sum(array)
print("Sum:", sum_value)
Sum: 15
Explanation: - np.sum([1, 2, 3, 4, 5]): Sums the array elements. - Output: 15
6
4.0.11 11. Finding the Maximum Value with np.max()
The np.max() function returns the maximum value from the array.
[23]: # Example: Finding the maximum value in an array
array = np.array([1, 2, 3, 4, 5])
max_value = np.max(array)
print("Max:", max_value)
Max: 5
Explanation: - np.max([1, 2, 3, 4, 5]): Finds the maximum value in the array. - Output: 5
The np.min() function returns the minimum value from the array.
[24]: # Example: Finding the minimum value in an array
array = np.array([1, 2, 3, 4, 5])
min_value = np.min(array)
print("Min:", min_value)
Min: 1
Explanation: - np.min([1, 2, 3, 4, 5]): Finds the minimum value in the array. - Output: 1
The np.sort() function sorts the elements of the array in ascending order.
[25]: # Example: Sorting an array
array = np.array([5, 3, 1, 4, 2])
sorted_array = np.sort(array)
print("Sorted Array:", sorted_array)
Sorted Array: [1 2 3 4 5]
Explanation: - np.sort([5, 3, 1, 4, 2]): Sorts the array in ascending order. - Output: [1,
2, 3, 4, 5]
The np.random.rand() function generates random numbers from a uniform distribution between
0 and 1.
7
[26]: # Example: Generating a 2x2 array of random numbers
random_array = np.random.rand(2, 2)
print("Random Array:\n", random_array)
Random Array:
[[0.64611576 0.14854119]
[0.03401987 0.05335882]]
Explanation: - np.random.rand(2, 2): Generates a 2x2 array with random values between 0
and 1. - Output: A 2x2 array with random values.
The np.load() function loads an array from a file saved in .npy format.
8
[29]: # Example: Loading an array from a file
loaded_array = np.load('array.npy')
print("Loaded Array:", loaded_array)
Loaded Array: [1 2 3 4 5]
Explanation: - np.load('array.npy'): Loads the array from the file ‘array.npy’. - Output: The
loaded array from the file. “‘
4.1 Quiz
[ ]:
9
Main
March 1, 2025
(512, 512, 3)
1
3. Filter np array to extract red | green | blue colors from the image and repaint image with
only red component and display it
[28]: # Ensure the image has 3 channels (RGB), ignoring alpha if present
if png_img_rgb.shape[-1] == 4: # RGBA
png_img_rgb = png_img_rgb[:, :, :3]
green_channel = png_img[:,:,1]
green_img = cv.merge((zero_channel, green_channel, zero_channel))
blue_channel = png_img[:,:,0]
blue_img = cv.merge((zero_channel, zero_channel, blue_channel))
2
plt.axis('off')
plt.subplot(131)
plt.imshow(red_img, cmap='gray')
plt.title('Red channel')
plt.axis('off')
plt.subplot(132)
plt.imshow(green_img, cmap='gray')
plt.title('Green channel')
plt.axis('off')
plt.subplot(133)
plt.imshow(blue_img, cmap='gray')
plt.title('Blue channel')
plt.axis('off')
# plt.axis('off')
plt.show()
3
plt.imshow(gray_img, cmap='gray')
plt.axis('off')
plt.show()
(512, 512)
Time taken by OpenCV function: 0.0003559589385986328 seconds
end = time.time()
diff_for = end - start
print(f'Time taken by for loop: {diff_for} seconds')
plt.imshow(gray_img, cmap='gray')
plt.axis('off')
plt.show()
# time differece
speedup = diff_for/diff_lib
4
print(f'Speedup by using numpy is: {speedup:.2f}x')
plt.subplot(122)
plt.title('Histogram')
plt.hist(gray_img.ravel(), bins=256, range=(0.0, 255.0), fc='k', ec='k')
plt.show()
5
6. Let X be the np matrix of the grayscale image
• obtain Y = X.T (transpose of X)
• obtain Z = Y.X (matrix multiplication of Y and X)
[32]: X = gray_img
print(f"{X.shape=}")
Y = X.T
print(f"{Y.shape=}")
# multiply Y and X
Z = np.matmul(Y,X)
print(f"{Z.shape=}")
X.shape=(512, 512)
Y.shape=(512, 512)
Z.shape=(512, 512)
7. Obtain a portion of the grayscale image and save it in an array A
[33]: P = int(X.shape[0]*.4),int(X.shape[1]*.4)
Q = int(X.shape[0]*.7),int(X.shape[1]*.7)
print(f"{P=}")
print(f"{Q=}")
P=(204, 204)
Q=(358, 358)
8. Display the partimage A
6
[39]: # display the originall and cropped image
plt.figure(figsize=(7,4))
plt.subplot(121)
plt.title('Original Image')
plt.imshow(gray_img, cmap='gray')
# display P and Q on the image
plt.plot([P[1], Q[1], Q[1], P[1], P[1]], [P[0], P[0], Q[0], Q[0], P[0]], 'r')
plt.text(P[1], P[0], 'P', color='b', fontsize=16)
plt.text(Q[1], Q[0], 'Q', color='b', fontsize=16)
plt.axis('off')
plt.subplot(122)
plt.title('Cropped Image A[P:Q]')
plt.imshow(A, cmap='gray')
plt.axis('off')
plt.show()