← Data Science and Engineering

DIMENSION REDUCTION · PROJECTION · MODEL-DERIVED FEATURES

เราไม่จำเป็นต้องส่ง Raw Features ทุกตัวเข้า Model โดยตรง

Dimensionality Reduction เปลี่ยน Feature จำนวนมากเป็น Representation ขนาดเล็ก ส่วน Logistic Regression สามารถรวม Evidence เป็น Score, Probability หรือ Log-odds ให้ Model ถัดไปใช้ แต่สิ่งเหล่านี้ไม่ได้ทำให้ Feature Engineering หายไป—เราย้ายงานไปอยู่ที่การเลือก Input, Objective, Fitting Population, Leakage Control และ Versioning

PYTHON NOTEBOOK · 45 CELLS15 techniques · worked experiments · exercises · leakage-safe workflow
ดาวน์โหลด Notebook สำหรับนักศึกษา
ORIGINAL FEATURESx₁ … xₚ

ข้อมูลที่วัดหรือสร้างจาก Domain

FITTED TRANSFORM / MODELTθ(X)

PCA, SVD, Encoder, Logistic Model

LEARNED FEATURESz₁ … zₖ

Component, Embedding, Score, Logit

DOWNSTREAM TASKg(Z, X*)

มักใช้ Z ร่วมกับ Feature สำคัญเดิม

01 · THREE DIFFERENT INTENTIONS

ลดมิติเพราะอะไร ต้องตอบก่อนเลือกเทคนิค

COMPRESSION

เก็บข้อมูลส่วนใหญ่ด้วยมิติน้อยลง

PCA, SVD, Autoencoder เหมาะเมื่อ Memory, Noise, Multicollinearity หรือ Training Cost เป็นปัญหา

SEPARATION

สร้างแกนที่ช่วยแยก Target

LDA, PLS และ Supervised Embedding ใช้ Y จึงต้อง Fit เฉพาะ Training Fold

SCORING

รวมหลาย Evidence เป็น Feature เดียว

Logistic score/log-odds สรุป Linear Evidence และส่งต่อสู่ Rule, Ranking หรือ Meta-model

02 · TECHNIQUE ATLAS

เทคนิค ข้อมูลที่เหมาะ และข้อจำกัดไม่ได้เหมือนกัน

กดเปิดแต่ละวิธีเพื่ออ่าน Method Dossier ฉบับเต็ม ตั้งแต่ Assumption, Preprocessing และ Model Selection ไปจนถึง Validation, Complexity, Failure Modes และ Python Code

01

PCA

Unsupervised · Linear

ข้อมูลตัวเลขต่อเนื่องที่ Standardize แล้ว และมี Correlation สูง

SUITABLE DATA

ข้อมูลตัวเลขต่อเนื่องที่ Standardize แล้ว และมี Correlation สูง

WHAT IT LEARNS

สร้างแกน Orthogonal ที่เก็บ Variance มากที่สุด

NOT A GOOD DEFAULT WHEN

ข้อมูล Nonlinear, Sparse count ที่ Scale ต่างมาก หรือ Component ต้องตีความตรงๆ

PREPROCESSING

Impute missing, split data, StandardScaler fit เฉพาะ train; พิจารณา RobustScaler เมื่อ outlier สูง

KEY HYPERPARAMETERS

n_components, svd_solver, whiten; เริ่มจาก explained variance และ downstream CV

HOW TO CHOOSE DIMENSION / MODEL

เลือก k จาก cumulative variance + validation score + latency ไม่ใช้ 95% เป็นกฎสากล

VALIDATION

ตรวจ reconstruction error, loading stability, downstream score และ drift ของ component score

COMPUTATIONAL COST

Full SVD โดยคร่าว O(min(np²,n²p)); randomized solver เหมาะเมื่อ k≪min(n,p)

FAILURE MODES

Scale dominance, outlier, component sign flip และ covariance เปลี่ยนตามเวลา

TRANSFORMATION EXAMPLEz₁=.71x₁+.69x₂+.12x₃
USE CASE

Sensor 200 ตัว → 15 components

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLEPCAFit on training data · transform held-out/new rows · persist the fitted artifact
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

X_train, X_test = train_test_split(X, test_size=.2, random_state=42)
pipe = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("scale", StandardScaler()),
    ("reduce", PCA(n_components=.95, svd_solver="full"))
])
Z_train = pipe.fit_transform(X_train)
Z_test = pipe.transform(X_test)
print(Z_train.shape, pipe[-1].explained_variance_ratio_.sum())
02

Truncated SVD / LSA

Unsupervised · Linear sparse

TF–IDF, user-item หรือ sparse high-dimensional matrix

SUITABLE DATA

TF–IDF, user-item หรือ sparse high-dimensional matrix

WHAT IT LEARNS

ลดมิติโดยไม่ต้อง Center sparse matrix; เก็บ latent directions

