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ạnh | Lập trình truyền thống | Machine Learning |
|---|---|---|
| Input | Dữ liệu + Quy tắc cố định | Dữ liệu + Kết quả mong muốn |
| Output | Kết quả | Quy tắc/Model |
| Update | Thủ công khi có case mới | Tự động học pattern mới |
| Độ phức tạp | Giới hạn bởi người viết | Có thể phát hiện pattern phức tạp |
Ví dụ: Nhận diện email spam
Traditional Programming vs Machine Learning
| Lập trình truyền thống | Machine Learning |
|---|---|
| Viết if-else cho từng từ khóa spam | Model tự học từ dữ liệu có nhãn |
| Cần update thủ công khi có spam mới | Tự động học pattern mới |
| Giới hạn bởi quy tắc người viết | Có thể phát hiện pattern phức tạp |
2. Các loại Machine Learning
Machine Learning Types
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:
Trong đó:
- : Features (đặc trưng đầu vào)
- : Labels (nhãn/kết quả)
- : Hàm mà model cần học
- : 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ại | Input | Output | Ví dụ |
|---|---|---|---|
| Supervised - Regression | X, y (liên tục) | Model dự đoán giá trị | Giá nhà, doanh thu |
| Supervised - Classification | X, y (rời rạc) | Model phân loại | Spam detection, bệnh |
| Unsupervised - Clustering | X (không nhãn) | Nhóm tương tự | Customer segmentation |
| Unsupervised - Dim. Reduction | X (nhiều chiều) | X (ít chiều) | PCA, t-SNE |
| Reinforcement | State, Action | Policy tối ưu | Game AI, Robotics |
3. Workflow chuẩn của ML Project
ML Pipeline - End to End
3.1 ML Pipeline Chi tiết
| Bước | Tên | Mô tả | Công cụ |
|---|---|---|---|
| 1 | Data Collection | Thu thập từ DB, API, Files | SQL, API, Pandas |
| 2 | EDA | Khám phá, visualize | Pandas, Matplotlib, Seaborn |
| 3 | Preprocessing | Missing values, Outliers, Scaling | Pandas, Scikit-learn |
| 4 | Feature Engineering | Tạo features mới | Domain knowledge |
| 5 | Train/Test Split | Chia data 70-30 hoặc 80-20 | train_test_split |
| 6 | Model Selection | Chọn model phù hợp | Scikit-learn |
| 7 | Training | Fit model với training data | model.fit() |
| 8 | Evaluation | Đánh giá trên test data | Metrics (Accuracy, RMSE) |
| 9 | Tuning | GridSearchCV, tuning | Hyperparameter tuning |
| 10 | Deployment | Đưa vào production | Flask, FastAPI, Docker |
4. Các khái niệm quan trọng
4.1 Features và Labels
- m: Số samples (observations)
- n: Số features
4.2 Training vs Testing
| Training Set | Test Set | |
|---|---|---|
| Mục đích | Huấn luyện model | Đánh giá model |
| Tỷ lệ | 70-80% | 20-30% |
| Model thấy | Có (khi train) | Không (khi train) |
1from sklearn.model_selection import train_test_split23# Chia data4X_train, X_test, y_train, y_test = train_test_split(5 X, y, test_size=0.2, random_state=426)4.3 Overfitting vs Underfitting
| Trạng thái | Train Error | Test Error | Vấn đề |
|---|---|---|---|
| Underfitting | Cao | Cao | Model quá đơn giản (High Bias) |
| Good Fit | Thấp | Thấp | Lý tưởng ✅ |
| Overfitting | Rất thấp | Cao | Model 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
1# Cài đặt các thư viện cần thiết2pip install numpy pandas scikit-learn matplotlib seaborn1# Import thư viện2import numpy as np3import pandas as pd4from sklearn.model_selection import train_test_split5from sklearn.linear_model import LinearRegression6import matplotlib.pyplot as plt7import seaborn as sns5.2 Ví dụ đầu tiên: Dự đoán giá nhà
1from sklearn.datasets import fetch_california_housing2from sklearn.model_selection import train_test_split3from sklearn.linear_model import LinearRegression4from sklearn.metrics import mean_squared_error, r2_score5import numpy as np67# 1. Load data8housing = fetch_california_housing()9X, y = housing.data, housing.target1011# Xem thông tin12print(f"Số samples: {X.shape[0]}")13print(f"Số features: {X.shape[1]}")14print(f"Feature names: {housing.feature_names}")1516# 2. Train/Test split17X_train, X_test, y_train, y_test = train_test_split(18 X, y, test_size=0.2, random_state=4219)2021print(f"Training set: {X_train.shape}")22print(f"Test set: {X_test.shape}")2324# 3. Train model25model = LinearRegression()26model.fit(X_train, y_train)2728# 4. Predict29y_pred = model.predict(X_test)3031# 5. Evaluate32mse = mean_squared_error(y_test, y_pred)33rmse = np.sqrt(mse)34r2 = r2_score(y_test, y_pred)3536print(f"\n📊 Model Performance:")37print(f"MSE: {mse:.4f}")38print(f"RMSE: {rmse:.4f}")39print(f"R² Score: {r2:.4f}")4041# 6. Visualize predictions42import matplotlib.pyplot as plt4344plt.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:
1Số samples: 206402Số features: 83Feature names: ['MedInc', 'HouseAge', 'AveRooms', ...]4 5Training set: (16512, 8)6Test set: (4128, 8)7 8📊 Model Performance:9MSE: 0.555810RMSE: 0.745511R² Score: 0.57576. Ưu và nhược điểm của ML
| ✅ Ưu điểm | ❌ Nhược điểm |
|---|---|
| Tự động học từ dữ liệu | Cần nhiều dữ liệu chất lượng |
| Phát hiện pattern phức tạp | Khó giải thích (black box) |
| Tự cải thiện theo thời gian | Cần nhiều tính toán (GPU) |
| Xử lý được bài toán phi tuyến | Dễ 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
-
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
-
Bài tập 2: Cài đặt môi trường và chạy ví dụ dự đoán giá nhà ở trên
-
Bài tập 3: Tìm hiểu thêm về Reinforcement Learning và cho 2 ví dụ thực tế
-
Bài tập 4: So sánh Bias vs Variance - cho ví dụ cụ thể
