Phần 2 · Nền tảng Machine Learning · Bài 8

Feature Engineering & Selection

13:00

Một feature tốt đáng giá bằng cả nghìn điểm dữ liệu.

Loại bài: Build
Ngôn ngữ: Python
Cần biết trước: Phần 1 (Thống kê cho ML, Đại số tuyến tính), Phần 2, bài 1–7
Thời gian: ~90 phút

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

  • Tự triển khai các phép biến đổi dữ liệu số (standardization, min-max scaling, log transform, binning) và giải thích khi nào nên dùng từng phép
  • Tự xây dựng one-hot encoding, label encoding và target encoding cho các feature dạng phân loại, đồng thời nhận ra nguy cơ data leakage trong target encoding
  • Tự xây dựng một TF-IDF vectorizer và giải thích vì sao nó hiệu quả hơn cách đếm số lần xuất hiện của từ khi phân loại văn bản
  • Áp dụng các phương pháp feature selection dựa trên bộ lọc (variance threshold, correlation, mutual information) để giảm số chiều

Vấn đề

Bạn có một dataset. Bạn chọn một thuật toán. Bạn training nó. Kết quả chỉ tàm tạm. Bạn thử một thuật toán xịn hơn. Vẫn tàm tạm. Bạn dành cả tuần tinh chỉnh hyperparameter. Kết quả nhích lên chút ít.

Rồi có người biến đổi dữ liệu thô thành các feature tốt hơn. Một mô hình logistic regression đơn giản đánh bại ensemble gradient boosting mà bạn đã dày công tinh chỉnh.

Chuyện này xảy ra suốt. Trong ML cổ điển, cách biểu diễn dữ liệu quan trọng hơn việc chọn thuật toán. Mô hình dự đoán giá nhà dùng «diện tích» và «số phòng ngủ» sẽ đánh bại mô hình dùng «địa chỉ dưới dạng chuỗi thô», dù thuật toán học của mô hình sau tinh vi đến đâu. Thuật toán chỉ làm việc được với những gì bạn đưa cho nó.

Feature engineering là quá trình biến đổi dữ liệu thô thành cách biểu diễn giúp mô hình dễ tìm ra quy luật hơn. Feature selection là quá trình loại bỏ những feature chỉ thêm nhiễu mà không thêm thông tin hữu ích. Kết hợp lại, đây là việc tạo ra tác động lớn nhất trong ML cổ điển.

Khái niệm

Feature pipeline

Sơ đồ

Feature dạng số

Các con số thô hiếm khi dùng ngay được cho mô hình. Những phép biến đổi thường gặp:

Scaling: Đưa các feature về cùng một khoảng giá trị để các thuật toán dựa trên khoảng cách (K-Means, KNN, SVM) đối xử với chúng như nhau. Min-max scaling đưa giá trị về [0, 1]. Standardization (z-score) đưa feature về mean=0, std=1.

Log transform: Nén các phân phối lệch phải (thu nhập, dân số, số lần xuất hiện của từ). Biến quan hệ nhân thành quan hệ cộng.

Binning: Chuyển giá trị liên tục thành các nhóm. Hữu ích khi quan hệ giữa feature và target không tuyến tính mà thay đổi theo từng nấc (ví dụ: nhóm tuổi).

Polynomial features: Tạo các hạng tử x2x^2, x3x^3, x1x2x_1 x_2. Giúp mô hình tuyến tính nắm bắt quan hệ phi tuyến, đổi lại là có thêm nhiều feature.

Feature dạng phân loại

Mô hình cần các con số. Các nhóm phải được encoding.

One-hot encoding: Tạo một cột nhị phân cho mỗi nhóm. «color = red/blue/green» trở thành ba cột: is_red, is_blue, is_green. Cách này hiệu quả với feature có ít nhóm, nhưng số cột sẽ bùng nổ nếu có nhiều nhóm.

Label encoding: Gán mỗi nhóm một số nguyên: red=0, blue=1, green=2. Cách này tạo ra thứ tự giả (mô hình có thể nghĩ green > blue > red). Chỉ phù hợp với các mô hình dựa trên cây, vốn chia dữ liệu theo từng giá trị.

