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

Tuần 1: Giới thiệu Machine Learning

Tổng quan về ML, các loại học máy, và workflow chuẩn

Tuần 1 - Bài 1: Giới thiệu Machine Learning

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

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

  • Hiểu Machine Learning là gì và khác gì với lập trình truyền thống
  • Phân biệt được các loại Machine Learning
  • Nắm được workflow chuẩn của một ML project
  • Thiết lập được môi trường phát triển

1. Machine Learning là gì?

1.1 Định nghĩa

Machine Learning (Học máy) là một nhánh của Trí tuệ nhân tạo (AI) cho phép máy tính học từ dữ liệu mà không cần lập trình tường minh cho từng trường hợp.

"A computer program is said to learn from experience E with respect to some task T and some performance measure P, if its performance on T, as measured by P, improves with experience E." — Tom Mitchell

1.2 So sánh với lập trình truyền thống

Khía cạnhLập trình truyền thốngMachine Learning
InputDữ liệu + Quy tắc cố địnhDữ liệu + Kết quả mong muốn
OutputKết quảQuy tắc/Model
UpdateThủ công khi có case mớiTự động học pattern mới
Độ phức tạpGiới hạn bởi người viếtCó thể phát hiện pattern phức tạp

Ví dụ: Nhận diện email spam

Traditional Programming vs Machine Learning

Traditional: Write if-else rules
ML: Learn from labeled data
Lập trình truyền thốngMachine Learning
Viết if-else cho từng từ khóa spamModel tự học từ dữ liệu có nhãn
Cần update thủ công khi có spam mớiTự động học pattern mới
Giới hạn bởi quy tắc người viếtCó thể phát hiện pattern phức tạp

2. Các loại Machine Learning

Machine Learning Types

Machine Learning
Supervised Learning
Regression
Classification
Unsupervised Learning
Clustering
Dimensionality Reduction
Reinforcement Learning
Agent-Environment Interaction

2.1 Supervised Learning (Học có giám sát)

Dữ liệu có nhãn (label) - biết trước kết quả đúng.

Công thức tổng quát:

y=f(X)+ϵy = f(X) + \epsilon

Trong đó:

  • XX: Features (đặc trưng đầu vào)
  • yy: Labels (nhãn/kết quả)
  • ff: Hàm mà model cần học
  • ϵ\epsilon: Nhiễu

Ví dụ:

  • Regression: Dự đoán giá nhà (giá là số liên tục)
  • Classification: Phân loại email spam/không spam

2.2 Unsupervised Learning (Học không giám sát)

Dữ liệu không có nhãn - model tự tìm pattern/cấu trúc.

Ví dụ:

  • Clustering: Phân nhóm khách hàng
  • Dimensionality Reduction: Giảm số features (PCA, t-SNE)

2.3 Reinforcement Learning (Học tăng cường)

Model học thông qua thử và sai, nhận reward/penalty.

Ví dụ: AlphaGo, xe tự lái, game AI

2.4 Bảng tóm tắt các loại ML

LoạiInputOutputVí dụ
Supervised - RegressionX, y (liên tục)Model dự đoán giá trịGiá nhà, doanh thu
Supervised - ClassificationX, y (rời rạc)Model phân loạiSpam detection, bệnh
Unsupervised - ClusteringX (không nhãn)Nhóm tương tựCustomer segmentation
Unsupervised - Dim. ReductionX (nhiều chiều)X (ít chiều)PCA, t-SNE
ReinforcementState, ActionPolicy tối ưuGame AI, Robotics

3. Workflow chuẩn của ML Project

ML Pipeline - End to End

1. Data Collection
2. EDA & Visualization
3. Data Preprocessing
4. Feature Engineering
5. Train/Test Split
6. Model Selection & Training
7. Evaluation
8. Hyperparameter Tuning
9. Deployment

3.1 ML Pipeline Chi tiết

BướcTênMô tảCông cụ
1Data CollectionThu thập từ DB, API, FilesSQL, API, Pandas
2EDAKhám phá, visualizePandas, Matplotlib, Seaborn
3PreprocessingMissing values, Outliers, ScalingPandas, Scikit-learn
4Feature EngineeringTạo features mớiDomain knowledge
5Train/Test SplitChia data 70-30 hoặc 80-20train_test_split
6Model SelectionChọn model phù hợpScikit-learn
7TrainingFit model với training datamodel.fit()
8EvaluationĐánh giá trên test dataMetrics (Accuracy, RMSE)
9TuningGridSearchCV, tuningHyperparameter tuning
10DeploymentĐưa vào productionFlask, FastAPI, Docker

4. Các khái niệm quan trọng

4.1 Features và Labels

X=[x1(1)x2(1)xn(1)x1(2)x2(2)xn(2)x1(m)x2(m)xn(m)],y=[y(1)y(2)y(m)]X = \begin{bmatrix} x_1^{(1)} & x_2^{(1)} & \cdots & x_n^{(1)} \\ x_1^{(2)} & x_2^{(2)} & \cdots & x_n^{(2)} \\ \vdots & \vdots & \ddots & \vdots \\ x_1^{(m)} & x_2^{(m)} & \cdots & x_n^{(m)} \end{bmatrix}, \quad y = \begin{bmatrix} y^{(1)} \\ y^{(2)} \\ \vdots \\ y^{(m)} \end{bmatrix}

  • m: Số samples (observations)
  • n: Số features

