GVHD: Th.S Võ Việt Khoa - Khoa CNTT - Trường ĐH Mở [Link].
Lesson 2: NumPy Advanced Operations
Các phép toán nâng cao với NumPy
Lesson Information | Thông tin bài học
Item Description
Duration 90 minutes
Type Lecture + Lab
Prerequisites Lesson 1: NumPy Fundamentals
Learning Objectives | Mục tiêu bài học
# Objective Assessment
1 Perform element-wise arithmetic operations Code exercises
2 Understand and apply broadcasting Quiz
3 Use aggregation and statistical functions Lab work
4 Apply linear algebra operations Code exercises
1. Element-wise Operations (20 min)
1.1 Arithmetic Operations
import numpy as np
a = [Link]([1, 2, 3, 4])
b = [Link]([5, 6, 7, 8])
# Basic arithmetic (element-wise)
print(a + b) # [ 6 8 10 12]
print(a - b) # [-4 -4 -4 -4]
print(a * b) # [ 5 12 21 32]
print(a / b) # [0.2 0.33 0.43 0.5 ]
print(a ** 2) # [ 1 4 9 16]
print(a % 2) # [1 0 1 0]
print(a // 2) # [0 1 1 2]
# NumPy functions (equivalent)
print([Link](a, b))
print([Link](a, b))
print([Link](a, b))
1 / 11
GVHD: Th.S Võ Việt Khoa - Khoa CNTT - Trường ĐH Mở [Link].
print([Link](a, b))
print([Link](a, 2))
1.2 Comparison Operations
a = [Link]([1, 2, 3, 4, 5])
b = [Link]([5, 4, 3, 2, 1])
print(a == b) # [False False True False False]
print(a != b) # [ True True False True True]
print(a > b) # [False False False True True]
print(a >= b) # [False False True True True]
print(a < b) # [ True True False False False]
print(a <= b) # [ True True True False False]
# Array comparison functions
print(np.array_equal(a, b)) # False
print([Link](a, b)) # False (for float comparison)
1.3 Universal Functions (ufuncs)
arr = [Link]([1, 4, 9, 16, 25])
# Math functions
print([Link](arr)) # [1. 2. 3. 4. 5.]
print([Link](arr)) # [e^1 e^4 ...]
print([Link](arr)) # Natural log
print(np.log10(arr)) # Log base 10
print(np.log2(arr)) # Log base 2
# Trigonometric
angles = [Link]([0, [Link]/6, [Link]/4, [Link]/3, [Link]/2])
print([Link](angles))
print([Link](angles))
print([Link](angles))
# Rounding
arr = [Link]([1.2, 2.5, 3.7, 4.1])
print([Link](arr)) # [1. 2. 4. 4.]
print([Link](arr)) # [1. 2. 3. 4.]
print([Link](arr)) # [2. 3. 4. 5.]
print([Link](arr)) # [1. 2. 3. 4.]
# Absolute value
arr = [Link]([-1, -2, 3, -4])
print([Link](arr)) # [1 2 3 4]
print([Link](arr)) # Same
2 / 11
GVHD: Th.S Võ Việt Khoa - Khoa CNTT - Trường ĐH Mở [Link].
2. Broadcasting (20 min)
2.1 What is Broadcasting?
Broadcasting allows NumPy to perform operations on arrays of different shapes.
Rules:
. Compare shapes from right to left
. Dimensions are compatible if they are equal OR one of them is 1
. Smaller array is "broadcast" across larger array
2.2 Broadcasting Examples
# Scalar broadcast
arr = [Link]([1, 2, 3, 4])
print(arr + 10) # [11 12 13 14]
print(arr * 2) # [2 4 6 8]
# 1D + 1D (same shape)
a = [Link]([1, 2, 3])
b = [Link]([10, 20, 30])
print(a + b) # [11 22 33]
# 2D + 1D
arr2d = [Link]([[1, 2, 3],
[4, 5, 6]])
row = [Link]([10, 20, 30])
print(arr2d + row)
# [[11 22 33]
# [14 25 36]]
2.3 Broadcasting Visualization
Array A (3, 4): Array B (4,):
[[1 2 3 4] [10 20 30 40]
[5 6 7 8] ↓ broadcast
[9 10 11 12]] [[10 20 30 40]
[10 20 30 40]
+ [10 20 30 40]]
=
Result (3, 4):
[[11 22 33 44]
[15 26 37 48]
[19 30 41 52]]
2.4 Column Broadcasting
3 / 11
GVHD: Th.S Võ Việt Khoa - Khoa CNTT - Trường ĐH Mở [Link].
arr2d = [Link]([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Add column vector
col = [Link]([[10],
[20],
[30]])
# Or: col = [Link]([10, 20, 30]).reshape(-1, 1)
print(arr2d + col)
# [[11 12 13]
# [24 25 26]
# [37 38 39]]
2.5 Broadcasting Errors
a = [Link]([[1, 2, 3],
[4, 5, 6]]) # Shape: (2, 3)
b = [Link]([1, 2]) # Shape: (2,)
# This will ERROR - shapes (2,3) and (2,) not compatible
# print(a + b) # ValueError
# Fix: reshape b
b = [Link](-1, 1) # Shape: (2, 1)
print(a + b) # Now works!
3. Aggregation Functions (20 min)
3.1 Basic Aggregations
arr = [Link]([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
# Sum
print([Link](arr)) # 78 (all elements)
print([Link](arr, axis=0)) # [15 18 21 24] (sum of columns)
print([Link](arr, axis=1)) # [10 26 42] (sum of rows)
# Product
print([Link](arr)) # Product of all elements
# Cumulative
4 / 11
GVHD: Th.S Võ Việt Khoa - Khoa CNTT - Trường ĐH Mở [Link].
print([Link](arr)) # Cumulative sum
print([Link](arr)) # Cumulative product
3.2 Statistical Functions
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# Central tendency
print([Link](arr)) # 5.5
print([Link](arr)) # 5.5
# Mode: use [Link]()
# Spread
print([Link](arr)) # Standard deviation
print([Link](arr)) # Variance
print([Link](arr)) # Peak-to-peak (max - min)
# Min/Max
print([Link](arr)) # 1
print([Link](arr)) # 10
print([Link](arr)) # 0 (index of min)
print([Link](arr)) # 9 (index of max)
# Percentile/Quantile
print([Link](arr, 25)) # 3.25 (25th percentile)
print([Link](arr, 50)) # 5.5 (median)
print([Link](arr, 75)) # 7.75
print([Link](arr, 0.25)) # Same as percentile(arr, 25)
3.3 Aggregation with Axis
arr = [Link]([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# axis=0: operate along rows (result is per column)
print([Link](arr, axis=0)) # [4. 5. 6.]
# axis=1: operate along columns (result is per row)
print([Link](arr, axis=1)) # [2. 5. 8.]
# keepdims - maintain dimensions
print([Link](arr, axis=1, keepdims=True))
# [[2.]
# [5.]
# [8.]]
3.4 Boolean Aggregations
5 / 11
GVHD: Th.S Võ Việt Khoa - Khoa CNTT - Trường ĐH Mở [Link].
arr = [Link]([1, 2, 3, 4, 5])
# Check conditions
print([Link](arr > 3)) # True (at least one)
print([Link](arr > 3)) # False (not all)
print([Link](arr > 10)) # False
# Count
print([Link](arr > 3)) # 2 (count True values)
print(np.count_nonzero(arr > 3)) # 2
# Where (find indices)
print([Link](arr > 3)) # (array([3, 4]),)
print([Link](arr > 3, 'big', 'small'))
# ['small' 'small' 'small' 'big' 'big']
4. Linear Algebra (20 min)
4.1 Matrix Operations
A = [Link]([[1, 2],
[3, 4]])
B = [Link]([[5, 6],
[7, 8]])
# Matrix multiplication
print([Link](A, B))
# [[19 22]
# [43 50]]
# Or use @ operator (Python 3.5+)
print(A @ B)
# Element-wise multiplication (not matrix mult!)
print(A * B)
# [[ 5 12]
# [21 32]]
# Transpose
print(A.T)
# [[1 3]
# [2 4]]
# Trace (sum of diagonal)
print([Link](A)) # 5
# Determinant
print([Link](A)) # -2.0
6 / 11
GVHD: Th.S Võ Việt Khoa - Khoa CNTT - Trường ĐH Mở [Link].
# Inverse
print([Link](A))
# [[-2. 1. ]
# [ 1.5 -0.5]]
# Verify: A @ A_inv = I
print(A @ [Link](A))
4.2 Solving Linear Equations
# Solve: Ax = b
# 2x + 3y = 8
# 3x + 4y = 11
A = [Link]([[2, 3],
[3, 4]])
b = [Link]([8, 11])
x = [Link](A, b)
print(x) # [1. 2.] -> x=1, y=2
# Verify
print(A @ x) # [8. 11.]
4.3 Eigenvalues and Eigenvectors
A = [Link]([[4, 2],
[1, 3]])
# Eigenvalues and eigenvectors
eigenvalues, eigenvectors = [Link](A)
print("Eigenvalues:", eigenvalues)
print("Eigenvectors:\n", eigenvectors)
# Verify: A @ v = λ @ v
for i in range(len(eigenvalues)):
v = eigenvectors[:, i]
λ = eigenvalues[i]
print(f"A @ v: {A @ v}")
print(f"λ * v: {λ * v}")
4.4 Matrix Decomposition
# SVD - Singular Value Decomposition
A = [Link]([[1, 2, 3],
7 / 11
GVHD: Th.S Võ Việt Khoa - Khoa CNTT - Trường ĐH Mở [Link].
[4, 5, 6]])
U, s, Vt = [Link](A)
print("U:", [Link]) # (2, 2)
print("s:", [Link]) # (2,) singular values
print("Vt:", [Link]) # (3, 3)
# Reconstruct A
S = [Link]((2, 3))
S[:2, :2] = [Link](s)
A_reconstructed = U @ S @ Vt
# QR Decomposition
Q, R = [Link](A.T)
# Cholesky Decomposition (for positive definite matrices)
# A = L @ L.T
4.5 Norms
v = [Link]([3, 4])
A = [Link]([[1, 2], [3, 4]])
# Vector norms
print([Link](v)) # L2 (Euclidean): 5.0
print([Link](v, 1)) # L1 (Manhattan): 7
print([Link](v, [Link])) # L∞ (Max): 4
# Matrix norms
print([Link](A)) # Frobenius norm
print([Link](A, 'fro')) # Same
5. Advanced Techniques (10 min)
5.1 Sorting
arr = [Link]([3, 1, 4, 1, 5, 9, 2, 6])
# Sort
print([Link](arr)) # [1 1 2 3 4 5 6 9]
print([Link](arr)) # [1 3 6 0 2 4 7 5] (indices)
# Sort 2D
arr2d = [Link]([[3, 1, 2],
[6, 4, 5]])
print([Link](arr2d, axis=0)) # Sort each column
print([Link](arr2d, axis=1)) # Sort each row
8 / 11
GVHD: Th.S Võ Việt Khoa - Khoa CNTT - Trường ĐH Mở [Link].
# Partial sort
print([Link](arr, 3)) # First 3 smallest, rest unsorted
5.2 Set Operations
a = [Link]([1, 2, 3, 4, 5])
b = [Link]([3, 4, 5, 6, 7])
print(np.intersect1d(a, b)) # [3 4 5]
print(np.union1d(a, b)) # [1 2 3 4 5 6 7]
print(np.setdiff1d(a, b)) # [1 2]
print(np.setxor1d(a, b)) # [1 2 6 7]
print(np.in1d(a, b)) # [False False True True True]
5.3 Copying vs Views
arr = [Link]([1, 2, 3, 4, 5])
# View (shares memory)
view = arr[1:4]
view[0] = 100
print(arr) # [1 100 3 4 5] - original changed!
# Copy (independent)
arr = [Link]([1, 2, 3, 4, 5])
copy = arr[1:4].copy()
copy[0] = 100
print(arr) # [1 2 3 4 5] - original unchanged
Practice Exercises | Bài tập thực hành
Exercise 2.1: Broadcasting Practice
# Create a 5x5 distance matrix where element [i,j]
# is the absolute difference |i - j|
# Expected:
# [[0 1 2 3 4]
# [1 0 1 2 3]
# [2 1 0 1 2]
# [3 2 1 0 1]
# [4 3 2 1 0]]
Exercise 2.2: Statistics
9 / 11
GVHD: Th.S Võ Việt Khoa - Khoa CNTT - Trường ĐH Mở [Link].
# Given: 100 random exam scores (0-100)
scores = [Link](0, 101, 100)
# Calculate:
# 1. Mean, median, std
# 2. Number of students who passed (≥50)
# 3. Percentage of A grades (≥90)
# 4. Grade distribution (A, B, C, D, F)
Exercise 2.3: Linear Algebra
# 1. Solve the system:
# x + 2y + 3z = 14
# 2x + 5y + 3z = 18
# 4x + 6y + 8z = 32
# 2. Find eigenvalues of:
# [[4, -2],
# [1, 1]]
Exercise 2.4: Image Processing Simulation
# Create a 100x100 "image" (random values 0-255)
# 1. Normalize to 0-1 range
# 2. Apply threshold (>0.5 = 1, else 0)
# 3. Count white and black pixels
# 4. Calculate mean intensity per row
Summary | Tóm tắt
Key Operations
Category Functions
Arithmetic +, -, *, /, **, @
Comparison ==, !=, >, <, >=, <=
Aggregation sum, mean, std, min, max
Linear Algebra dot, inv, solve, eig
Broadcasting Rules
. Compare shapes right-to-left
. Dimensions must be equal or one must be 1
10 / 11
GVHD: Th.S Võ Việt Khoa - Khoa CNTT - Trường ĐH Mở [Link].
. Smaller array broadcasts to match larger
Next Lesson | Bài tiếp theo
Lesson 3: Pandas Basics
Series and DataFrame
Reading data files
Data selection and filtering
11 / 11