Target encoding: Thay mỗi nhóm bằng giá trị trung bình của biến target trong nhóm đó. Hiệu quả nhưng nguy hiểm: nguy cơ data leakage cao. Bạn chỉ được tính giá trị này trên dữ liệu training, rồi áp dụng cho dữ liệu test.

Feature văn bản

Count vectorizer: Đếm số lần mỗi từ xuất hiện trong một văn bản. «the cat sat on the mat» trở thành {the: 2, cat: 1, sat: 1, on: 1, mat: 1}.

TF-IDF: Term Frequency-Inverse Document Frequency. Gán weight cho từ dựa trên mức độ khác biệt của nó giữa các văn bản. Những từ phổ biến như «the» có weight thấp. Những từ hiếm, mang tính đặc trưng có weight cao.

TF(word,doc)=count(word in doc)total words in docIDF(word)=log⁡total docsdocs containing wordTF-IDF=TF⋅IDF\begin{aligned} \text{TF}(\text{word}, \text{doc}) &= \frac{\text{count(word in doc)}}{\text{total words in doc}} \\ \text{IDF}(\text{word}) &= \log \frac{\text{total docs}}{\text{docs containing word}} \\ \text{TF-IDF} &= \text{TF} \cdot \text{IDF} \end{aligned}

Giá trị bị thiếu

Dữ liệu thực tế có những chỗ trống. Các cách xử lý:

  • Bỏ hàng: Chỉ khi dữ liệu bị thiếu ít và ngẫu nhiên
  • Điền bằng mean/median: Đơn giản, giữ giá trị ở vùng trung tâm của feature (median ít bị ảnh hưởng bởi outlier hơn), nhưng làm giảm variance và dồn mọi giá trị được điền vào cùng một điểm, khiến hình dạng phân phối thay đổi
  • Điền bằng mode: Dành cho feature dạng phân loại
  • Cột chỉ báo: Thêm cột nhị phân «was_this_missing» trước khi điền giá trị. Bản thân việc thiếu dữ liệu cũng có thể mang thông tin
  • Điền bằng giá trị trước/sau: Dành cho dữ liệu chuỗi thời gian

Tương tác giữa các feature

Đôi khi, quy luật nằm ở sự kết hợp. Riêng «chiều cao» và «cân nặng» dự đoán kém hơn BMI=weight/height2\text{BMI} = \text{weight} / \text{height}^2. Feature interaction làm số lượng feature tăng lên, vì vậy hãy dùng hiểu biết về lĩnh vực để chọn những kết hợp phù hợp.

Feature selection

Nhiều feature hơn chưa chắc đã tốt hơn. Feature không liên quan tạo thêm nhiễu, tăng thời gian training và có thể gây overfitting.

Phương pháp lọc (trước khi chạy mô hình):

  • Correlation: loại các feature có correlation cao với nhau (trùng lặp thông tin)
  • Mutual information: đo mức độ mà việc biết một feature làm giảm sự không chắc chắn về target
  • Variance threshold: loại các feature gần như không thay đổi

Phương pháp dựa trên mô hình:

  • L1 regularization (Lasso): đẩy weight của các feature không liên quan về đúng bằng 0
  • Recursive feature elimination: training, loại feature ít quan trọng nhất, rồi lặp lại

Vì sao cần chọn lọc: Mô hình có 10 feature tốt thường sẽ hoạt động tốt hơn mô hình có cùng 10 feature tốt và thêm 90 feature nhiễu. Các feature nhiễu tạo cơ hội để mô hình overfit vào những quy luật trong dữ liệu training nhưng không áp dụng được cho dữ liệu mới.

Tự xây dựng

Bước 1: Tự xây dựng các phép biến đổi dữ liệu số

python
import math


def min_max_scale(values):
    min_val = min(values)
    max_val = max(values)
    if max_val == min_val:
        return [0.0] * len(values)
    return [(v - min_val) / (max_val - min_val) for v in values]


def standardize(values):
    n = len(values)
    mean = sum(values) / n
    variance = sum((v - mean) ** 2 for v in values) / n
    std = math.sqrt(variance) if variance > 0 else 1.0
    return [(v - mean) / std for v in values]


