Lý thuyết
4-5 giờ
Bài 4/15

Nền tảng Toán học cho Machine Learning

Đại số tuyến tính, Thống kê và NumPy

Nền tảng Toán học cho Machine Learning

🎯 Mục tiêu bài học

Sau bài học này, học viên sẽ:

  • Nắm vững các khái niệm Đại số tuyến tính cần thiết
  • Hiểu các khái niệm Thống kê cơ bản
  • Thực hành tính toán với NumPy

1. Đại số tuyến tính (Linear Algebra)

1.1 Vector va Ma trận

Vector la mảng 1 chiều:

x=[x1x2xn]\mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix}

Ma trận la mảng 2 chiều:

A=[a11a12a1na21a22a2nam1am2amn]\mathbf{A} = \begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \cdots & a_{mn} \end{bmatrix}

1.2 Cac phép toán cơ bản

Phep toanCong thucDieu kien
Cộng ma tranC=A+BC = A + BCung kích thước
Nhân scalarB=kAB = kA-
Nhan ma tranC=A×BC = A \times BA: mxn, B: nxp
TransposeB=ATB = A^T-
Dot productab=aibia \cdot b = \sum a_i b_iCung độ dài

1.3 Thực hành NumPy

Python
1import numpy as np
2
3# Tạo vector
4x = np.array([1, 2, 3])
5print(f"Vector: {x}")
6print(f"Shape: {x.shape}")
7
8# Tạo ma trận
9A = np.array([[1, 2, 3],
10 [4, 5, 6]])
11print(f"Ma trận:\n{A}")
12print(f"Shape: {A.shape}")
13
14# Cac phép toán
15B = np.array([[7, 8, 9],
16 [10, 11, 12]])
17
18# Cong
19print(f"A + B:\n{A + B}")
20
21# Nhân scalar
22print(f"2 * A:\n{2 * A}")
23
24# Dot product
25a = np.array([1, 2, 3])
26b = np.array([4, 5, 6])
27print(f"a dot b: {np.dot(a, b)}") # 1*4 + 2*5 + 3*6 = 32
28
29# Nhan ma tran
30C = np.array([[1, 2],
31 [3, 4],
32 [5, 6]])
33print(f"A @ C:\n{A @ C}") # (2x3) @ (3x2) = (2x2)
34
35# Transpose
36print(f"A transpose:\n{A.T}")

2. Thống kê cơ bản (Statistics)

2.1 Cac do độ đo tập trung

Do doCong thucÝ nghĩa
Meanxˉ=1ni=1nxi\bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_iGiá trị trung bình
MedianGiá trị giuaKhông bị ảnh hưởng bởi outliers
ModeGiá trị xuat hien nhieu nhatCho du lieu phân loại

2.2 Cac độ đo phân tán

Variance (Phương sai):

σ2=1ni=1n(xixˉ)2\sigma^2 = \frac{1}{n}\sum_{i=1}^{n}(x_i - \bar{x})^2

Standard Deviation (Độ lệch chuẩn):

σ=σ2\sigma = \sqrt{\sigma^2}

2.3 Vi du tính toán

Dữ liệu: [2, 4, 4, 4, 5, 5, 7, 9]

Tính Mean: xˉ=2+4+4+4+5+5+7+98=408=5\bar{x} = \frac{2+4+4+4+5+5+7+9}{8} = \frac{40}{8} = 5

Tính Variance: σ2=(25)2+(45)2+...+(95)28=9+1+1+1+0+0+4+168=4\sigma^2 = \frac{(2-5)^2 + (4-5)^2 + ... + (9-5)^2}{8} = \frac{9+1+1+1+0+0+4+16}{8} = 4

Tính Standard Deviation: σ=4=2\sigma = \sqrt{4} = 2

2.4 Thực hành voi NumPy

Python
1import numpy as np
2
3data = np.array([2, 4, 4, 4, 5, 5, 7, 9])
4
5print(f"Mean: {np.mean(data)}")
6print(f"Median: {np.median(data)}")
7print(f"Variance: {np.var(data)}")
8print(f"Std: {np.std(data)}")
9print(f"Min: {np.min(data)}")
10print(f"Max: {np.max(data)}")
11print(f"Percentile 25: {np.percentile(data, 25)}")
12print(f"Percentile 75: {np.percentile(data, 75)}")

3. Covariance va Correlation

3.1 Covariance (Hiệp phương sai)

