เก็บข้อมูลส่วนใหญ่ด้วยมิติน้อยลง
PCA, SVD, Autoencoder เหมาะเมื่อ Memory, Noise, Multicollinearity หรือ Training Cost เป็นปัญหา
DIMENSION REDUCTION · PROJECTION · MODEL-DERIVED FEATURES
Dimensionality Reduction เปลี่ยน Feature จำนวนมากเป็น Representation ขนาดเล็ก ส่วน Logistic Regression สามารถรวม Evidence เป็น Score, Probability หรือ Log-odds ให้ Model ถัดไปใช้ แต่สิ่งเหล่านี้ไม่ได้ทำให้ Feature Engineering หายไป—เราย้ายงานไปอยู่ที่การเลือก Input, Objective, Fitting Population, Leakage Control และ Versioning
x₁ … xₚข้อมูลที่วัดหรือสร้างจาก Domain
Tθ(X)PCA, SVD, Encoder, Logistic Model
z₁ … zₖComponent, Embedding, Score, Logit
g(Z, X*)มักใช้ Z ร่วมกับ Feature สำคัญเดิม
01 · THREE DIFFERENT INTENTIONS
PCA, SVD, Autoencoder เหมาะเมื่อ Memory, Noise, Multicollinearity หรือ Training Cost เป็นปัญหา
LDA, PLS และ Supervised Embedding ใช้ Y จึงต้อง Fit เฉพาะ Training Fold
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
ข้อมูลตัวเลขต่อเนื่องที่ Standardize แล้ว และมี Correlation สูง
ข้อมูลตัวเลขต่อเนื่องที่ Standardize แล้ว และมี Correlation สูง
สร้างแกน Orthogonal ที่เก็บ Variance มากที่สุด
ข้อมูล Nonlinear, Sparse count ที่ Scale ต่างมาก หรือ Component ต้องตีความตรงๆ
Impute missing, split data, StandardScaler fit เฉพาะ train; พิจารณา RobustScaler เมื่อ outlier สูง
n_components, svd_solver, whiten; เริ่มจาก explained variance และ downstream CV
เลือก k จาก cumulative variance + validation score + latency ไม่ใช้ 95% เป็นกฎสากล
ตรวจ reconstruction error, loading stability, downstream score และ drift ของ component score
Full SVD โดยคร่าว O(min(np²,n²p)); randomized solver เหมาะเมื่อ k≪min(n,p)
Scale dominance, outlier, component sign flip และ covariance เปลี่ยนตามเวลา
z₁=.71x₁+.69x₂+.12x₃Sensor 200 ตัว → 15 components
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valuefrom 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())TF–IDF, user-item หรือ sparse high-dimensional matrix
TF–IDF, user-item หรือ sparse high-dimensional matrix
ลดมิติโดยไม่ต้อง Center sparse matrix; เก็บ latent directions
ความหมาย Component อาจเปลี่ยนเมื่อ Corpus เปลี่ยน
สร้าง sparse count/TF–IDF; ไม่ Center matrix; freeze tokenizer และ vocabulary/corpus policy
n_components, n_iter, algorithm, random_state; ค่า k มักมากกว่า visualization dimension
เลือก k จาก retrieval/classification CV, reconstruction proxy และ memory budget
ตรวจ singular-value spectrum, topic coherence แบบระวัง และ performance บน future corpus
Randomized SVD โดยประมาณ O(nnz(X)·k·iterations)
Corpus drift, vocabulary drift, sign ambiguity และ latent axis ไม่ใช่ topic บริสุทธิ์
10,000 TF–IDF terms → 200 latent dimensionsDocument retrieval / topic-like representation
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valuefrom 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())ข้อมูล Non-negative เช่น count, intensity, purchase
ข้อมูล Non-negative เช่น count, intensity, purchase
W,H ≥ 0 ทำให้ Component มักเป็นส่วนประกอบที่อ่านง่ายกว่า
ข้อมูลติดลบหรือ relation ที่ต้องหักล้างกัน
Input ต้อง non-negative; เลือก count/TF–IDF/intensity และจัดการ zero/missing อย่างชัดเจน
n_components, init, solver, beta_loss, alpha_W/H, l1_ratio, max_iter
เลือก k จาก held-out reconstruction, stability, interpretability และ downstream task
ตรวจ convergence, component stability หลาย seed และ feature loading ที่มีเหตุผล
ขึ้นกับ solver; โดยทั่วไป iterative และแปรตาม nnz(X)·k·iterations
Local minima, scale ambiguity, component ซ้ำ และค่าติดลบที่ถูก clip อย่างไม่เหมาะสม
purchase matrix ≈ customer_topics × category_loadingsสินค้า 5,000 SKU → 30 shopping profiles
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valuefrom 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_)สัญญาณผสมที่สมมติ latent sources เป็นอิสระเชิงสถิติ
สัญญาณผสมที่สมมติ latent sources เป็นอิสระเชิงสถิติ
แยก Independent Components มากกว่าแกน Variance
Noise สูง จำนวน source ไม่ชัด หรือ assumption independence ไม่เหมาะ
Center/whiten data, ตรวจ rank และเลือก signal channels/window ที่สัมพันธ์กัน
n_components, algorithm, whiten, fun, max_iter, tol, random_state
จำนวน component อิงจำนวน source ที่สมเหตุผล + stability ไม่ใช่ variance อย่างเดียว
ตรวจ convergence, independence proxy, source reproducibility และ domain plausibility
Iterative matrix operations; โดยคร่าว O(iterations·n·p·k)
Non-convergence, permutation/sign ambiguity และ assumption independent non-Gaussian sources ไม่จริง
mixed sensors X = A·S → estimate SEEG/audio/machine vibration source separation
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valuefrom 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_)ข้อมูลมิติสูงมาก ต้องการเร็วและยอมเสียระยะเล็กน้อย
ข้อมูลมิติสูงมาก ต้องการเร็วและยอมเสียระยะเล็กน้อย
คูณเมทริกซ์สุ่มเพื่อประมาณ pairwise distance
ต้องการ Component ที่มีความหมายหรือ reproducibility โดยไม่เก็บ seed
Impute/scale ตาม distance metric; กำหนด seed และเก็บ projection matrix
n_components หรือ eps, density, random_state; Gaussian/Sparse projection
ใช้ Johnson–Lindenstrauss bound เป็นเพดานเริ่มต้น แล้ว validate downstream
ตรวจ distortion ของ pairwise distance จาก sample และ performance ของงานปลายทาง
Dense O(npk); sparse projection ลดต้นทุนตาม density
Projection seed หาย, k ต่ำเกินไป และ Feature scale ไม่สมเหตุผล
z = X·R / √k1M sparse dimensions → 1,000 dimensions
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valuefrom 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)Token/category จำนวนมากหรือไม่รู้ Vocabulary ล่วงหน้า
Token/category จำนวนมากหรือไม่รู้ Vocabulary ล่วงหน้า
Hash key ลง fixed bins; memory คงที่และใช้ streaming ได้
Collision สำคัญมากหรือต้องย้อนอ่านชื่อ Feature ทุกตัว
กำหนด key normalization, namespace, signed hashing และ collision policy
n_features, input_type, alternate_sign; ขนาด bin เป็น power-of-two เพื่อปฏิบัติการง่าย
เพิ่ม bins จน collision/validation metric อยู่ในขอบเขตและ memory ยังรับได้
ติดตาม occupancy, collision estimate, unseen key และ downstream calibration
O(number of nonzero tokens); memory ต่อ row คงที่ตาม nonzero
Hash configuration เปลี่ยน, namespace ชนกัน และ audit กลับชื่อ Feature ไม่ได้
hash(token) mod 2¹⁸URL, ad IDs, event keys → 262,144 bins
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valuefrom 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)Classification ที่ class separation สำคัญและ covariance assumptions พอใช้
Classification ที่ class separation สำคัญและ covariance assumptions พอใช้
หาแกนที่เพิ่ม Between-class / Within-class separation
Nonlinear boundary, class distribution ซับซ้อน หรือ covariance singular มาก
Split ก่อน fit, scale หากจำเป็น, ตรวจ class imbalance และ covariance rank
solver, shrinkage, priors, n_components ≤ classes−1
เลือก component จาก class count และ CV; shrinkage สำคัญเมื่อ p ใกล้/มากกว่า n
ใช้ stratified CV, confusion/calibration และตรวจ axis stability
ขึ้นกับ solver; covariance/eigen decomposition มักมีต้นทุนตาม p²/p³
Target leakage, singular covariance, Gaussian/shared-covariance assumptions และ class drift
z = wᵀx; สูงสุดไม่เกิน C−1 axes20 classes → ≤19 supervised components
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valuefrom 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))Predictors correlated จำนวนมาก และต้องการ Component ที่สัมพันธ์กับ Y
Predictors correlated จำนวนมาก และต้องการ Component ที่สัมพันธ์กับ Y
สร้าง latent scores โดยใช้ covariance ระหว่าง X และ Y
ต้องการ representation ที่ไม่ผูกกับ target หรือ relation Nonlinear
Center/scale X และ Y, split ตาม unit/time, ตรวจ missing และ collinearity
n_components, scale, max_iter, tol; PLSRegression สำหรับ continuous/multi-output Y
เลือก component ด้วย nested CV บน prediction error ไม่ใช้ variance X อย่างเดียว
ตรวจ held-out error, coefficient/loading stability และ residual structure
Iterative latent-factor extraction โดยคร่าว O(iterations·n·p·k)
Fit ก่อน split, component ผูกกับ target snapshot และ extrapolation นอก calibration range
t=Xw โดยเลือก w ให้ cov(t,Y) สูงSpectroscopy/omics → latent response-aware scores
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valuefrom 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)ข้อมูลมากพอและ manifold ซับซ้อน เช่น image/signal
ข้อมูลมากพอและ manifold ซับซ้อน เช่น image/signal
Encoder สร้าง bottleneck; Decoder บังคับให้เก็บข้อมูลที่ reconstruct ได้
ข้อมูลน้อย, reconstruction objective ไม่ตรงงาน หรือ latency จำกัด
Split ก่อน train, scale input, กำหนด reconstruction target และ DataLoader โดยไม่ปะปน test
latent_dim, architecture, activation, loss, learning rate, batch size, epochs, regularization
เลือก latent dimension จาก reconstruction + downstream validation + latency
ติดตาม train/validation loss, latent collapse, nearest neighbors, drift และ downstream score
ต่อ epoch แปรตาม n × network FLOPs; inference แปรตามจำนวน parameters
จำ identity/noise, reconstruction ดีแต่ไม่เก็บ signal ของ target และ train/test preprocessing ต่างกัน
x → encoder → z₁…zₖ → decoder → x̂Image 784 pixels → latent 32
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valueimport 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()สำรวจ neighborhood structure และ visualization; ใช้ transform ได้เมื่อ pipeline frozen
สำรวจ neighborhood structure และ visualization; ใช้ transform ได้เมื่อ pipeline frozen
รักษา local neighborhood โดยสร้าง graph และ low-dimensional embedding
Production Feature ที่ต้อง stable ข้าม retraining หรือ distance ต้องตีความตรง
Split ก่อน fit, scale ตาม metric, ลด noise ด้วย PCA/SVD ได้ และตรวจ disconnected points
n_neighbors, n_components, min_dist, metric, random_state, transform_seed
2D เหมาะ visualization; production representation ทดลอง 5–50D ด้วย downstream CV
ตรวจหลาย seed/parameter, trustworthiness, neighbor preservation และ performance ของ new-row transform
สร้าง neighbor graph + optimization; ต้นทุนขึ้นกับ n, neighbors, epochs และ approximate NN
อ่าน global distance เกินจริง, retrain แล้วพิกัดหมุน/ย้าย และ distribution ของ new rows เปลี่ยน
100-D embedding → 2-D/10-D manifold coordinatesCluster exploration; production requires versioned fitted mapper
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · value# 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)Visualization ข้อมูลมิติสูงที่ต้องการเห็น Local Neighborhood ใน 2-D/3-D
Visualization ข้อมูลมิติสูงที่ต้องการเห็น Local Neighborhood ใน 2-D/3-D
เปลี่ยน pairwise similarities ในมิติสูงให้ใกล้เคียงกันในแผนที่มิติต่ำ โดยเน้นเพื่อนบ้านใกล้
ใช้พิกัดเป็น Production Feature, ต้อง Transform New Rows อย่างเสถียร, หรือตีความระยะและขนาด Cluster แบบสากล
Scale input, sample อย่างเป็นธรรม, ลดมิติเบื้องต้นด้วย PCA/SVD และกำหนด seed
n_components(2/3), perplexity, early_exaggeration, learning_rate, max_iter, init, metric
ไม่เลือก dimension เพื่อ production; เปรียบเทียบหลาย perplexity/seed เพื่อความซื่อสัตย์ของภาพ
ตรวจ trustworthiness, neighborhood overlap และดูว่ากลุ่มคงอยู่ข้าม parameter หรือไม่
Pairwise/optimization แพง; implementation ใช้ Barnes–Hut เมื่อเหมาะ แต่ยังหนักกว่า PCA
ตีความช่องว่าง/ขนาด cluster เป็น global geometry และใช้ fit_transform แยก train/test แล้วเทียบพิกัด
50-D embedding → t-SNE(x,y); compare perplexity 5/30/50สำรวจ Cluster, outlier และ representation quality—ไม่ใช่ default feature generator
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valuefrom 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)Binary outcome, ต้องการ probability/ranking ที่อธิบาย coefficient ได้
Binary outcome, ต้องการ probability/ranking ที่อธิบาย coefficient ได้
รวมหลาย input เป็น η=β₀+Σβᵢxᵢ และ p=σ(η)
Nonlinear interaction สูงโดยไม่เพิ่ม basis หรือ probability ไม่ calibrate
Impute/encode/scale ใน Pipeline, stratified หรือ time split, class/sample weights ตาม policy
penalty, C, l1_ratio, solver, class_weight, max_iter; calibration แยกจาก discrimination
เลือก regularization ด้วย nested CV และ metric ตาม decision cost
ตรวจ ROC/PR, log loss, calibration, subgroup stability, coefficient drift และ decision curve
Training ขึ้นกับ solver และ sparsity; inference เป็น dot product O(p)
Probability ไม่ calibrate, multicollinearity, missing-not-at-random และ coefficient ถูกอ่านเป็น causal effect
η=−2+.8x₁−.4x₂; p=1/(1+e⁻η)Credit/churn/risk score เป็น 1 composite feature
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valuefrom 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])Multiclass หรือหลาย expert signals ที่ downstream model ต้องใช้
Multiclass หรือหลาย expert signals ที่ downstream model ต้องใช้
สร้าง K probabilities/logits เป็น meta-features
สร้าง prediction บน training row ด้วย model ที่เห็น row เดิม—เกิด leakage
สร้าง Base Features ด้วย Pipeline และแบ่ง outer holdout; Meta-feature ใน train ต้อง Out-of-fold
K folds, base C/penalty, OvR/multinomial strategy, calibration และ meta-model regularization
เลือกจาก nested CV ของทั้ง stack ไม่ tune base แล้วประเมินบนแถวเดิม
ตรวจ OOF vs holdout gap, class calibration, correlation ระหว่าง logits และ drift
ประมาณ K เท่าของ base training + final full-data fit
In-sample prediction leakage, fold ไม่ตรง entity/time และ base model version ไม่ครบ
[logit₁,…,logitₖ] จาก cross-fitted base modelsClass probabilities 20 ค่า → meta-model
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valueimport 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)Feature จำนวนมากและต้องการ sparse coefficients
Feature จำนวนมากและต้องการ sparse coefficients
L1 ทำ coefficient บางตัวเป็นศูนย์; Elastic Net จัดการ correlated groups
ตีความ zero ว่าไม่มีผลเชิงสาเหตุ หรือเลือก Feature จาก full data ก่อน CV
Impute/encode/scale; group related dummy columns; selection ต้องอยู่ภายใน CV Pipeline
penalty l1/elasticnet, C, l1_ratio, solver=saga, class_weight, threshold ของ nonzero
เลือก C/l1_ratio ด้วย nested CV และตรวจ selection stability หลาย bootstrap/fold
รายงาน performance + จำนวน nonzero + selection frequency ไม่รายงานรายชื่อครั้งเดียว
Sparse solver ได้ประโยชน์จาก sparse X; training iterative ส่วน inference O(nonzero β)
เลือกจาก full data, correlated features ผลัดกันถูกเลือก และ zero coefficient ไม่เท่ากับไม่มีผล
min log-loss + λ₁|β|₁ + λ₂|β|²50,000 variables → nonzero shortlist
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valuefrom 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]Categorical cardinality สูงและมีข้อมูลต่อ category มากพอ
Categorical cardinality สูงและมีข้อมูลต่อ category มากพอ
เรียน vector ต่อ entity ร่วมกับ objective ปลายทาง
Cold-start, rare categories, identity drift และ privacy
Map category จาก train เท่านั้น, reserve unknown ID, กำหนด min frequency และ monitor cold start
embedding_dim, regularization, objective, negative sampling, optimizer, epochs
เริ่ม k≈min(50, round(cardinality**.25×4)) แล้วเลือกด้วย validation/latency
ตรวจ new/rare entity, nearest neighbors, subgroup drift และ downstream holdout
Lookup O(1); training cost อยู่ที่ objective network และจำนวน events
ID เป็น proxy sensitive attribute, rare vector overfit, entity reindex และ unknown policy ไม่ตรงกัน
product_id → e∈R¹⁶100k products → 16 learned features
entity_id · as_of · fitted_on · input_schema · transform_version · component_id · valueimport 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 version03 · WORKED EXAMPLE: PCA
| row | temp | pressure | vibration |
|---|---|---|---|
| A | −1.0 | −0.9 | 0.2 |
| B | 0.0 | 0.1 | −0.1 |
| C | 1.0 | 0.8 | 0.0 |
PC1 = .72·temp
+ .69·pressure
+ .08·vibrationA: −1.325
B: 0.061
C: 1.272PC1 ในตัวอย่างนี้แทนสภาวะร่วมของ Temperature/Pressure ไม่ได้มีชื่อ Domain โดยอัตโนมัติ
Mean, SD และ Loading ต้อง Fit จาก Training Data แล้ว Freeze ไปใช้ Validation/Test
ดู Explained Variance ร่วมกับ Downstream Performance ไม่ใช้ Threshold เดียวทุกงาน
04 · WORKED EXAMPLE: LOGISTIC SCORE AS A FEATURE
late_payments = 2
utilization = .70
account_age = 4η = −2 + .8(2) + 1.5(.70) − .1(4)
η = 0.25p = σ(.25) = 0.562risk_logit = .25
risk_probability = .562ต้องการค่าช่วง 0–1 และ Model ผ่าน Calibration ตาม Population เป้าหมายแล้ว
Downstream model ต้องการค่าที่ไม่อิ่มตัวใกล้ 0/1 และอ่าน Evidence แบบ Additive
Model ถัดไปอาจพบ Interaction/Nonlinearity ที่ Logistic Base Model สรุปทิ้งไป
05 · THE LEAKAGE TRAP
fit logistic on all training rows
predict the same rows
use prediction as featureแต่ละแถวมีอิทธิพลต่อ Model ที่สร้าง Feature ของตนเอง ค่า Training จึงดีเกินจริง โดยเฉพาะเมื่อ Model/Category มีความยืดหยุ่นสูง
split K folds
fit on K−1 folds
predict held-out fold
concatenate OOF predictionsทุก Training Row ได้ Model-derived Feature จาก Model ที่ไม่เคยเห็น Label ของแถวนั้น Final Model จึงประเมินอย่างสมเหตุผลกว่า
06 · TECHNIQUE SELECTOR
07 · COMPARISON MATRIX
| Method family | Uses Y? | Nonlinear? | Sparse friendly | Transform new rows | Interpretability | Main risk |
|---|---|---|---|---|---|---|
| PCA | No | No | ไม่เหมาะกับ centered sparse | Yes | Medium | scale / drift |
| SVD/NMF | No | No | Yes | Yes | Medium | corpus/version drift |
| Autoencoder | Usually no | Yes | depends | Yes | Low | objective mismatch |
| UMAP | Usually no | Yes | possible | With fitted mapper | Low | unstable geometry |
| LDA/PLS | Yes | No | depends | Yes | Medium | target leakage |
| Logistic score | Yes | Linear unless basis added | Yes | Yes | High | calibration/leakage |
| Entity embedding | Often | Yes | lookup | Known entities | Low | cold start/drift |
DOWNLOADABLE STUDENT LAB · JUPYTER NOTEBOOK
Notebook แบบ self-contained จำนวน 45 Cells ครอบคลุม 15 เทคนิค ใช้ Dataset ใน scikit-learn และ Synthetic Data เป็นหลัก พร้อม Optional UMAP/PyTorch, Leakage-safe Workflow, Comparison Table และแบบฝึกหัดท้ายบท
FINAL PRINCIPLE
Latent Component, Embedding หรือ Logistic Score เป็น Feature ใหม่ที่เรียนจากข้อมูล มันอาจลด Noise และต้นทุนได้มาก แต่ต้อง Version ตัว Transformer, Fit เฉพาะ Training Population, ป้องกัน Leakage และตรวจว่าข้อมูลสำคัญไม่ได้ถูกบีบหายไป การใช้ Representation ร่วมกับ Feature Domain ที่จำเป็นมักเป็น Baseline ที่รอบคอบกว่าการแทนทุกอย่างทันที