def log_transform(values):
    return [math.log(v + 1) for v in values]


def bin_values(values, n_bins=5):
    min_val = min(values)
    max_val = max(values)
    bin_width = (max_val - min_val) / n_bins
    if bin_width == 0:
        return [0] * len(values)
    result = []
    for v in values:
        bin_idx = int((v - min_val) / bin_width)
        bin_idx = min(bin_idx, n_bins - 1)
        result.append(bin_idx)
    return result


def polynomial_features(row, degree=2):
    n = len(row)
    result = list(row)
    if degree >= 2:
        for i in range(n):
            result.append(row[i] ** 2)
        for i in range(n):
            for j in range(i + 1, n):
                result.append(row[i] * row[j])
    return result

Bước 2: Tự xây dựng encoding cho feature dạng phân loại

python
def one_hot_encode(values):
    categories = sorted(set(values))
    cat_to_idx = {cat: i for i, cat in enumerate(categories)}
    n_cats = len(categories)

    encoded = []
    for v in values:
        row = [0] * n_cats
        row[cat_to_idx[v]] = 1
        encoded.append(row)

    return encoded, categories


def label_encode(values):
    categories = sorted(set(values))
    cat_to_int = {cat: i for i, cat in enumerate(categories)}
    return [cat_to_int[v] for v in values], cat_to_int


def target_encode(feature_values, target_values, smoothing=10):
    global_mean = sum(target_values) / len(target_values)

    category_stats = {}
    for feat, target in zip(feature_values, target_values):
        if feat not in category_stats:
            category_stats[feat] = {"sum": 0.0, "count": 0}
        category_stats[feat]["sum"] += target
        category_stats[feat]["count"] += 1

    encoding = {}
    for cat, stats in category_stats.items():
        cat_mean = stats["sum"] / stats["count"]
        weight = stats["count"] / (stats["count"] + smoothing)
        encoding[cat] = weight * cat_mean + (1 - weight) * global_mean

    return [encoding[v] for v in feature_values], encoding

Bước 3: Tự xây dựng feature văn bản

python
def count_vectorize(documents):
    vocab = {}
    idx = 0
    for doc in documents:
        for word in doc.lower().split():
            if word not in vocab:
                vocab[word] = idx
                idx += 1

    vectors = []
    for doc in documents:
        vec = [0] * len(vocab)
        for word in doc.lower().split():
            vec[vocab[word]] += 1
        vectors.append(vec)

    return vectors, vocab


def tfidf(documents):
    n_docs = len(documents)

    vocab = {}
    idx = 0
    for doc in documents:
        for word in doc.lower().split():
            if word not in vocab:
                vocab[word] = idx
                idx += 1

    doc_freq = {}
    for doc in documents:
        seen = set()
        for word in doc.lower().split():
            if word not in seen:
                doc_freq[word] = doc_freq.get(word, 0) + 1
                seen.add(word)

    vectors = []
    for doc in documents:
        words = doc.lower().split()
        word_count = len(words)
        tf_map = {}
        for word in words:
            tf_map[word] = tf_map.get(word, 0) + 1

        vec = [0.0] * len(vocab)
        for word, count in tf_map.items():
            tf = count / word_count
            idf = math.log(n_docs / doc_freq[word])
            vec[vocab[word]] = tf * idf
        vectors.append(vec)

    return vectors, vocab

Bước 4: Tự điền giá trị bị thiếu

python
def impute_mean(values):
    present = [v for v in values if v is not None]
    if not present:
        return [0.0] * len(values), 0.0
    mean = sum(present) / len(present)
    return [v if v is not None else mean for v in values], mean