NOT A GOOD DEFAULT WHEN

ความหมาย Component อาจเปลี่ยนเมื่อ Corpus เปลี่ยน

PREPROCESSING

สร้าง sparse count/TF–IDF; ไม่ Center matrix; freeze tokenizer และ vocabulary/corpus policy

KEY HYPERPARAMETERS

n_components, n_iter, algorithm, random_state; ค่า k มักมากกว่า visualization dimension

HOW TO CHOOSE DIMENSION / MODEL

เลือก k จาก retrieval/classification CV, reconstruction proxy และ memory budget

VALIDATION

ตรวจ singular-value spectrum, topic coherence แบบระวัง และ performance บน future corpus

COMPUTATIONAL COST

Randomized SVD โดยประมาณ O(nnz(X)·k·iterations)

FAILURE MODES

Corpus drift, vocabulary drift, sign ambiguity และ latent axis ไม่ใช่ topic บริสุทธิ์

TRANSFORMATION EXAMPLE10,000 TF–IDF terms → 200 latent dimensions
USE CASE

Document retrieval / topic-like representation

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLETruncated SVD / LSAFit on training data · transform held-out/new rows · persist the fitted artifact
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.pipeline import Pipeline

lsa = Pipeline([
    ("tfidf", TfidfVectorizer(min_df=3, ngram_range=(1, 2))),
    ("svd", TruncatedSVD(n_components=200, n_iter=7, random_state=42))
])
Z_train = lsa.fit_transform(text_train)
Z_test = lsa.transform(text_test)
print(Z_train.shape, lsa[-1].explained_variance_ratio_.sum())
03

NMF

Unsupervised · Parts-based

ข้อมูล Non-negative เช่น count, intensity, purchase

SUITABLE DATA

ข้อมูล Non-negative เช่น count, intensity, purchase

WHAT IT LEARNS

W,H ≥ 0 ทำให้ Component มักเป็นส่วนประกอบที่อ่านง่ายกว่า

NOT A GOOD DEFAULT WHEN

ข้อมูลติดลบหรือ relation ที่ต้องหักล้างกัน

PREPROCESSING

Input ต้อง non-negative; เลือก count/TF–IDF/intensity และจัดการ zero/missing อย่างชัดเจน

KEY HYPERPARAMETERS

n_components, init, solver, beta_loss, alpha_W/H, l1_ratio, max_iter

HOW TO CHOOSE DIMENSION / MODEL

เลือก k จาก held-out reconstruction, stability, interpretability และ downstream task

VALIDATION

ตรวจ convergence, component stability หลาย seed และ feature loading ที่มีเหตุผล

COMPUTATIONAL COST

ขึ้นกับ solver; โดยทั่วไป iterative และแปรตาม nnz(X)·k·iterations

FAILURE MODES

Local minima, scale ambiguity, component ซ้ำ และค่าติดลบที่ถูก clip อย่างไม่เหมาะสม

TRANSFORMATION EXAMPLEpurchase matrix ≈ customer_topics × category_loadings
USE CASE

สินค้า 5,000 SKU → 30 shopping profiles

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLENMFFit on training data · transform held-out/new rows · persist the fitted artifact
from sklearn.decomposition import NMF

nmf = NMF(
    n_components=20, init="nndsvda", solver="cd",
    max_iter=500, random_state=42
)
W_train = nmf.fit_transform(X_train_nonnegative)
W_test = nmf.transform(X_test_nonnegative)
H = nmf.components_
print(W_train.shape, nmf.reconstruction_err_)
04

ICA

Unsupervised · Source separation

สัญญาณผสมที่สมมติ latent sources เป็นอิสระเชิงสถิติ

SUITABLE DATA

สัญญาณผสมที่สมมติ latent sources เป็นอิสระเชิงสถิติ

WHAT IT LEARNS

แยก Independent Components มากกว่าแกน Variance

NOT A GOOD DEFAULT WHEN

Noise สูง จำนวน source ไม่ชัด หรือ assumption independence ไม่เหมาะ

PREPROCESSING

Center/whiten data, ตรวจ rank และเลือก signal channels/window ที่สัมพันธ์กัน

KEY HYPERPARAMETERS

n_components, algorithm, whiten, fun, max_iter, tol, random_state

HOW TO CHOOSE DIMENSION / MODEL

จำนวน component อิงจำนวน source ที่สมเหตุผล + stability ไม่ใช่ variance อย่างเดียว

VALIDATION

ตรวจ convergence, independence proxy, source reproducibility และ domain plausibility

COMPUTATIONAL COST

Iterative matrix operations; โดยคร่าว O(iterations·n·p·k)

FAILURE MODES

Non-convergence, permutation/sign ambiguity และ assumption independent non-Gaussian sources ไม่จริง

TRANSFORMATION EXAMPLEmixed sensors X = A·S → estimate S
USE CASE