Cov(X,Y)=1ni=1n(xixˉ)(yiyˉ)Cov(X, Y) = \frac{1}{n}\sum_{i=1}^{n}(x_i - \bar{x})(y_i - \bar{y})

  • Cov>0Cov > 0: Tương quan thuận
  • Cov<0Cov < 0: Tương quan nghịch
  • Cov=0Cov = 0: Khong tuong quan tuyến tính

3.2 Correlation (Hệ số tương quan Pearson)

r=Cov(X,Y)σXσYr = \frac{Cov(X, Y)}{\sigma_X \sigma_Y}

Giá trị rÝ nghĩa
r = 1Tương quan thuận hoàn hảo
r = -1Tương quan nghịch hoàn hảo
r = 0Khong tuong quan
0.7 < r < 1Tương quan manh
0.3 < r < 0.7Tương quan vừa
r < 0.3Tương quan yếu

3.3 Thực hành

Python
1import numpy as np
2
3X = np.array([1, 2, 3, 4, 5])
4Y = np.array([2, 4, 5, 4, 5])
5
6# Covariance
7cov_matrix = np.cov(X, Y)
8print(f"Covariance Matrix:\n{cov_matrix}")
9
10# Correlation
11corr_matrix = np.corrcoef(X, Y)
12print(f"Correlation Matrix:\n{corr_matrix}")
13print(f"Correlation coefficient: {corr_matrix[0, 1]:.4f}")

4. Probability Distributions

4.1 Normal Distribution (Phân phối chuẩn)

f(x)=1σ2πe(xμ)22σ2f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}

Trong đó:

  • μ\mu: Mean (trung bình)
  • σ\sigma: Standard deviation (do lech chuan)

Normal Distribution

Hinh: Normal Distribution voi cac gia tri sigma khac nhau

4.2 Thực hành

Python
1import numpy as np
2import matplotlib.pyplot as plt
3from scipy import stats
4
5# Tao data tu normal distribution
6mu, sigma = 0, 1
7data = np.random.normal(mu, sigma, 1000)
8
9# Visualize
10plt.figure(figsize=(10, 4))
11plt.hist(data, bins=30, density=True, alpha=0.7)
12x = np.linspace(-4, 4, 100)
13plt.plot(x, stats.norm.pdf(x, mu, sigma), 'r-', lw=2)
14plt.title('Normal Distribution')
15plt.xlabel('Value')
16plt.ylabel('Density')
17plt.show()

5. Feature Scaling

5.1 Tại sao cần Scaling?

Vấn đềGiải pháp
Features co scale khac nhauStandardization
Gradient descent hội tụ chậmFeature scaling
Distance-based models bi biasNormalization

5.2 Cac phương pháp Scaling

Standardization (Z-score):

z=xμσz = \frac{x - \mu}{\sigma}

Min-Max Normalization:

xnorm=xxminxmaxxminx_{norm} = \frac{x - x_{min}}{x_{max} - x_{min}}

5.3 Thực hành

Python
1from sklearn.preprocessing import StandardScaler, MinMaxScaler
2import numpy as np
3
4# Data
5X = np.array([[1, 200],
6 [2, 400],
7 [3, 600],
8 [4, 800]])
9
10# StandardScaler
11scaler_std = StandardScaler()
12X_std = scaler_std.fit_transform(X)
13print(f"Standardized:\n{X_std}")
14print(f"Mean: {X_std.mean(axis=0)}")
15print(f"Std: {X_std.std(axis=0)}")
16
17# MinMaxScaler
18scaler_mm = MinMaxScaler()
19X_mm = scaler_mm.fit_transform(X)
20print(f"Min-Max Normalized:\n{X_mm}")
21print(f"Min: {X_mm.min(axis=0)}")
22print(f"Max: {X_mm.max(axis=0)}")

Ưu và nhược điểm cac phương pháp Scaling

Phuong phapUu diemNhuoc diem
StandardScalerKhông bị ảnh hưởng bởi outliers nhieuGiá trị khong giới hạn
MinMaxScalerGiá trị trong [0,1]Rat nhay voi outliers
RobustScalerKhông bị ảnh hưởng bởi outliersÍt phổ biến

Bài tập tự luyện

  1. Bài tập 1: Tinh mean, variance, std cua data: [10, 20, 30, 40, 50]
  2. Bài tập 2: Tinh correlation giua X = [1,2,3,4,5] va Y = [5,4,3,2,1]
  3. Bài tập 3: Áp dụng StandardScaler va MinMaxScaler cho một dataset

Tài liệu tham khảo