def impute_median(values):
    present = sorted(v for v in values if v is not None)
    if not present:
        return [0.0] * len(values), 0.0
    n = len(present)
    if n % 2 == 0:
        median = (present[n // 2 - 1] + present[n // 2]) / 2
    else:
        median = present[n // 2]
    return [v if v is not None else median for v in values], median


def impute_mode(values):
    present = [v for v in values if v is not None]
    if not present:
        return values, None
    counts = {}
    for v in present:
        counts[v] = counts.get(v, 0) + 1
    mode = max(counts, key=counts.get)
    return [v if v is not None else mode for v in values], mode


def add_missing_indicator(values):
    return [0 if v is not None else 1 for v in values]

Bước 5: Tự xây dựng feature selection

python
def correlation(x, y):
    n = len(x)
    mean_x = sum(x) / n
    mean_y = sum(y) / n
    cov = sum((xi - mean_x) * (yi - mean_y) for xi, yi in zip(x, y)) / n
    std_x = math.sqrt(sum((xi - mean_x) ** 2 for xi in x) / n)
    std_y = math.sqrt(sum((yi - mean_y) ** 2 for yi in y) / n)
    if std_x == 0 or std_y == 0:
        return 0.0
    return cov / (std_x * std_y)


def mutual_information(feature, target, n_bins=10):
    feat_min = min(feature)
    feat_max = max(feature)
    bin_width = (feat_max - feat_min) / n_bins if feat_max != feat_min else 1.0
    feat_binned = [
        min(int((f - feat_min) / bin_width), n_bins - 1) for f in feature
    ]

    n = len(feature)
    target_classes = sorted(set(target))

    feat_bins = sorted(set(feat_binned))
    p_feat = {}
    for b in feat_bins:
        p_feat[b] = feat_binned.count(b) / n

    p_target = {}
    for t in target_classes:
        p_target[t] = target.count(t) / n

    mi = 0.0
    for b in feat_bins:
        for t in target_classes:
            joint_count = sum(
                1 for fb, tv in zip(feat_binned, target) if fb == b and tv == t
            )
            p_joint = joint_count / n
            if p_joint > 0:
                mi += p_joint * math.log(p_joint / (p_feat[b] * p_target[t]))

    return mi


def variance_threshold(features, threshold=0.01):
    n_features = len(features[0])
    n_samples = len(features)
    selected = []

    for j in range(n_features):
        col = [features[i][j] for i in range(n_samples)]
        mean = sum(col) / n_samples
        var = sum((v - mean) ** 2 for v in col) / n_samples
        if var >= threshold:
            selected.append(j)

    return selected


def remove_correlated(features, threshold=0.9):
    n_features = len(features[0])
    n_samples = len(features)

    to_remove = set()
    for i in range(n_features):
        if i in to_remove:
            continue
        col_i = [features[r][i] for r in range(n_samples)]
        for j in range(i + 1, n_features):
            if j in to_remove:
                continue
            col_j = [features[r][j] for r in range(n_samples)]
            corr = abs(correlation(col_i, col_j))
            if corr >= threshold:
                to_remove.add(j)

    return [i for i in range(n_features) if i not in to_remove]

Bước 6: Pipeline hoàn chỉnh và bản demo

python
import random


def make_housing_data(n=200, seed=42):
    random.seed(seed)
    data = []
    for _ in range(n):
        sqft = random.uniform(500, 5000)
        bedrooms = random.choice([1, 2, 3, 4, 5])
        age = random.uniform(0, 50)
        neighborhood = random.choice(["downtown", "suburbs", "rural"])
        has_pool = random.choice([True, False])

        sqft_with_missing = sqft if random.random() > 0.05 else None
        age_with_missing = age if random.random() > 0.08 else None

        price = (
            50 * sqft
            + 20000 * bedrooms
            - 1000 * age
            + (50000 if neighborhood == "downtown" else 10000 if neighborhood == "suburbs" else 0)
            + (15000 if has_pool else 0)
            + random.gauss(0, 20000)
        )

        data.append({
            "sqft": sqft_with_missing,
            "bedrooms": bedrooms,
            "age": age_with_missing,
            "neighborhood": neighborhood,
            "has_pool": has_pool,
            "price": price,
        })
    return data


if __name__ == "__main__":
    data = make_housing_data(200)

    print("=== Raw Data Sample ===")
    for row in data[:3]:
        print(f"  {row}")

    sqft_raw = [d["sqft"] for d in data]
    age_raw = [d["age"] for d in data]
    prices = [d["price"] for d in data]

    print("\n=== Missing Value Handling ===")
    sqft_missing = sum(1 for v in sqft_raw if v is None)
    age_missing = sum(1 for v in age_raw if v is None)
    print(f"  sqft missing: {sqft_missing}/{len(sqft_raw)}")
    print(f"  age missing: {age_missing}/{len(age_raw)}")

    sqft_indicator = add_missing_indicator(sqft_raw)
    age_indicator = add_missing_indicator(age_raw)
    sqft_imputed, sqft_fill = impute_median(sqft_raw)
    age_imputed, age_fill = impute_mean(age_raw)
    print(f"  sqft filled with median: {sqft_fill:.0f}")
    print(f"  age filled with mean: {age_fill:.1f}")

    print("\n=== Numerical Transforms ===")
    sqft_scaled = standardize(sqft_imputed)
    age_scaled = min_max_scale(age_imputed)
    sqft_log = log_transform(sqft_imputed)
    age_binned = bin_values(age_imputed, n_bins=5)
    print(f"  sqft standardized: mean={sum(sqft_scaled)/len(sqft_scaled):.4f}, std={math.sqrt(sum(v**2 for v in sqft_scaled)/len(sqft_scaled)):.4f}")
    print(f"  age min-max: [{min(age_scaled):.2f}, {max(age_scaled):.2f}]")
    print(f"  age bins: {sorted(set(age_binned))}")

    print("\n=== Categorical Encoding ===")
    neighborhoods = [d["neighborhood"] for d in data]

    ohe, ohe_cats = one_hot_encode(neighborhoods)
    print(f"  One-hot categories: {ohe_cats}")
    print(f"  Sample encoding: {neighborhoods[0]} -> {ohe[0]}")

    le, le_map = label_encode(neighborhoods)
    print(f"  Label encoding map: {le_map}")

    te, te_map = target_encode(neighborhoods, prices, smoothing=10)
    print(f"  Target encoding: {({k: round(v) for k, v in te_map.items()})}")

    print("\n=== Text Features ===")
    descriptions = [
        "large modern house with pool",
        "small cozy cottage near downtown",
        "spacious family home with large yard",
        "modern apartment downtown with view",
        "rustic cabin in rural area",
    ]
    cv, cv_vocab = count_vectorize(descriptions)
    print(f"  Vocabulary size: {len(cv_vocab)}")
    print(f"  Doc 0 non-zero features: {sum(1 for v in cv[0] if v > 0)}")

    tf, tf_vocab = tfidf(descriptions)
    print(f"  TF-IDF vocabulary size: {len(tf_vocab)}")
    top_words = sorted(tf_vocab.keys(), key=lambda w: tf[0][tf_vocab[w]], reverse=True)[:3]
    print(f"  Doc 0 top TF-IDF words: {top_words}")

    print("\n=== Polynomial Features ===")
    sample_row = [sqft_scaled[0], age_scaled[0]]
    poly = polynomial_features(sample_row, degree=2)
    print(f"  Input: {[round(v, 4) for v in sample_row]}")
    print(f"  Polynomial: {[round(v, 4) for v in poly]}")
    print(f"  Features: [x1, x2, x1^2, x2^2, x1*x2]")

    print("\n=== Feature Selection ===")
    feature_matrix = [
        [sqft_scaled[i], age_scaled[i], float(sqft_indicator[i]), float(age_indicator[i])]
        + ohe[i]
        for i in range(len(data))
    ]

    print(f"  Total features: {len(feature_matrix[0])}")

    surviving_var = variance_threshold(feature_matrix, threshold=0.01)
    print(f"  After variance threshold (0.01): {len(surviving_var)} features kept")

    surviving_corr = remove_correlated(feature_matrix, threshold=0.9)
    print(f"  After correlation filter (0.9): {len(surviving_corr)} features kept")

    binary_prices = [1 if p > sum(prices) / len(prices) else 0 for p in prices]
    print("\n  Mutual information with target:")
    feature_names = ["sqft", "age", "sqft_missing", "age_missing"] + [f"neigh_{c}" for c in ohe_cats]
    for j in range(len(feature_matrix[0])):
        col = [feature_matrix[i][j] for i in range(len(feature_matrix))]
        mi = mutual_information(col, binary_prices, n_bins=10)
        print(f"    {feature_names[j]}: MI={mi:.4f}")

    print("\n  Correlation with price:")
    for j in range(len(feature_matrix[0])):
        col = [feature_matrix[i][j] for i in range(len(feature_matrix))]
        corr = correlation(col, prices)
        print(f"    {feature_names[j]}: r={corr:.4f}")

Dùng thực tế

Với scikit-learn, bạn có thể ghép các phép biến đổi này thành pipeline:

python
from sklearn.preprocessing import StandardScaler, OneHotEncoder, PolynomialFeatures
from sklearn.impute import SimpleImputer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import mutual_info_classif, VarianceThreshold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline

numeric_pipe = Pipeline([
    ("imputer", SimpleImputer(strategy="median")),
    ("scaler", StandardScaler()),
])

categorical_pipe = Pipeline([
    ("encoder", OneHotEncoder(sparse_output=False)),
])

preprocessor = ColumnTransformer([
    ("num", numeric_pipe, ["sqft", "age"]),
    ("cat", categorical_pipe, ["neighborhood"]),
])

Các phiên bản tự xây dựng cho bạn thấy chính xác điều gì xảy ra bên trong từng phép biến đổi. Các phiên bản trong thư viện xử lý thêm các trường hợp đặc biệt, hỗ trợ sparse matrix và cho phép ghép pipeline, nhưng phần toán học vẫn như nhau.

Đưa vào sản phẩm

Bài học này tạo ra:

  • outputs/prompt-feature-engineer.md - một prompt để xây dựng feature từ dữ liệu thô một cách có hệ thống

Bài tập

  1. Thêm robust scaling (dùng median và khoảng tứ phân vị thay cho mean và standard deviation) vào các phép biến đổi dữ liệu số. So sánh nó với standard scaling trên dữ liệu có outlier cực lớn.
  2. Triển khai leave-one-out target encoding: với mỗi hàng, tính mean của target nhưng không tính giá trị target của chính hàng đó. Cho thấy cách này giảm overfitting so với target encoding thông thường như thế nào.
  3. Xây dựng một feature selection pipeline tự động kết hợp variance threshold, lọc theo correlation và xếp hạng bằng mutual information. Áp dụng nó cho dataset giá nhà và so sánh hiệu quả mô hình (dùng một mô hình linear regression đơn giản) khi dùng tất cả feature với khi chỉ dùng các feature đã chọn.

Thuật ngữ chính

Thuật ngữNgười ta hay nóiNghĩa thật sự
Feature engineering«Tạo thêm cột mới»Biến đổi dữ liệu thô thành cách biểu diễn giúp mô hình nhận ra các quy luật
Standardization«Đưa về dạng bình thường»Trừ đi mean rồi chia cho standard deviation để feature có mean=0 và std=1
One-hot encoding«Tạo các biến giả»Tạo một cột nhị phân cho mỗi nhóm; ở mỗi hàng, đúng một cột có giá trị 1
Target encoding«Dùng đáp án để encoding»Thay mỗi nhóm bằng giá trị target trung bình của nhóm đó, có áp dụng smoothing để tránh overfitting
TF-IDF«Đếm từ kiểu xịn»Term Frequency nhân với Inverse Document Frequency: gán weight cho từ dựa trên mức độ đặc trưng của nó trong toàn bộ tập văn bản
Imputation«Điền vào chỗ trống»Thay giá trị bị thiếu bằng giá trị ước tính (mean, median, mode hoặc giá trị do mô hình dự đoán)
Feature selection«Loại các cột không tốt»Loại feature gây nhiễu hoặc trùng lặp, chỉ giữ những feature mang thông tin về target
Mutual information«Một thứ cho bạn biết bao nhiêu về thứ khác»Đại lượng đo mức giảm sự không chắc chắn về biến Y khi quan sát biến X
Data leakage«Vô tình gian lận»Dùng trong lúc training thông tin sẽ không có khi dự đoán, khiến kết quả có vẻ tốt hơn thực tế

Đọc thêm