EEG/audio/machine vibration source separation

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLEICAFit on training data · transform held-out/new rows · persist the fitted artifact
from sklearn.decomposition import FastICA
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
Xs_train = scaler.fit_transform(X_train)
Xs_test = scaler.transform(X_test)
ica = FastICA(n_components=8, whiten="unit-variance",
              max_iter=1000, random_state=42)
S_train = ica.fit_transform(Xs_train)
S_test = ica.transform(Xs_test)
print(S_train.shape, ica.n_iter_)
05

Random Projection

Unsupervised · Random linear

ข้อมูลมิติสูงมาก ต้องการเร็วและยอมเสียระยะเล็กน้อย

SUITABLE DATA

ข้อมูลมิติสูงมาก ต้องการเร็วและยอมเสียระยะเล็กน้อย

WHAT IT LEARNS

คูณเมทริกซ์สุ่มเพื่อประมาณ pairwise distance

NOT A GOOD DEFAULT WHEN

ต้องการ Component ที่มีความหมายหรือ reproducibility โดยไม่เก็บ seed

PREPROCESSING

Impute/scale ตาม distance metric; กำหนด seed และเก็บ projection matrix

KEY HYPERPARAMETERS

n_components หรือ eps, density, random_state; Gaussian/Sparse projection

HOW TO CHOOSE DIMENSION / MODEL

ใช้ Johnson–Lindenstrauss bound เป็นเพดานเริ่มต้น แล้ว validate downstream

VALIDATION

ตรวจ distortion ของ pairwise distance จาก sample และ performance ของงานปลายทาง

COMPUTATIONAL COST

Dense O(npk); sparse projection ลดต้นทุนตาม density

FAILURE MODES

Projection seed หาย, k ต่ำเกินไป และ Feature scale ไม่สมเหตุผล

TRANSFORMATION EXAMPLEz = X·R / √k
USE CASE

1M sparse dimensions → 1,000 dimensions

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLERandom ProjectionFit on training data · transform held-out/new rows · persist the fitted artifact
from sklearn.random_projection import GaussianRandomProjection
from sklearn.preprocessing import StandardScaler

scale = StandardScaler()
Xs_train = scale.fit_transform(X_train)
Xs_test = scale.transform(X_test)
rp = GaussianRandomProjection(n_components=256, random_state=42)
Z_train = rp.fit_transform(Xs_train)
Z_test = rp.transform(Xs_test)
print(X_train.shape, "->", Z_train.shape)
06

Feature Hashing

Unsupervised · Streaming sparse

Token/category จำนวนมากหรือไม่รู้ Vocabulary ล่วงหน้า

SUITABLE DATA

Token/category จำนวนมากหรือไม่รู้ Vocabulary ล่วงหน้า

WHAT IT LEARNS

Hash key ลง fixed bins; memory คงที่และใช้ streaming ได้

NOT A GOOD DEFAULT WHEN

Collision สำคัญมากหรือต้องย้อนอ่านชื่อ Feature ทุกตัว

PREPROCESSING

กำหนด key normalization, namespace, signed hashing และ collision policy

KEY HYPERPARAMETERS

n_features, input_type, alternate_sign; ขนาด bin เป็น power-of-two เพื่อปฏิบัติการง่าย

HOW TO CHOOSE DIMENSION / MODEL

เพิ่ม bins จน collision/validation metric อยู่ในขอบเขตและ memory ยังรับได้

VALIDATION

ติดตาม occupancy, collision estimate, unseen key และ downstream calibration

COMPUTATIONAL COST

O(number of nonzero tokens); memory ต่อ row คงที่ตาม nonzero

FAILURE MODES

Hash configuration เปลี่ยน, namespace ชนกัน และ audit กลับชื่อ Feature ไม่ได้

TRANSFORMATION EXAMPLEhash(token) mod 2¹⁸
USE CASE

URL, ad IDs, event keys → 262,144 bins

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLEFeature HashingFit on training data · transform held-out/new rows · persist the fitted artifact
from sklearn.feature_extraction import FeatureHasher

hasher = FeatureHasher(
    n_features=2**18, input_type="dict", alternate_sign=True
)
rows_train = [{"country=TH": 1, "device=mobile": 1},
              {"country=JP": 1, "device=desktop": 1}]
Xh_train = hasher.transform(rows_train)
Xh_test = hasher.transform(rows_test)
print(Xh_train.shape, Xh_train.nnz)
07

LDA: Linear Discriminant Analysis

Supervised · Linear

Classification ที่ class separation สำคัญและ covariance assumptions พอใช้

SUITABLE DATA

Classification ที่ class separation สำคัญและ covariance assumptions พอใช้

WHAT IT LEARNS

หาแกนที่เพิ่ม Between-class / Within-class separation

NOT A GOOD DEFAULT WHEN