4.2 Training vs Testing

Training SetTest Set
Mục đíchHuấn luyện modelĐánh giá model
Tỷ lệ70-80%20-30%
Model thấyCó (khi train)Không (khi train)
Python
1from sklearn.model_selection import train_test_split
2
3# Chia data
4X_train, X_test, y_train, y_test = train_test_split(
5 X, y, test_size=0.2, random_state=42
6)

4.3 Overfitting vs Underfitting

Total Error=Bias2+Variance+Irreducible Error\text{Total Error} = \text{Bias}^2 + \text{Variance} + \text{Irreducible Error}

Trạng tháiTrain ErrorTest ErrorVấn đề
UnderfittingCaoCaoModel quá đơn giản (High Bias)
Good FitThấpThấpLý tưởng ✅
OverfittingRất thấpCaoModel quá phức tạp (High Variance)

5. Thực hành: Thiết lập môi trường

5.1 Cài đặt thư viện

Bash
1# Cài đặt các thư viện cần thiết
2pip install numpy pandas scikit-learn matplotlib seaborn
Python
1# Import thư viện
2import numpy as np
3import pandas as pd
4from sklearn.model_selection import train_test_split
5from sklearn.linear_model import LinearRegression
6import matplotlib.pyplot as plt
7import seaborn as sns

5.2 Ví dụ đầu tiên: Dự đoán giá nhà

Python
1from sklearn.datasets import fetch_california_housing
2from sklearn.model_selection import train_test_split
3from sklearn.linear_model import LinearRegression
4from sklearn.metrics import mean_squared_error, r2_score
5import numpy as np
6
7# 1. Load data
8housing = fetch_california_housing()
9X, y = housing.data, housing.target
10
11# Xem thông tin
12print(f"Số samples: {X.shape[0]}")
13print(f"Số features: {X.shape[1]}")
14print(f"Feature names: {housing.feature_names}")
15
16# 2. Train/Test split
17X_train, X_test, y_train, y_test = train_test_split(
18 X, y, test_size=0.2, random_state=42
19)
20
21print(f"Training set: {X_train.shape}")
22print(f"Test set: {X_test.shape}")
23
24# 3. Train model
25model = LinearRegression()
26model.fit(X_train, y_train)
27
28# 4. Predict
29y_pred = model.predict(X_test)
30
31# 5. Evaluate
32mse = mean_squared_error(y_test, y_pred)
33rmse = np.sqrt(mse)
34r2 = r2_score(y_test, y_pred)
35
36print(f"\n📊 Model Performance:")
37print(f"MSE: {mse:.4f}")
38print(f"RMSE: {rmse:.4f}")
39print(f"R² Score: {r2:.4f}")
40
41# 6. Visualize predictions
42import matplotlib.pyplot as plt
43
44plt.figure(figsize=(10, 6))
45plt.scatter(y_test, y_pred, alpha=0.5)
46plt.plot([y_test.min(), y_test.max()],
47 [y_test.min(), y_test.max()],
48 'r--', lw=2)
49plt.xlabel('Actual Price')
50plt.ylabel('Predicted Price')
51plt.title('Actual vs Predicted House Prices')
52plt.grid(alpha=0.3)
53plt.show()

Output mẫu:

Text
1Số samples: 20640
2Số features: 8
3Feature names: ['MedInc', 'HouseAge', 'AveRooms', ...]
4
5Training set: (16512, 8)
6Test set: (4128, 8)
7
8📊 Model Performance:
9MSE: 0.5558
10RMSE: 0.7455
11R² Score: 0.5757

6. Ưu và nhược điểm của ML

✅ Ưu điểm❌ Nhược điểm
Tự động học từ dữ liệuCần nhiều dữ liệu chất lượng
Phát hiện pattern phức tạpKhó giải thích (black box)
Tự cải thiện theo thời gianCần nhiều tính toán (GPU)
Xử lý được bài toán phi tuyếnDễ bị overfitting
Không cần lập trình rules cụ thểPhụ thuộc vào chất lượng data

Bài tập tự luyện

  1. Bài tập 1: Phân loại các bài toán sau là Supervised hay Unsupervised:

    • Dự đoán bệnh nhân bị tiểu đường
    • Phân nhóm khách hàng theo hành vi
    • Dự đoán giá cổ phiếu
    • Phát hiện gian lận thẻ tín dụng
  2. Bài tập 2: Cài đặt môi trường và chạy ví dụ dự đoán giá nhà ở trên

  3. Bài tập 3: Tìm hiểu thêm về Reinforcement Learning và cho 2 ví dụ thực tế

  4. Bài tập 4: So sánh Bias vs Variance - cho ví dụ cụ thể


Tài liệu tham khảo