Nonlinear boundary, class distribution ซับซ้อน หรือ covariance singular มาก

PREPROCESSING

Split ก่อน fit, scale หากจำเป็น, ตรวจ class imbalance และ covariance rank

KEY HYPERPARAMETERS

solver, shrinkage, priors, n_components ≤ classes−1

HOW TO CHOOSE DIMENSION / MODEL

เลือก component จาก class count และ CV; shrinkage สำคัญเมื่อ p ใกล้/มากกว่า n

VALIDATION

ใช้ stratified CV, confusion/calibration และตรวจ axis stability

COMPUTATIONAL COST

ขึ้นกับ solver; covariance/eigen decomposition มักมีต้นทุนตาม p²/p³

FAILURE MODES

Target leakage, singular covariance, Gaussian/shared-covariance assumptions และ class drift

TRANSFORMATION EXAMPLEz = wᵀx; สูงสุดไม่เกิน C−1 axes
USE CASE

20 classes → ≤19 supervised components

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLELDA: Linear Discriminant AnalysisFit on training data · transform held-out/new rows · persist the fitted artifact
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import train_test_split

Xtr, Xte, ytr, yte = train_test_split(
    X, y, test_size=.2, stratify=y, random_state=42
)
lda = LinearDiscriminantAnalysis(solver="eigen", shrinkage="auto",
                                 n_components=min(2, len(set(ytr))-1))
Ztr = lda.fit_transform(Xtr, ytr)
Zte = lda.transform(Xte)
print(Ztr.shape, lda.score(Xte, yte))
08

PLS

Supervised · Linear

Predictors correlated จำนวนมาก และต้องการ Component ที่สัมพันธ์กับ Y

SUITABLE DATA

Predictors correlated จำนวนมาก และต้องการ Component ที่สัมพันธ์กับ Y

WHAT IT LEARNS

สร้าง latent scores โดยใช้ covariance ระหว่าง X และ Y

NOT A GOOD DEFAULT WHEN

ต้องการ representation ที่ไม่ผูกกับ target หรือ relation Nonlinear

PREPROCESSING

Center/scale X และ Y, split ตาม unit/time, ตรวจ missing และ collinearity

KEY HYPERPARAMETERS

n_components, scale, max_iter, tol; PLSRegression สำหรับ continuous/multi-output Y

HOW TO CHOOSE DIMENSION / MODEL

เลือก component ด้วย nested CV บน prediction error ไม่ใช้ variance X อย่างเดียว

VALIDATION

ตรวจ held-out error, coefficient/loading stability และ residual structure

COMPUTATIONAL COST

Iterative latent-factor extraction โดยคร่าว O(iterations·n·p·k)

FAILURE MODES

Fit ก่อน split, component ผูกกับ target snapshot และ extrapolation นอก calibration range

TRANSFORMATION EXAMPLEt=Xw โดยเลือก w ให้ cov(t,Y) สูง
USE CASE

Spectroscopy/omics → latent response-aware scores

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLEPLSFit on training data · transform held-out/new rows · persist the fitted artifact
from sklearn.cross_decomposition import PLSRegression
from sklearn.model_selection import train_test_split

Xtr, Xte, ytr, yte = train_test_split(
    X, y, test_size=.2, random_state=42
)
pls = PLSRegression(n_components=6, scale=True, max_iter=1000)
Ztr = pls.fit_transform(Xtr, ytr)[0]
Zte = pls.transform(Xte)
pred = pls.predict(Xte)
print(Ztr.shape, pred.shape)
09

Autoencoder

Unsupervised/Self-supervised · Nonlinear

ข้อมูลมากพอและ manifold ซับซ้อน เช่น image/signal

SUITABLE DATA

ข้อมูลมากพอและ manifold ซับซ้อน เช่น image/signal

WHAT IT LEARNS

Encoder สร้าง bottleneck; Decoder บังคับให้เก็บข้อมูลที่ reconstruct ได้

NOT A GOOD DEFAULT WHEN

ข้อมูลน้อย, reconstruction objective ไม่ตรงงาน หรือ latency จำกัด

PREPROCESSING

Split ก่อน train, scale input, กำหนด reconstruction target และ DataLoader โดยไม่ปะปน test

KEY HYPERPARAMETERS

latent_dim, architecture, activation, loss, learning rate, batch size, epochs, regularization

HOW TO CHOOSE DIMENSION / MODEL

เลือก latent dimension จาก reconstruction + downstream validation + latency

VALIDATION

ติดตาม train/validation loss, latent collapse, nearest neighbors, drift และ downstream score

COMPUTATIONAL COST

ต่อ epoch แปรตาม n × network FLOPs; inference แปรตามจำนวน parameters

FAILURE MODES

จำ identity/noise, reconstruction ดีแต่ไม่เก็บ signal ของ target และ train/test preprocessing ต่างกัน

TRANSFORMATION EXAMPLEx → encoder → z₁…zₖ → decoder → x̂
USE CASE

Image 784 pixels → latent 32

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLEAutoencoderFit on training data · transform held-out/new rows · persist the fitted artifact
import torch
from torch import nn

class Autoencoder(nn.Module):
    def __init__(self, p, k=32):
        super().__init__()
        self.encoder = nn.Sequential(nn.Linear(p, 128), nn.ReLU(), nn.Linear(128, k))
        self.decoder = nn.Sequential(nn.Linear(k, 128), nn.ReLU(), nn.Linear(128, p))
    def forward(self, x):
        z = self.encoder(x)
        return self.decoder(z), z

model = Autoencoder(X_train.shape[1], k=32)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
loss_fn = nn.MSELoss()
for _ in range(50):
    x = torch.as_tensor(X_train, dtype=torch.float32)
    x_hat, _ = model(x); loss = loss_fn(x_hat, x)
    opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
    Z_test = model.encoder(torch.tensor(X_test, dtype=torch.float32)).numpy()
10

UMAP

Unsupervised · Nonlinear manifold

สำรวจ neighborhood structure และ visualization; ใช้ transform ได้เมื่อ pipeline frozen

SUITABLE DATA

สำรวจ neighborhood structure และ visualization; ใช้ transform ได้เมื่อ pipeline frozen

WHAT IT LEARNS

รักษา local neighborhood โดยสร้าง graph และ low-dimensional embedding

NOT A GOOD DEFAULT WHEN

Production Feature ที่ต้อง stable ข้าม retraining หรือ distance ต้องตีความตรง

PREPROCESSING

Split ก่อน fit, scale ตาม metric, ลด noise ด้วย PCA/SVD ได้ และตรวจ disconnected points

KEY HYPERPARAMETERS

n_neighbors, n_components, min_dist, metric, random_state, transform_seed

HOW TO CHOOSE DIMENSION / MODEL

2D เหมาะ visualization; production representation ทดลอง 5–50D ด้วย downstream CV

VALIDATION

ตรวจหลาย seed/parameter, trustworthiness, neighbor preservation และ performance ของ new-row transform

COMPUTATIONAL COST

สร้าง neighbor graph + optimization; ต้นทุนขึ้นกับ n, neighbors, epochs และ approximate NN

FAILURE MODES

อ่าน global distance เกินจริง, retrain แล้วพิกัดหมุน/ย้าย และ distribution ของ new rows เปลี่ยน

TRANSFORMATION EXAMPLE100-D embedding → 2-D/10-D manifold coordinates
USE CASE

Cluster exploration; production requires versioned fitted mapper

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLEUMAPFit on training data · transform held-out/new rows · persist the fitted artifact
# pip install umap-learn
from umap import UMAP
from sklearn.preprocessing import StandardScaler

scale = StandardScaler()
Xs_train = scale.fit_transform(X_train)
Xs_test = scale.transform(X_test)
reducer = UMAP(n_neighbors=15, min_dist=.1, n_components=10,
               metric="euclidean", random_state=42, transform_seed=42)
Z_train = reducer.fit_transform(Xs_train)
Z_test = reducer.transform(Xs_test)
print(Z_train.shape, Z_test.shape)
11

t-SNE

Unsupervised · Nonlinear visualization

Visualization ข้อมูลมิติสูงที่ต้องการเห็น Local Neighborhood ใน 2-D/3-D

SUITABLE DATA

Visualization ข้อมูลมิติสูงที่ต้องการเห็น Local Neighborhood ใน 2-D/3-D

WHAT IT LEARNS

เปลี่ยน pairwise similarities ในมิติสูงให้ใกล้เคียงกันในแผนที่มิติต่ำ โดยเน้นเพื่อนบ้านใกล้

NOT A GOOD DEFAULT WHEN

ใช้พิกัดเป็น Production Feature, ต้อง Transform New Rows อย่างเสถียร, หรือตีความระยะและขนาด Cluster แบบสากล

PREPROCESSING

Scale input, sample อย่างเป็นธรรม, ลดมิติเบื้องต้นด้วย PCA/SVD และกำหนด seed

KEY HYPERPARAMETERS

n_components(2/3), perplexity, early_exaggeration, learning_rate, max_iter, init, metric

HOW TO CHOOSE DIMENSION / MODEL

ไม่เลือก dimension เพื่อ production; เปรียบเทียบหลาย perplexity/seed เพื่อความซื่อสัตย์ของภาพ

VALIDATION

ตรวจ trustworthiness, neighborhood overlap และดูว่ากลุ่มคงอยู่ข้าม parameter หรือไม่

COMPUTATIONAL COST

Pairwise/optimization แพง; implementation ใช้ Barnes–Hut เมื่อเหมาะ แต่ยังหนักกว่า PCA

FAILURE MODES

ตีความช่องว่าง/ขนาด cluster เป็น global geometry และใช้ fit_transform แยก train/test แล้วเทียบพิกัด

TRANSFORMATION EXAMPLE50-D embedding → t-SNE(x,y); compare perplexity 5/30/50
USE CASE

สำรวจ Cluster, outlier และ representation quality—ไม่ใช่ default feature generator

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLEt-SNEFit on training data · transform held-out/new rows · persist the fitted artifact
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, trustworthiness
from sklearn.preprocessing import StandardScaler

Xs = StandardScaler().fit_transform(X_sample)  # exploratory sample only
Xp = PCA(n_components=min(50, Xs.shape[1]), random_state=42).fit_transform(Xs)
tsne = TSNE(n_components=2, perplexity=30, init="pca",
            learning_rate="auto", max_iter=1000, random_state=42)
Z = tsne.fit_transform(Xp)
print(Z.shape, trustworthiness(Xp, Z, n_neighbors=10))
# ใช้เพื่อ visualization; standard TSNE ไม่มี transform(X_new)
12

Logistic score / Log-odds

Supervised · Model-derived

Binary outcome, ต้องการ probability/ranking ที่อธิบาย coefficient ได้

SUITABLE DATA

Binary outcome, ต้องการ probability/ranking ที่อธิบาย coefficient ได้

WHAT IT LEARNS

รวมหลาย input เป็น η=β₀+Σβᵢxᵢ และ p=σ(η)

NOT A GOOD DEFAULT WHEN

Nonlinear interaction สูงโดยไม่เพิ่ม basis หรือ probability ไม่ calibrate

PREPROCESSING

Impute/encode/scale ใน Pipeline, stratified หรือ time split, class/sample weights ตาม policy

KEY HYPERPARAMETERS

penalty, C, l1_ratio, solver, class_weight, max_iter; calibration แยกจาก discrimination

HOW TO CHOOSE DIMENSION / MODEL

เลือก regularization ด้วย nested CV และ metric ตาม decision cost

VALIDATION

ตรวจ ROC/PR, log loss, calibration, subgroup stability, coefficient drift และ decision curve

COMPUTATIONAL COST

Training ขึ้นกับ solver และ sparsity; inference เป็น dot product O(p)

FAILURE MODES

Probability ไม่ calibrate, multicollinearity, missing-not-at-random และ coefficient ถูกอ่านเป็น causal effect

TRANSFORMATION EXAMPLEη=−2+.8x₁−.4x₂; p=1/(1+e⁻η)
USE CASE

Credit/churn/risk score เป็น 1 composite feature

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLELogistic score / Log-oddsFit on training data · transform held-out/new rows · persist the fitted artifact
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

score_model = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("scale", StandardScaler()),
    ("logit", LogisticRegression(C=1.0, penalty="l2", max_iter=2000))
])
score_model.fit(X_train, y_train)
risk_logit = score_model.decision_function(X_test)
risk_probability = score_model.predict_proba(X_test)[:, 1]
print(risk_logit[:3], risk_probability[:3])
13

One-vs-rest Logistic Stack

Supervised · Model-derived

Multiclass หรือหลาย expert signals ที่ downstream model ต้องใช้

SUITABLE DATA

Multiclass หรือหลาย expert signals ที่ downstream model ต้องใช้

WHAT IT LEARNS

สร้าง K probabilities/logits เป็น meta-features

NOT A GOOD DEFAULT WHEN

สร้าง prediction บน training row ด้วย model ที่เห็น row เดิม—เกิด leakage

PREPROCESSING

สร้าง Base Features ด้วย Pipeline และแบ่ง outer holdout; Meta-feature ใน train ต้อง Out-of-fold

KEY HYPERPARAMETERS

K folds, base C/penalty, OvR/multinomial strategy, calibration และ meta-model regularization

HOW TO CHOOSE DIMENSION / MODEL

เลือกจาก nested CV ของทั้ง stack ไม่ tune base แล้วประเมินบนแถวเดิม

VALIDATION

ตรวจ OOF vs holdout gap, class calibration, correlation ระหว่าง logits และ drift

COMPUTATIONAL COST

ประมาณ K เท่าของ base training + final full-data fit

FAILURE MODES

In-sample prediction leakage, fold ไม่ตรง entity/time และ base model version ไม่ครบ

TRANSFORMATION EXAMPLE[logit₁,…,logitₖ] จาก cross-fitted base models
USE CASE

Class probabilities 20 ค่า → meta-model

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLEOne-vs-rest Logistic StackFit on training data · transform held-out/new rows · persist the fitted artifact
import numpy as np
from sklearn.model_selection import StratifiedKFold, cross_val_predict
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier

base = OneVsRestClassifier(LogisticRegression(max_iter=2000))
cv = StratifiedKFold(5, shuffle=True, random_state=42)
oof_prob = cross_val_predict(base, X_train, y_train, cv=cv,
                             method="predict_proba")
base.fit(X_train, y_train)                 # model used for future rows
test_prob = base.predict_proba(X_test)
meta = LogisticRegression(max_iter=2000).fit(oof_prob, y_train)
pred = meta.predict_proba(test_prob)
print(oof_prob.shape, pred.shape)
14

Regularized Logistic Selection

Supervised · Sparse linear

Feature จำนวนมากและต้องการ sparse coefficients

SUITABLE DATA

Feature จำนวนมากและต้องการ sparse coefficients

WHAT IT LEARNS

L1 ทำ coefficient บางตัวเป็นศูนย์; Elastic Net จัดการ correlated groups

NOT A GOOD DEFAULT WHEN

ตีความ zero ว่าไม่มีผลเชิงสาเหตุ หรือเลือก Feature จาก full data ก่อน CV

PREPROCESSING

Impute/encode/scale; group related dummy columns; selection ต้องอยู่ภายใน CV Pipeline

KEY HYPERPARAMETERS

penalty l1/elasticnet, C, l1_ratio, solver=saga, class_weight, threshold ของ nonzero

HOW TO CHOOSE DIMENSION / MODEL

เลือก C/l1_ratio ด้วย nested CV และตรวจ selection stability หลาย bootstrap/fold

VALIDATION

รายงาน performance + จำนวน nonzero + selection frequency ไม่รายงานรายชื่อครั้งเดียว

COMPUTATIONAL COST

Sparse solver ได้ประโยชน์จาก sparse X; training iterative ส่วน inference O(nonzero β)

FAILURE MODES

เลือกจาก full data, correlated features ผลัดกันถูกเลือก และ zero coefficient ไม่เท่ากับไม่มีผล

TRANSFORMATION EXAMPLEmin log-loss + λ₁|β|₁ + λ₂|β|²
USE CASE

50,000 variables → nonzero shortlist

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLERegularized Logistic SelectionFit on training data · transform held-out/new rows · persist the fitted artifact
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV

pipe = Pipeline([
    ("scale", StandardScaler()),
    ("select_model", LogisticRegression(
        penalty="elasticnet", solver="saga", max_iter=5000
    ))
])
search = GridSearchCV(pipe, {
    "select_model__C": [.01, .1, 1],
    "select_model__l1_ratio": [.2, .5, .8]
}, cv=5, scoring="neg_log_loss")
search.fit(X_train, y_train)
coef = search.best_estimator_[-1].coef_.ravel()
selected = feature_names[coef != 0]
15

Entity Embedding

Supervised · Learned lookup

Categorical cardinality สูงและมีข้อมูลต่อ category มากพอ

SUITABLE DATA

Categorical cardinality สูงและมีข้อมูลต่อ category มากพอ

WHAT IT LEARNS

เรียน vector ต่อ entity ร่วมกับ objective ปลายทาง

NOT A GOOD DEFAULT WHEN

Cold-start, rare categories, identity drift และ privacy

PREPROCESSING

Map category จาก train เท่านั้น, reserve unknown ID, กำหนด min frequency และ monitor cold start

KEY HYPERPARAMETERS

embedding_dim, regularization, objective, negative sampling, optimizer, epochs

HOW TO CHOOSE DIMENSION / MODEL

เริ่ม k≈min(50, round(cardinality**.25×4)) แล้วเลือกด้วย validation/latency

VALIDATION

ตรวจ new/rare entity, nearest neighbors, subgroup drift และ downstream holdout

COMPUTATIONAL COST

Lookup O(1); training cost อยู่ที่ objective network และจำนวน events

FAILURE MODES

ID เป็น proxy sensitive attribute, rare vector overfit, entity reindex และ unknown policy ไม่ตรงกัน

TRANSFORMATION EXAMPLEproduct_id → e∈R¹⁶
USE CASE

100k products → 16 learned features

OUTPUT CONTRACTentity_id · as_of · fitted_on · input_schema · transform_version · component_id · value
PYTHON EXAMPLEEntity EmbeddingFit on training data · transform held-out/new rows · persist the fitted artifact
import torch
from torch import nn

num_entities, embedding_dim = 100_001, 16  # ID 0 = unknown
embedding = nn.Embedding(num_entities, embedding_dim, padding_idx=0)
entity_id = torch.tensor([12, 980, 0], dtype=torch.long)
Z = embedding(entity_id)                   # shape: [3, 16]

# ใช้ Z ร่วมกับ numeric features แล้ว train ด้วย task loss
numeric = torch.randn(3, 8)
model_input = torch.cat([Z, numeric], dim=1)
print(model_input.shape)
# ต้อง save ID mapping + weights + preprocessing version

03 · WORKED EXAMPLE: PCA

จาก Sensor ที่ซ้ำกัน ไปสู่แกนร่วม

STANDARDIZED INPUT
rowtemppressurevibration
A−1.0−0.90.2
B0.00.1−0.1
C1.00.80.0
×
LOADING VECTORPC1 = .72·temp
+ .69·pressure
+ .08·vibration
=
NEW FEATUREA: −1.325
B: 0.061
C: 1.272
Interpret

PC1 ในตัวอย่างนี้แทนสภาวะร่วมของ Temperature/Pressure ไม่ได้มีชื่อ Domain โดยอัตโนมัติ

Fit correctly

Mean, SD และ Loading ต้อง Fit จาก Training Data แล้ว Freeze ไปใช้ Validation/Test

Choose k

ดู Explained Variance ร่วมกับ Downstream Performance ไม่ใช้ Threshold เดียวทุกงาน

04 · WORKED EXAMPLE: LOGISTIC SCORE AS A FEATURE

จากหลาย Evidence สู่ Log-odds ที่ส่งต่อได้

INPUTlate_payments = 2
utilization = .70
account_age = 4
LINEAR SCOREη = −2 + .8(2) + 1.5(.70) − .1(4)
η = 0.25
PROBABILITYp = σ(.25) = 0.562
DOWNSTREAM FEATURESrisk_logit = .25
risk_probability = .562
ใช้ Probability เมื่อ

ต้องการค่าช่วง 0–1 และ Model ผ่าน Calibration ตาม Population เป้าหมายแล้ว

ใช้ Log-odds เมื่อ

Downstream model ต้องการค่าที่ไม่อิ่มตัวใกล้ 0/1 และอ่าน Evidence แบบ Additive

เก็บ Raw Features เมื่อ

Model ถัดไปอาจพบ Interaction/Nonlinearity ที่ Logistic Base Model สรุปทิ้งไป

05 · THE LEAKAGE TRAP

Supervised Representation ต้องสร้างแบบ Out-of-fold

WRONGfit logistic on all training rows
predict the same rows
use prediction as feature

แต่ละแถวมีอิทธิพลต่อ Model ที่สร้าง Feature ของตนเอง ค่า Training จึงดีเกินจริง โดยเฉพาะเมื่อ Model/Category มีความยืดหยุ่นสูง

CROSS-FITTEDsplit K folds
fit on K−1 folds
predict held-out fold
concatenate OOF predictions

ทุก Training Row ได้ Model-derived Feature จาก Model ที่ไม่เคยเห็น Label ของแถวนั้น Final Model จึงประเมินอย่างสมเหตุผลกว่า

Fold 1 predicts 2Fold 2 predicts 3Fold 3 predicts 1→ OOF logit feature

06 · TECHNIQUE SELECTOR

ทดลองเลือกตามโครงสร้างข้อมูล

07 · COMPARISON MATRIX

Representation ที่ดีต้องเหมาะทั้งข้อมูลและการใช้งาน

Method familyUses Y?Nonlinear?Sparse friendlyTransform new rowsInterpretabilityMain risk
PCANoNoไม่เหมาะกับ centered sparseYesMediumscale / drift
SVD/NMFNoNoYesYesMediumcorpus/version drift
AutoencoderUsually noYesdependsYesLowobjective mismatch
UMAPUsually noYespossibleWith fitted mapperLowunstable geometry
LDA/PLSYesNodependsYesMediumtarget leakage
Logistic scoreYesLinear unless basis addedYesYesHighcalibration/leakage
Entity embeddingOftenYeslookupKnown entitiesLowcold start/drift

DOWNLOADABLE STUDENT LAB · JUPYTER NOTEBOOK

รัน ทดลอง เปลี่ยน Parameter แล้วอธิบายผลด้วยตนเอง

Notebook แบบ self-contained จำนวน 45 Cells ครอบคลุม 15 เทคนิค ใช้ Dataset ใน scikit-learn และ Synthetic Data เป็นหลัก พร้อม Optional UMAP/PyTorch, Leakage-safe Workflow, Comparison Table และแบบฝึกหัดท้ายบท

  • 22 Python code cells
  • 23 explanations and exercises
  • ไม่ต้องดาวน์โหลด Dataset เพิ่มสำหรับบทหลัก
  • เปิดด้วย JupyterLab, VS Code หรือ Google Colab ได้
Download Python Notebook .ipynb · student lab

FINAL PRINCIPLE

Reduce dimensions, not meaning.

Latent Component, Embedding หรือ Logistic Score เป็น Feature ใหม่ที่เรียนจากข้อมูล มันอาจลด Noise และต้นทุนได้มาก แต่ต้อง Version ตัว Transformer, Fit เฉพาะ Training Population, ป้องกัน Leakage และตรวจว่าข้อมูลสำคัญไม่ได้ถูกบีบหายไป การใช้ Representation ร่วมกับ Feature Domain ที่จำเป็นมักเป็น Baseline ที่รอบคอบกว่าการแทนทุกอย่างทันที