Skip to content

Machine Learning チートシート

機械学習の概念、アルゴリズム、Python 実装。

01

はじめに

機械学習とは

機械学習は、手書きのルールに従うのではなくデータから汎化するシステムを構築します。3 つのパラダイム(教師あり、教師なし、強化学習)が、ほとんどの現実の問題をカバーします。構造化されたワークフローに従うこと — 特にきれいなテストセットを手元に確保すること — が、評価への過剰適合という最大の罪を防ぎます。

machine-learning
# Machine Learning: systems that learn patterns from data
# instead of being explicitly programmed.

# Three main paradigms:
# - Supervised:    learn f: X -> y from labeled (X, y) pairs
# - Unsupervised:  find structure in unlabeled X
# - Reinforcement: learn actions that maximize reward via trial-and-error

# Typical workflow:
# 1. Define problem & collect data
# 2. Preprocess & feature engineering
# 3. Split train / validation / test
# 4. Train model, tune hyperparameters
# 5. Evaluate on test set
# 6. Deploy & monitor

コアライブラリ

scikit-learn が表形式/古典 ML の主力です — すべてのアルゴリズムで一貫した fit/predict/transform API を持ちます。データの加工は NumPy と Pandas が、可視化は Matplotlib/Seaborn が扱います。深層学習には、PyTorch(研究向け)か TensorFlow/Keras(本番向け)を選びましょう — どちらも同じ領域をカバーします。

machine-learning
# The standard ML stack in Python
import numpy as np          # numerical arrays
import pandas as pd         # tabular data
import matplotlib.pyplot as plt  # plotting
import seaborn as sns       # statistical plots

# scikit-learn: classical ML (trees, SVM, linear models, preprocessing)
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# Deep learning (pick one):
import torch                # PyTorch
# import tensorflow as tf   # TensorFlow/Keras

# Install:
# pip install numpy pandas matplotlib seaborn scikit-learn torch

Train / Validation / Test の分割

最終評価までテストセットに触れてはいけません — チューニングに使うと情報が漏れ、報告する指標が膨らみます。クラスのバランスを保つ stratify=y は、不均衡な分類には決定的に重要です。分割を再現可能にするのが random_state です。小さな dataset では、固定の検証セットの代わりに k 分割 CV を使いましょう。

machine-learning
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y,
    test_size=0.2,      # 20% held out for test
    random_state=42,    # reproducibility
    stratify=y,         # keep class proportions (classification only)
)

# For a third validation set:
X_train, X_temp, y_train, y_temp = train_test_split(
    X, y, test_size=0.4, stratify=y, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(
    X_temp, y_temp, test_size=0.5, stratify=y_temp, random_state=42)
# Now: 60% train, 20% val, 20% test

最初のモデル(Iris)

Iris dataset が ML の「Hello World」です — 花のサンプル 150 個、特徴 4 個、クラス 3 個。このスニペットが定番の sklearn パターンを示します:データのロード、分割、モデルのインスタンス化、fit、predict、評価。classification_report がクラスごとの precision/recall/F1 を与え、不均衡な問題では精度だけよりはるかに情報豊かです。

machine-learning
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report

iris = load_iris()
X, y = iris.data, iris.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)

model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

print("Accuracy:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred, target_names=iris.target_names))

再現性

重みの初期化とシャッフルが再現可能になるよう、numpy、random、DL フレームワークのシードを設定しましょう。すべての確率的な sklearn 推定器に random_state を渡しましょう。完全な決定性(特に GPU 上)には、決定的なアルゴリズムと env フラグも必要です — 「一致するはず」なのに一致しない結果のデバッグに有用です。

machine-learning
import numpy as np
import random
import torch

SEED = 42
np.random.seed(SEED)
random.seed(SEED)
torch.manual_seed(SEED)
if torch.cuda.is_available():
    torch.cuda.manual_seed_all(SEED)

# For sklearn, pass random_state to each estimator:
# RandomForestClassifier(random_state=SEED)

# Force deterministic operations (slower but fully reproducible):
torch.use_deterministic_algorithms(True)

# Optional: pin GPU non-determinism
import os
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
02

データの前処理

欠損値の処理

全 dataset で imputer を fit すると、テストの統計が学習へ漏れます — 必ず train のみで fit しましょう。平均より中央値が外れ値に強いです。カテゴリ特徴には 'most_frequent' か 'constant' を使いましょう。KNN 補完は多変量の構造を捉えられますが、大きなデータでは高コストです。欠損自体が情報を運ぶことも検討しましょう('is_missing' のインジケータを追加)。

machine-learning
import pandas as pd
from sklearn.impute import SimpleImputer, KNNImputer

df = pd.DataFrame({"age": [25, np.nan, 35, 45],
                   "income": [50000, 60000, np.nan, 80000]})

# Drop rows with any missing values (use sparingly)
df_drop = df.dropna()

# Mean/median/mode imputation
imp = SimpleImputer(strategy="median")  # 'mean','most_frequent','constant'
df_imputed = pd.DataFrame(imp.fit_transform(df), columns=df.columns)

# KNN imputer (uses similar samples)
knn_imp = KNNImputer(n_neighbors=3)
df_knn = pd.DataFrame(knn_imp.fit_transform(df), columns=df.columns)

# Always fit imputers on TRAINING data only, then transform test
imp.fit(X_train)
X_train_imp = imp.transform(X_train)
X_test_imp  = imp.transform(X_test)   # uses train medians

スケーリングと正規化

多くのアルゴリズム(SVM、KNN、ロジスティック回帰、ニューラルネット、PCA)はスケールに敏感です — ツリーモデルは一般にそうではありません。デフォルトは StandardScaler で、有界の範囲が必要なとき(画像など)は MinMaxScaler、外れ値が StandardScaler を歪めるなら RobustScaler です。ALWAYS で、train で fit し、同じ fit 済みの scaler で test を transform しましょう — test で fit_transform は決してしないこと。

machine-learning
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler

# Standardization: mean 0, std 1 (most common)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled  = scaler.transform(X_test)   # use train mean/std!

# Min-max: scale to [0, 1]
minmax = MinMaxScaler()
X_mm = minmax.fit_transform(X_train)

# Robust to outliers: uses median & IQR
robust = RobustScaler()
X_robust = robust.fit_transform(X_train)

カテゴリ変数のエンコード

LabelEncoder はターゲット用で、OneHotEncoder は名義特徴用です(固有の順序がない — one-hot により、red < green < blue を含意するのを避けます)。順序カテゴリ(サイズなど)には OrdinalEncoder です。テスト時に未知のカテゴリでエラーになるのを防ぐのが handle_unknown='ignore' です。高基数のカテゴリ(郵便番号など)には、次元の爆発を避けるため、ターゲット/カウントエンコードの方が向いています。

machine-learning
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, OrdinalEncoder

# Label encode TARGET (classification): strings -> integers
le = LabelEncoder()
y = le.fit_transform(["cat", "dog", "cat", "bird"])  # [0, 1, 0, 2]
le.inverse_transform([0, 1, 2])                       # back to strings

# One-hot encode FEATURES (nominal, no order)
ohe = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
X_ohe = ohe.fit_transform(df[["color"]])  # red/green/blue -> 3 cols

# Ordinal encode (ordered categories)
oe = OrdinalEncoder(categories=[["low", "medium", "high"]])
X_ord = oe.fit_transform(df[["size"]])

# For high-cardinality features, consider target encoding
# or just drop them if they're IDs.

不均衡データの処理

不均衡なデータがモデルを多数派クラスへ傾けます。最もきれいな修正が class_weight='balanced' です(データの複製なし)。SMOTE が少数派の新しいサンプルを合成しますが、ノイズを作り得ます — train にだけ適用しましょう。オーバーサンプリングとアンダーサンプリングは機能しますが、過剰適合したりデータを失ったりします。評価には必ず precision、recall、F1、AUC を使いましょう — 不均衡データでは精度だけに頼らないこと。

machine-learning
from sklearn.utils import resample
from imblearn.over_sampling import SMOTE
from sklearn.utils.class_weight import compute_class_weight

# 1. Class weights (no resampling — preferred for trees/linear)
classes = np.unique(y_train)
weights = compute_class_weight("balanced", classes=classes, y=y_train)
class_weight = dict(zip(classes, weights))
model = RandomForestClassifier(class_weight=class_weight)

# 2. Oversample minority
df_majority = df[df.y == 0]
df_minority = df[df.y == 1]
df_minority_up = resample(df_minority, replace=True,
                          n_samples=len(df_majority), random_state=42)

# 3. SMOTE: synthesize new minority samples via k-nearest neighbors
smote = SMOTE(random_state=42)
X_res, y_res = smote.fit_resample(X_train, y_train)

# Always resample on TRAINING data only — never the test set!

外れ値検出

外れ値が平均、標準偏差、線形モデルを歪めます。Z-score は速いですが正規性を仮定し、外れ値自体により歪められます(代わりに頑健な IQR を使いましょう)。高次元と非線形の境界を扱うのが Isolation Forest です。ドメインに応じて、外れ値を落とすか、上限を切るか(winsorize)、残すか決めましょう — 外れ値こそが、注目するケース(不正、異常)であることもあります。

machine-learning
import numpy as np
from sklearn.ensemble import IsolationForest

# Z-score: |x - mean| / std > 3 is an outlier
z_scores = np.abs((X - X.mean()) / X.std())
outliers = (z_scores > 3).any(axis=1)

# IQR method (more robust to outliers than z-score)
Q1, Q3 = X.quantile(0.25), X.quantile(0.75)
IQR = Q3 - Q1
outliers_iqr = ((X < (Q1 - 1.5 * IQR)) | (X > (Q3 + 1.5 * IQR))).any(axis=1)

# Isolation Forest (good for high-dimensional data)
iso = IsolationForest(contamination=0.05, random_state=42)
outliers_iso = iso.fit_predict(X)  # -1 = outlier, 1 = inlier

# Remove or cap (winsorize) outliers before training
X_clean = X[~outliers]
03

特徴量エンジニアリング

多項式と交互作用の特徴

PolynomialFeatures により、x^2、x*y などを新しい特徴として加え、線形モデルが非線形の関係を捉えられます。純粋な 2 乗を避けたいときに有用なのが interaction_only です。特徴数が組合せ的に爆発するため、過剰適合を防ぐため必ず正則化(Ridge/Lasso)とペアにするか、次元削減の後に使いましょう。

machine-learning
from sklearn.preprocessing import PolynomialFeatures

# Generate degree-2 features including interactions
poly = PolynomialFeatures(degree=2, interaction_only=False,
                          include_bias=False)
X_poly = poly.fit_transform(X)
# For X = [a, b], produces: [a, b, a^2, a*b, b^2]

# interaction_only=True keeps just [a, b, a*b] — no squares
poly_int = PolynomialFeatures(degree=2, interaction_only=True,
                              include_bias=False)
X_int = poly_int.fit_transform(X)

# Useful for linear models to capture non-linearity
# WARNING: feature count grows quickly — use with regularization

ビニングと離散化

ビニングが連続特徴を離散的なバケットへ変え、モデルが非線形の効果を捉え、外れ値への敏感さを減らす助けになります。等幅ビンの空ビン問題を避けるのが、分位点ビン(等頻度)です。ドメイン固有のビン(年齢層など)が、自動的なものをしばしば上回ります。モデルがバケットを別のカテゴリとして扱えるよう、ビン化された特徴を one-hot エンコードしましょう。

machine-learning
from sklearn.preprocessing import KBinsDiscretizer
import pandas as pd

# Equal-width bins (uniform spacing)
df["age_bin"] = pd.cut(df["age"], bins=5, labels=False)

# Equal-frequency bins (quantiles — same count per bin)
df["age_quantile"] = pd.qcut(df["age"], q=5, labels=False,
                              duplicates="drop")

# KBinsDiscretizer with strategy
kbd = KBinsDiscretizer(n_bins=5, encode="onehot-dense",
                        strategy="quantile")  # 'uniform','kmeans'
X_binned = kbd.fit_transform(X[["age"]])

# Custom bins with domain knowledge
df["age_group"] = pd.cut(df["age"],
                          bins=[0, 18, 35, 60, 100],
                          labels=["child","young","adult","senior"])

テキスト特徴の抽出

Bag-of-words のカウントは単純ですが、すべての単語を等しく扱います。文書をまたいで共通する単語の重みを下げるのが TF-IDF です。短いフレーズを捉えるのが ngram_range=(1,2) です。モダンな NLP には、事前学習済みの埋め込み(sentence-transformers、BERT)を使いましょう — bag-of-words では捉えられない意味を捉えます。語彙のサイズとノイズを制御するため、max_features と min_df を必ず設定しましょう。

machine-learning
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer

corpus = [
    "machine learning is fun",
    "deep learning is a subset of machine learning",
    "python is great for data science",
]

# Bag of words (counts)
cv = CountVectorizer(max_features=1000, stop_words="english",
                     ngram_range=(1, 2))
X_counts = cv.fit_transform(corpus)

# TF-IDF: downweights common words
tfidf = TfidfVectorizer(max_features=1000, stop_words="english",
                        ngram_range=(1, 2), min_df=2)
X_tfidf = tfidf.fit_transform(corpus)

# For production, consider sentence-transformers for embeddings:
# from sentence_transformers import SentenceTransformer
# model = SentenceTransformer("all-MiniLM-L6-v2")
# embeddings = model.encode(corpus)

日付と時刻の特徴

生の datetime の列はモデルにとって無用です — 意味のある部分(時、曜日、月)を抽出しましょう。循環特徴(sin/cos)が連続性を保ちます:時刻 23 が時刻 0 に近いこと。これは生の整数エンコードでは見失われます。人間の周期のパターンを捉えるのが is_weekend と祝日です。時系列の単純なトレンド特徴が days_since です。

machine-learning
import pandas as pd

df["date"] = pd.to_datetime(df["date"])

# Extract calendar parts
df["year"]      = df["date"].dt.year
df["month"]     = df["date"].dt.month
df["day"]       = df["date"].dt.day
df["dayofweek"] = df["date"].dt.dayofweek    # 0=Mon
df["dayofyear"] = df["date"].dt.dayofyear
df["hour"]      = df["date"].dt.hour
df["is_weekend"] = df["date"].dt.dayofweek >= 5

# Cyclic encoding (preserves continuity: hour 23 -> 0)
df["hour_sin"] = np.sin(2 * np.pi * df["hour"] / 24)
df["hour_cos"] = np.cos(2 * np.pi * df["hour"] / 24)
df["month_sin"] = np.sin(2 * np.pi * df["month"] / 12)
df["month_cos"] = np.cos(2 * np.pi * df["month"] / 12)

# Time elapsed (useful as a trend feature)
df["days_since"] = (df["date"] - df["date"].min()).dt.days

特徴選択

特徴が多いほど良いわけではありません — 無関係な特徴がノイズと過剰適合のリスクを加えます。速く統計的なのが SelectKBest で、徹底的だが遅いのが RFE(モデルを繰り返し再学習します)、tree の feature_importances_ を一発のフィルタとして使うのが SelectFromModel です。相関のフィルタが冗長な特徴を安価に取り除きます。選択は TRAINING データ上でだけ行い、同じセレクタを test に適用しましょう。

machine-learning
from sklearn.feature_selection import (SelectKBest, f_classif,
    RFE, SelectFromModel)
from sklearn.ensemble import RandomForestClassifier

# 1. Univariate: keep top-k by statistical test
selector = SelectKBest(f_classif, k=10)
X_new = selector.fit_transform(X, y)
selected = selector.get_support(indices=True)

# 2. Recursive Feature Elimination (model-based, iterative)
rfe = RFE(RandomForestClassifier(random_state=42),
          n_features_to_select=10)
X_rfe = rfe.fit_transform(X, y)

# 3. Select from model importance
sfm = SelectFromModel(RandomForestClassifier(random_state=42),
                      threshold="median")
X_sfm = sfm.fit_transform(X, y)

# 4. Correlation filter — drop one of highly-correlated pairs
corr = pd.DataFrame(X).corr().abs()
to_drop = [c for c in corr.columns
           if any(corr[c] > 0.95)]
X_filtered = X.drop(columns=to_drop)
04

教師あり学習

線形回帰とロジスティック回帰

線形モデルは速く、解釈可能で、強いベースラインです。LogisticRegression はデフォルトで L2 正則化を使います — C が低いほど正則化が強いです。多クラスには softmax を使います。係数が特徴の重要性を示しますが、それはスケーリング後だけです — スケールされていない特徴は係数を比較不可能にします。複雑なモデルを試す前に、必ず線形のベースラインから始めましょう。

machine-learning
from sklearn.linear_model import LinearRegression, LogisticRegression

# Regression: predict a continuous value
lr = LinearRegression()
lr.fit(X_train, y_train)
y_pred = lr.predict(X_test)

# Inspect coefficients
print("Coef:", lr.coef_, "Intercept:", lr.intercept_)

# Classification: predict a class (uses softmax for multiclass)
clf = LogisticRegression(
    penalty="l2",            # 'l1' (Lasso), 'elasticnet', None
    C=1.0,                   # inverse of regularization strength
    max_iter=1000,
    multi_class="multinomial",
)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
y_proba = clf.predict_proba(X_test)  # class probabilities

決定木とランダムフォレスト

決定木は解釈可能ですが高分散です — データの小さな変化が大きく異なる木を生みます。これを修正するのがランダムフォレストです。ブートストラップサンプルとランダムな特徴の部分集合で学習した多くの木の平均を取ります(bagging)。分類の標準が max_features='sqrt' です。フォレストからの特徴の重要性は、高基数特徴へ偏ります — より公正な見方には permutation_importance を試しましょう。

machine-learning
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier

# Single tree (high variance, easy to overfit)
tree = DecisionTreeClassifier(
    max_depth=5,              # limit depth to prevent overfitting
    min_samples_leaf=10,      # min samples per leaf
    random_state=42,
)
tree.fit(X_train, y_train)

# Random forest: ensemble of trees on bootstrapped samples
rf = RandomForestClassifier(
    n_estimators=200,         # number of trees
    max_depth=None,
    max_features="sqrt",      # features per split
    n_jobs=-1,                # use all CPUs
    random_state=42,
)
rf.fit(X_train, y_train)

# Feature importance (averaged across trees)
importances = pd.Series(rf.feature_importances_, index=X.columns)

勾配ブースティング(XGBoost / LightGBM)

勾配ブースティングが木を逐次的に構築し、それぞれが前の木の誤りを修正します — 表形式データでは通常最高の性能です。sklearn の GradientBoosting は遅く、そのヒストグラムベースの高速な等価物が HistGradientBoosting です。本番/競技の標準が XGBoost と LightGBM で、ネイティブの欠損値処理と早期停止を持ちます。最適な木の数を見つけるため、検証セット付きの early_stopping を必ず使いましょう。

machine-learning
from sklearn.ensemble import GradientBoostingClassifier, HistGradientBoostingClassifier
import lightgbm as lgb
import xgboost as xgb

# sklearn (slow on large data)
gbm = GradientBoostingClassifier(
    n_estimators=200, learning_rate=0.1, max_depth=3, random_state=42)
gbm.fit(X_train, y_train)

# sklearn's faster histogram-based version (like LightGBM)
hgbm = HistGradientBoostingClassifier(
    max_iter=200, learning_rate=0.1, max_leaf_nodes=31, random_state=42)
hgbm.fit(X_train, y_train)

# XGBoost (popular in competitions)
xgb_clf = xgb.XGBClassifier(
    n_estimators=200, learning_rate=0.1, max_depth=6,
    subsample=0.8, colsample_bytree=0.8, n_jobs=-1,
    eval_metric="logloss", random_state=42)
xgb_clf.fit(X_train, y_train, eval_set=[(X_val, y_val)], early_stopping_rounds=10)

# LightGBM (fastest on large data)
lgb_clf = lgb.LGBMClassifier(n_estimators=200, learning_rate=0.1, num_leaves=31)
lgb_clf.fit(X_train, y_train, eval_set=(X_val, y_val))

サポートベクターマシン

SVM が、クラスを分離する最大マージンの超平面を見つけます — はっきりした境界を持つ小〜中規模の dataset に強力です。特徴のスケーリングは MUST です(SVM は距離ベース)。非線形を扱うのが RBF カーネルで、grid search により C(正則化)と gamma(カーネルの幅)を調整しましょう。SVC はサンプルに対するスケーリングが悪いです(O(n^2)〜O(n^3))— 5 万サンプルを超えるなら LinearSVC か木のアンサンブルを使いましょう。

machine-learning
from sklearn.svm import SVC, SVR
from sklearn.preprocessing import StandardScaler

# SVC requires scaling!
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s  = scaler.transform(X_test)

# Kernels: 'linear', 'rbf' (Gaussian), 'poly', 'sigmoid'
svm = SVC(
    kernel="rbf",
    C=1.0,              # regularization (higher = fit harder)
    gamma="scale",      # kernel width
    probability=True,   # enable predict_proba (slower)
    random_state=42,
)
svm.fit(X_train_s, y_train)
y_pred = svm.predict(X_test_s)

# SVR for regression
svr = SVR(kernel="rbf", C=1.0, epsilon=0.1)
svr.fit(X_train_s, y_train)

k-近傍法

KNN が最も単純な ML アルゴリズムです:学習データを保存し、k 個の最近傍の間の投票で予測します。スケーリングが不可欠です(距離ベース)。小さい k = 低バイアス/高分散(過剰適合)、大きい k = 高バイアス/低分散(学習不足)。大きな dataset では予測時に KNN は遅いです — 本番には近似最近傍(FAISS、HNSW)を使いましょう。

machine-learning
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor

# KNN: classify by majority vote of k nearest training samples
knn = KNeighborsClassifier(
    n_neighbors=5,        # k — try odd values to break ties
    weights="uniform",    # or 'distance' (closer = more weight)
    metric="minkowski",   # 'euclidean','manhattan', etc.
    p=2,                  # 2=euclidean, 1=manhattan
    n_jobs=-1,
)
knn.fit(X_train_scaled, y_train)
y_pred = knn.predict(X_test_scaled)

# Choose k via cross-validation
from sklearn.model_selection import cross_val_score
for k in [1, 3, 5, 7, 9, 11]:
    score = cross_val_score(KNeighborsClassifier(n_neighbors=k),
                            X_train_scaled, y_train, cv=5).mean()
    print(f"k={k}: {score:.3f}")
05

教師なし学習

K-Means クラスタリング

K-Means が、クラスタ内分散を最小化することで、データを k 個の球状クラスタへ分割します。10 個のランダムな初期値からアルゴリズムを実行し最良を保つのが n_init=10 です(デフォルトは sklearn 1.4 で変わりました)。k の選択は、ひじ(inertia)か silhouette スコアで行いましょう(silhouette の方が原理的です)。K-Means は球状で等サイズのクラスタを仮定します — 非球状のクラスタには DBSCAN か Gaussian Mixture を。

machine-learning
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

# Choose k via the elbow method or silhouette score
inertias, silhouettes = [], []
for k in range(2, 11):
    km = KMeans(n_clusters=k, n_init=10, random_state=42)
    labels = km.fit_predict(X)
    inertias.append(km.inertia_)
    silhouettes.append(silhouette_score(X, labels))

# Final model with chosen k
kmeans = KMeans(n_clusters=4, n_init=10, random_state=42)
clusters = kmeans.fit_predict(X)
centers = kmeans.cluster_centers_

# Predict cluster for new points
new_labels = kmeans.predict(X_new)

DBSCAN(密度ベース)

DBSCAN が、任意の形状のクラスタを見つけ、外れ値(ラベル -1)を自動検出します — k を指定する必要がありません。決定的なパラメータが eps で、k 距離プロット(ソートされた k 最近傍距離の「ひじ」)で調整しましょう。ノイズへの敏感さの制御は min_samples です。密度の変化に DBSCAN は苦手で — それをよりよく扱うのが HDBSCAN です。新しいポイントを直接予測できません。再 fit するか、HDBSCAN の approximate_predict を使いましょう。

machine-learning
from sklearn.cluster import DBSCAN

# DBSCAN groups densely-connected points; marks sparse ones as noise (-1)
db = DBSCAN(
    eps=0.5,            # max distance between points in a cluster
    min_samples=5,      # min points to form a dense region
    metric="euclidean",
)
labels = db.fit_predict(X)
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
n_noise = list(labels).count(-1)

# Tune eps via the k-distance plot (k = min_samples)
from sklearn.neighbors import NearestNeighbors
nn = NearestNeighbors(n_neighbors=5).fit(X)
distances, _ = nn.kneighbors(X)
distances = np.sort(distances[:, -1])

# DBSCAN doesn't have predict() — refit to predict on new data
# Or use HDBSCAN for a more robust, parameter-light alternative

階層的クラスタリング

階層的クラスタリングが、ネストしたクラスタのツリー(樹形図)を構築します — 複数の粒度でクラスタ構造を理解したいときに有用です。樹形図が、任意のクラスタ数のためにどこで切るべきか視覚的に示します。最も一般的な結合方法が 'ward'(クラスタ内分散を最小化)で、'single' は脆いです(連鎖します)。AgglomerativeClustering は約 1 万サンプルを超えるとスケールしません — より大きなデータには K-Means か HDBSCAN を。

machine-learning
from sklearn.cluster import AgglomerativeClustering
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt

# Compute linkage matrix (for dendrogram)
Z = linkage(X, method="ward")  # 'ward','complete','average','single'

# Plot dendrogram to choose number of clusters
plt.figure(figsize=(10, 5))
dendrogram(Z, truncate_mode="level", p=5)
plt.axhline(y=Z[-4, 2], color="r", linestyle="--")  # cut at 4 clusters
plt.show()

# Agglomerative clustering with chosen k
agg = AgglomerativeClustering(
    n_clusters=4,
    linkage="ward",   # minimizes variance
    metric="euclidean",
)
labels = agg.fit_predict(X)

ガウス混合モデル

GMM が K-Means の確率的な対応物です:各クラスタが独自の平均と共分散を持つガウスであり、楕円のクラスタを扱い、ソフトな割り当て(確率)を与えます。最も柔軟なのが covariance_type='full' ですがパラメータが多く、'diag' が良い妥協です。k の選択は BIC で行いましょう(低い方が良い)。GMM は新しいサンプルも生成でき — データ拡張に有用です。

machine-learning
from sklearn.mixture import GaussianMixture

# GMM: probabilistic clustering — each cluster is a Gaussian
gmm = GaussianMixture(
    n_components=4,
    covariance_type="full",  # 'spherical','tied','diag','full'
    n_init=10,
    random_state=42,
)
gmm.fit(X)

labels = gmm.predict(X)
probs = gmm.predict_proba(X)   # soft clustering (responsibilities)

# Generative: sample new data
X_sampled, y_sampled = gmm.sample(100)

# Choose n_components via BIC (lower is better)
bics = []
for k in range(1, 11):
    g = GaussianMixture(n_components=k, n_init=10, random_state=42).fit(X)
    bics.append(g.bic(X))

異常検出

異常検出が、まれで疑わしいアイテムを特定します — 不正、欠陥、侵入。汎用の勝者が Isolation Forest です(速く、スケールが良く、高次元を扱えます)。きれいな「正常」の学習セットがあるときに機能するのが One-Class SVM です。グローバルな手法が見逃す局所的な異常を捉えるのが LOF です。期待される異常率を設定するのが contamination で、ドメイン知識に基づき調整しましょう。

machine-learning
from sklearn.ensemble import IsolationForest
from sklearn.svm import OneClassSVM
from sklearn.neighbors import LocalOutlierFactor

# Isolation Forest: isolates anomalies with shallow trees
iso = IsolationForest(contamination=0.05, random_state=42)
labels = iso.fit_predict(X)  # -1 anomaly, 1 normal
scores = iso.decision_function(X)  # lower = more anomalous

# One-Class SVM: learns a boundary around normal data
ocsvm = OneClassSVM(kernel="rbf", nu=0.05, gamma="scale")
labels = ocsvm.fit_predict(X_train_normal)

# Local Outlier Factor: density-based (good for local anomalies)
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.05)
labels = lof.fit_predict(X)
# For new data: lof.negative_outlier_factor_ (lower = more anomalous)
06

回帰

線形回帰と正則化版

OLS が正則化なしで二乗誤差を最小化します — 多重共線データでは高分散です。L2 の Ridge が係数を滑らかに縮めます — 多くの特徴がそれぞれ効くときに良いです。L1 の Lasso がいくつかの係数をゼロへ押し込み、特徴選択を行います。両者を混ぜた ElasticNet が、特徴が相関しているときに有用です。ペナルティが特徴間で公平になるよう、正則化回帰の前には必ず特徴をスケールしましょう。

machine-learning
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet

# Ordinary Least Squares
ols = LinearRegression()
ols.fit(X_train, y_train)

# Ridge (L2): shrinks coefficients, keeps all features
ridge = Ridge(alpha=1.0)
ridge.fit(X_train_scaled, y_train)

# Lasso (L1): shrinks some coefficients to 0 (feature selection)
lasso = Lasso(alpha=0.1, max_iter=10000)
lasso.fit(X_train_scaled, y_train)
print("Non-zero coefs:", (lasso.coef_ != 0).sum())

# ElasticNet: mix of L1 and L2
en = ElasticNet(alpha=0.1, l1_ratio=0.5)  # l1_ratio=1 -> pure Lasso
en.fit(X_train_scaled, y_train)

回帰の評価指標

RMSE が大きな誤差を(二乗で)罰し、y と同じ単位です — 最もよくある指標です。MAE がより解釈しやすく外れ値に頑健です。R2 が説明された分散の割合であり、0 はモデルが平均の予測と変わらないことを意味します。y=0 のとき未定義になるのが、パーセンテージの誤差を与える MAPE です。ビジネスコストに基づき指標を選びましょう:大きな誤差が壊滅的なら RMSE、すべての誤差が等しく高くつくなら MAE です。

machine-learning
from sklearn.metrics import (mean_squared_error, mean_absolute_error,
    r2_score, mean_absolute_percentage_error)

y_pred = model.predict(X_test)

mse  = mean_squared_error(y_test, y_pred)         # sensitive to outliers
rmse = np.sqrt(mse)                                # same units as y
mae  = mean_absolute_error(y_test, y_pred)         # robust to outliers
r2   = r2_score(y_test, y_pred)                    # 1=perfect, 0=mean, <0=worse
mape = mean_absolute_percentage_error(y_test, y_pred)  # % error

print(f"RMSE: {rmse:.3f}")
print(f"MAE:  {mae:.3f}")
print(f"R2:   {r2:.3f}")
print(f"MAPE: {mape:.1%}")

# Adjusted R2 accounts for number of features
n, p = X_test.shape
adj_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)

決定木回帰

木ベースの回帰器は区分一定の予測を行います — 学習データの範囲を超えて外挿できません。平均により分散を減らすのがランダムフォレストで、逐次修正によりバイアスを減らすのが勾配ブースティングです。平均ではなく分位点を予測するのが、分位点回帰(loss='quantile')です — 下側/上側の分位点モデルを組み合わせれば予測区間が得られ、不確実性の推定が必要なときに有用です。

machine-learning
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor

# Single tree (piecewise constant predictions)
dt = DecisionTreeRegressor(max_depth=5, min_samples_leaf=10,
                            random_state=42)
dt.fit(X_train, y_train)

# Random forest regressor (averages trees)
rf = RandomForestRegressor(n_estimators=200, max_features="sqrt",
                            n_jobs=-1, random_state=42)
rf.fit(X_train, y_train)

# Gradient boosting regressor
gb = GradientBoostingRegressor(n_estimators=200, learning_rate=0.1,
                                max_depth=3, random_state=42)
gb.fit(X_train, y_train)

# Quantile regression — predict ranges instead of points
from sklearn.ensemble import GradientBoostingRegressor
gbr_lower = GradientBoostingRegressor(loss="quantile", alpha=0.1)
gbr_upper = GradientBoostingRegressor(loss="quantile", alpha=0.9)
gbr_lower.fit(X_train, y_train)
gbr_upper.fit(X_train, y_train)

正則化パス

正則化パスが、alpha が増えるにつれ Lasso の係数がゼロへ縮む様子を示します — 異なるペナルティの強さの下での特徴の重要性の可視化です。高い alpha で生き残る特徴が最も予測的です。どの特徴が効くかの理解や、クロスバリデーションの前の合理的な alpha の範囲の選択のための、素晴らしい診断です。

machine-learning
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import lasso_path

# Compute Lasso coefficients for many alpha values
alphas, coefs, _ = lasso_path(X_train_scaled, y_train,
                               alphas=np.logspace(-3, 1, 100))

# Plot: each line is a coefficient vs alpha
plt.figure(figsize=(8, 5))
for coef in coefs:
    plt.plot(alphas, coef)
plt.xscale("log")
plt.xlabel("alpha (regularization strength)")
plt.ylabel("coefficient")
plt.title("Lasso regularization path")
plt.axhline(0, color="k", lw=0.5)
plt.show()

残差分析

残差プロットがモデルの仕様誤りを診断します。0 の周りのランダムな雲がモデルの良好な適合を意味し、U 字型は欠けた非線形性を(多項式特徴の追加か木の使用)、漏斗型は不均一分散を(y の log 変換を試す)示唆します。残差の正規性が効くのは推論(信頼区間)のためであり、予測精度のためではありません。

machine-learning
import matplotlib.pyplot as plt
import seaborn as sns

residuals = y_test - y_pred

fig, axes = plt.subplots(1, 2, figsize=(12, 5))

# 1. Residuals vs predicted — should look random around 0
axes[0].scatter(y_pred, residuals, alpha=0.5)
axes[0].axhline(0, color="r", linestyle="--")
axes[0].set_xlabel("Predicted"); axes[0].set_ylabel("Residual")

# 2. Residual distribution — should be ~normal
sns.histplot(residuals, kde=True, ax=axes[1])
axes[1].set_xlabel("Residual")

plt.show()

# Patterns in residuals suggest model issues:
# - U-shape: missing non-linearity (add polynomial features)
# - Funnel: heteroscedasticity (try log-transforming y)
# - Skew: try transforming y or use a different loss
07

分類

二値分類の基本

predict がハードなクラスラベルを返し(しきい値 0.5)、predict_proba が確率を返します — 通常こちらが有用です。デフォルトの 0.5 のしきい値はめったに最適ではありません:より高い recall を得るには(陽性を多く捉える、がんスクリーニングなど)下げ、より高い precision を得るには(誤警報を減らす、スパムフィルタなど)上げましょう。しきい値に依存せず、陽性が陰性より上にランクされる度合いを測るのが ROC-AUC です。

machine-learning
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (confusion_matrix, classification_report,
    roc_auc_score, precision_recall_curve)

clf = LogisticRegression(max_iter=1000)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
y_proba = clf.predict_proba(X_test)[:, 1]  # P(class=1)

# Confusion matrix: TN FP / FN TP
cm = confusion_matrix(y_test, y_pred)
print(cm)
print(classification_report(y_test, y_pred))

# Adjust threshold (default 0.5) to trade precision for recall
y_pred_custom = (y_proba > 0.3).astype(int)  # higher recall

# ROC-AUC: probability ranking quality (threshold-independent)
print("ROC-AUC:", roc_auc_score(y_test, y_proba))

混同行列と派生指標

不均衡データでは accuracy が誤解を招きます — 99% が陰性の dataset は、すべての陰性を予測するだけで 99% の精度になります。precision と recall が precision-recall のトレードオフを明らかにします:precision が「予測された陽性のうち、何個が本物か?」に、recall が「実際の陽性のうち、何個を捉えたか?」に答えます。両者の調和平均が F1 です。クラスが等しく重み付けされるべきなら macro、頻度を反映すべきなら weighted を使います。

machine-learning
from sklearn.metrics import (confusion_matrix, precision_score,
    recall_score, f1_score)

# Binary: confusion_matrix returns [[TN, FP], [FN, TP]]
tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()

accuracy  = (tp + tn) / (tp + tn + fp + fn)
precision = tp / (tp + fp)    # of predicted positives, how many correct
recall    = tp / (tp + fn)    # of actual positives, how many caught
f1        = 2 * precision * recall / (precision + recall)  # harmonic mean
specificity = tn / (tn + fp)  # true negative rate

# sklearn shortcuts
print("Precision:", precision_score(y_test, y_pred))
print("Recall:    ", recall_score(y_test, y_pred))
print("F1:        ", f1_score(y_test, y_pred))

# Multi-class: average='macro' (unweighted) or 'weighted' (by class size)
print("Macro F1:", f1_score(y_test, y_pred, average="macro"))

ROC と PR 曲線

ROC 曲線が、しきい値をまたいで recall(TPR)を偽陽性率に対してプロットします。ランクの品質を要約するのが曲線下面積(AUC)です(0.5 = ランダム、1.0 = 完全)。不均衡データでは ROC より PR 曲線の方が情報豊かです — 陰性が支配的なとき、ROC は欺瞞的に良く見えることがあります。ROC では左上、PR では右上を目指しましょう。

machine-learning
from sklearn.metrics import (roc_curve, precision_recall_curve,
    auc, RocCurveDisplay, PrecisionRecallDisplay)
import matplotlib.pyplot as plt

# ROC curve: TPR (recall) vs FPR at all thresholds
fpr, tpr, thresholds = roc_curve(y_test, y_proba)
roc_auc = auc(fpr, tpr)

# PR curve: precision vs recall (better for imbalanced data)
prec, rec, thresholds = precision_recall_curve(y_test, y_proba)
pr_auc = auc(rec, prec)

fig, axes = plt.subplots(1, 2, figsize=(12, 5))
RocCurveDisplay.from_predictions(y_test, y_proba, ax=axes[0])
PrecisionRecallDisplay.from_predictions(y_test, y_proba, ax=axes[1])
axes[0].set_title(f"ROC (AUC={roc_auc:.3f})")
axes[1].set_title(f"PR (AUC={pr_auc:.3f})")
plt.show()

多クラス分類

クラス数が 2 より大きいとき、LogisticRegression は softmax を使います(multi_class='multinomial')。どのクラスをモデルが混同するかが、クラスごとの precision/recall で分かります。クラスごとの recall を見るには、混同行列を(真のクラスの)行ごとに正規化しましょう — 系統的に誤分類されるカテゴリの発見に有用です。偶然の一致を調整するのが Cohen の kappa で、予測確率の品質を測るのが log_loss です(低い方が良い)。

machine-learning
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (cohen_kappa_score, log_loss,
    classification_report, confusion_matrix, ConfusionMatrixDisplay)

# Multiclass: logistic regression uses softmax by default
clf = LogisticRegression(multi_class="multinomial", max_iter=1000)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
y_proba = clf.predict_proba(X_test)

# Per-class report
print(classification_report(y_test, y_pred))

# Confusion matrix (now NxN)
disp = ConfusionMatrixDisplay.from_predictions(
    y_test, y_pred, display_labels=clf.classes_,
    cmap="Blues", normalize="true")  # normalize per true class

# Multiclass metrics
print("Cohen's kappa:", cohen_kappa_score(y_test, y_pred))
print("Log loss:     ", log_loss(y_test, y_proba))

確率のキャリブレーション

80% と予測したモデルは 80% の確度で正しいはずです — しかし多くの分類器(Random Forest、SVM、Naive Bayes)は、キャリブレーションされていないスコアを出力します。これを修正するのが CalibratedClassifierCV で、ホールドアウトしたセット上で、等張回帰かシグモイドを fit します。確率に基づいて行動する(リスクスコアリング、しきい値調整)ときはキャリブレーションが効きます — ハードなクラス予測しか使わないなら不要です。

machine-learning
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
import matplotlib.pyplot as plt

# Many classifiers output poorly-calibrated probabilities
# (e.g. Random Forest, SVM). Calibrate them.

# Method 1: isotonic regression (more flexible, needs more data)
# Method 2: sigmoid (Platt scaling) — parametric, works with less data
calibrated = CalibratedClassifierCV(rf, method="isotonic", cv=5)
calibrated.fit(X_train, y_train)
y_proba = calibrated.predict_proba(X_test)[:, 1]

# Calibration curve: predicted prob vs observed frequency
prob_true, prob_pred = calibration_curve(y_test, y_proba, n_bins=10)
plt.plot([0, 1], [0, 1], "k--")
plt.plot(prob_pred, prob_true, "s-")
plt.xlabel("Predicted probability"); plt.ylabel("Observed frequency")
plt.show()
08

クラスタリングの深掘り

k の選択:Elbow と Silhouette

ひじ法は、inertia の低下が急でなくなる k を探します — 主観的で、時に見えません。より原理的なのが silhouette スコアです:各点が自分のクラスタと最も近い別のクラスタのどれに似ているかを測ります(範囲 -1〜1)。Silhouette > 0.5 が合理的な構造で、> 0.7 が強いです。両方を可視化し、ひじが不明瞭なときは silhouette を優先しましょう。

machine-learning
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, silhouette_samples
import matplotlib.pyplot as plt

# Elbow method: inertia (sum of squared distances to centroid)
inertias = []
for k in range(1, 11):
    km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X)
    inertias.append(km.inertia_)

plt.plot(range(1, 11), inertias, "o-")
plt.xlabel("k"); plt.ylabel("Inertia"); plt.title("Elbow method")
plt.show()

# Silhouette: -1 (bad) to 1 (well-clustered), 0 = on boundary
silhouettes = []
for k in range(2, 11):
    labels = KMeans(n_clusters=k, n_init=10, random_state=42).fit_predict(X)
    silhouettes.append(silhouette_score(X, labels))

Silhouette プロット

silhouette プロットが、クラスタごとにグループ化した、すべてのサンプルの silhouette 係数を示します。等幅の「ナイフ」形状がバランスの取れたクラスタを意味し、不均一な幅は、あるクラスタが支配的であることを意味します。赤い破線が平均で — この線を下回る平均のクラスタは分離が悪いです。異なる k の値を視覚的に比較するには、このプロットを使いましょう。

machine-learning
from sklearn.metrics import silhouette_samples
import matplotlib.pyplot as plt
import numpy as np

k = 4
km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X)
labels = km.labels_
sil_values = silhouette_samples(X, labels)

fig, ax = plt.subplots(figsize=(8, 6))
y_lower = 10
for i in range(k):
    ith = np.sort(sil_values[labels == i])
    y_upper = y_lower + len(ith)
    ax.fill_betweenx(np.arange(y_lower, y_upper), 0, ith, alpha=0.7)
    ax.text(-0.05, (y_lower + y_upper) / 2, str(i))
    y_lower = y_upper + 10
ax.axvline(sil_values.mean(), color="red", linestyle="--")
ax.set_xlabel("Silhouette coefficient"); ax.set_ylabel("Cluster")
plt.show()

HDBSCAN(Hierarchical DBSCAN)

HDBSCAN が、DBSCAN の最大の弱点 — eps の調整必要性 — を修正します。変化する密度レベルにわたり階層を構築し、安定したクラスタを取り出すため、クラスタの密度が変化するデータで機能します。主なパラメータが min_cluster_size で、直感的です(注目する最小のクラスタ)。まばらな領域のポイントがラベル -1(ノイズ)を得ます。実世界のデータでは、HDBSCAN が K-Means より意味のあるクラスタをしばしば作ります。

machine-learning
import hdbscan  # pip install hdbscan

# HDBSCAN: DBSCAN that automatically chooses eps via hierarchy
clusterer = hdbscan.HDBSCAN(
    min_cluster_size=5,   # min points to form a cluster
    min_samples=None,     # how conservative to be about noise
    metric="euclidean",
    cluster_selection_method="eom",  # 'leaf' for fine-grained
)
labels = clusterer.fit_predict(X)

# Soft clustering: probability of cluster membership
probs = clusterer.probabilities_

# Compare clusters across parameter settings
clusterer.condensed_tree_.plot()

クラスタリングの評価

内部の指標(silhouette、Davies-Bouldin、Calinski-Harabasz)が、グラウンドトゥルースなしでクラスタの品質を評価します — モデル選択に有用です。既知のラベルとクラスタリングを比較するのが外部の指標(ARI、NMI)です — ラベル付きデータでのベンチマークに有用です。ARI と NMI のどちらも偶然を調整し、置換不変です。最良の単一指標はなく — いくつかを使い、クラスタを可視化しましょう。

machine-learning
from sklearn.metrics import (silhouette_score, davies_bouldin_score,
    calinski_harabasz_score, adjusted_rand_score, normalized_mutual_info_score)

# Internal metrics (no ground truth)
print("Silhouette:        ", silhouette_score(X, labels))      # higher = better
print("Davies-Bouldin:    ", davies_bouldin_score(X, labels))   # lower = better
print("Calinski-Harabasz: ", calinski_harabasz_score(X, labels)) # higher = better

# External metrics (when you have ground-truth labels)
true_labels = y  # e.g. the actual iris species
print("Adjusted Rand:    ", adjusted_rand_score(true_labels, labels))
print("NMI:              ", normalized_mutual_info_score(true_labels, labels))

# ARI and NMI: 0 = random, 1 = perfect match
# Both are invariant to label permutations (cluster 1 vs cluster 2 doesn't matter)

クラスタリングのための次元削減

高次元でのクラスタリングは次元の呪いに苦しみます — 距離が無意味になります。まず 5〜50 次元へ削減しましょう(線形で速い PCA か、非線形で局所構造を保つ UMAP)。t-SNE は可視化専用です(新しいデータのための transform メソッドがなく、歪みのためクラスタリングの入力には不適切です)。クラスタの可視化は、t-SNE か UMAP で 2D に必ず行いましょう。

machine-learning
from sklearn.decomposition import PCA, UMAP  # umap-learn package
from sklearn.manifold import TSNE
from sklearn.cluster import KMeans

# Reduce dimensions BEFORE clustering high-dim data
# PCA: linear, fast, preserves global structure
pca = PCA(n_components=10, random_state=42).fit(X)
X_pca = pca.transform(X)

# UMAP: non-linear, fast, preserves local+global structure
reducer = UMAP(n_components=5, random_state=42)
X_umap = reducer.fit_transform(X)

# t-SNE: visualization only (no transform on new data)
X_tsne = TSNE(n_components=2, perplexity=30, random_state=42).fit_transform(X)

# Cluster on the embeddings
labels = KMeans(n_clusters=4, n_init=10, random_state=42).fit_predict(X_umap)

# Plot 2D embedding colored by cluster
plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=labels, cmap="tab10", s=10)
plt.show()
09

次元削減

PCA(主成分分析)

PCA が、最も多くの分散を捉える直交軸(主成分)を見つけ、ほとんどの情報を保ちつつ高次元データを圧縮させます。スケーリングが効きます — PCA は特徴のスケールに敏感です。95% の分散を自動的に保つのが n_components=0.95 です。PCA は線形で速いですが、分散 = 情報という仮定を置きます。これは常に真ではありません(低分散の特徴が識別的であることもあります)。

machine-learning
from sklearn.decomposition import PCA

# PCA finds orthogonal axes of maximum variance
pca = PCA(n_components=2, random_state=42)
X_pca = pca.fit_transform(X_scaled)   # scaling matters!

# Explained variance: how much info each PC retains
print("Explained variance ratio:", pca.explained_variance_ratio_)
print("Total retained:", pca.explained_variance_ratio_.sum())

# Choose n_components to retain 95% of variance
pca_full = PCA(n_components=0.95, random_state=42).fit(X_scaled)
print("Components for 95%:", pca_full.n_components_)
X_reduced = pca_full.transform(X_scaled)

# Reconstruct (lossy) from compressed representation
X_reconstructed = pca_full.inverse_transform(X_reduced)

可視化のための t-SNE

t-SNE が高次元データの 2D/3D 可視化に優れ、局所近傍を保つため、クラスタが視覚的に現れます。局所と大域の構造のバランスを制御するのが perplexity(通常 5〜50)です。t-SNE の歪み:クラスタのサイズとクラスタ間の距離は「意味を持ちません」。意味を持つのは局所近傍だけです。大きなデータでは遅いので、t-SNE の前に PCA で次元を削減しましょう(例えば 50 へ)。

machine-learning
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt

# t-SNE is for 2D/3D visualization, NOT as preprocessing
tsne = TSNE(
    n_components=2,
    perplexity=30,         # try 5-50; ~ sqrt(n_samples) is a heuristic
    learning_rate="auto",
    n_iter=1000,
    init="pca",            # better than random init
    random_state=42,
)
X_tsne = tsne.fit_transform(X_scaled)

plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=y, cmap="tab10", s=10)
plt.colorbar(); plt.show()

UMAP

UMAP が t-SNE のモダンな代替です:より速く、スケールが良く、局所と大域の構造の両方を保ち、決定的に重要なのは、新しいデータへの transform をサポートするため、パイプラインのステップになれることです。局所対大域のトレードオフを制御するのが n_neighbors で(小 = 局所の詳細、大 = 大域の構造)、ポイントがどれだけ密集するかの制御が min_dist です。ML パイプラインでは、2 ではなく 5〜50 次元への圧縮に UMAP を使いましょう。

machine-learning
from umap import UMAP  # pip install umap-learn

# UMAP: faster than t-SNE, preserves more global structure,
# and supports transform on new data (good for ML pipelines)
reducer = UMAP(
    n_components=2,
    n_neighbors=15,    # smaller = local, larger = global
    min_dist=0.1,      # how tightly points pack
    metric="euclidean",
    random_state=42,
)
X_umap = reducer.fit_transform(X_scaled)

# Can transform new data (unlike t-SNE)
X_new_umap = reducer.transform(X_new)

# Use in a pipeline as a preprocessor before clustering/classification
from sklearn.pipeline import Pipeline
pipe = Pipeline([
    ("umap", UMAP(n_components=5, random_state=42)),
    ("clf",  RandomForestClassifier(random_state=42)),
])

LDA(線形判別分析)

PCA(教師なし)と違い、LDA はクラスラベルを使い、クラス間分散を最大化しつつクラス内分散を最小化する射影を見つけます。n_components の最大は n_classes - 1 であるため、クラス数の少ない問題でしか有用ではありません。LDA は線形分類器も兼ねます(共通の共分散を持つガウスのクラスを仮定します)。ラベルがあり、クラス分離性を最大化する次元削減が欲しいときに LDA を使いましょう。

machine-learning
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

# LDA is SUPERVISED dimensionality reduction — uses class labels
# to find axes that best separate classes
lda = LinearDiscriminantAnalysis(n_components=2)
X_lda = lda.fit_transform(X_train, y_train)  # note: y_train passed in

# Also a classifier (Gaussian model per class)
y_pred = lda.predict(X_test)

# Max n_components = n_classes - 1
# For 3 classes, you get at most 2 LDA components

# Compare: PCA ignores class labels (unsupervised);
# LDA uses labels to maximize class separability

Truncated SVD(疎データ向け)

TruncatedSVD(テキストでは LSA とも)が、疎データ向けの PCA の代替です。データを中心化しないため、TF-IDF のような疎行列で機能します。TF-IDF と組み合わせると「トピック」が作れます — 共起する単語のグループです。より良いトピックモデルには、NMF かモダンな埋め込みベースのアプローチを試しましょう。テキストには約 100〜300 成分を保ち、正しい数はコーパスのサイズと下流のタスクに依存します。

machine-learning
from sklearn.decomposition import TruncatedSVD

# PCA doesn't work on sparse matrices (it needs to center data)
# Use TruncatedSVD instead — works directly on sparse TF-IDF, etc.

from scipy.sparse import csr_matrix
X_sparse = csr_matrix(X_tfidf)  # e.g. from TfidfVectorizer

svd = TruncatedSVD(n_components=100, random_state=42)
X_reduced = svd.fit_transform(X_sparse)

# Often combined with TF-IDF for LSA (Latent Semantic Analysis)
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD

vectorizer = TfidfVectorizer(max_features=10000)
lsa = Pipeline([
    ("tfidf", vectorizer),
    ("svd",   TruncatedSVD(n_components=100, random_state=42)),
])
X_topics = lsa.fit_transform(documents)
10

モデル評価

クロスバリデーション

クロスバリデーションが、複数の train/test 分割の平均により、堅牢な性能推定を与えます。分類でのクラスバランスの保持(不均衡データには不可欠)は StratifiedKFold です。異なる分割で CV を複数回実行するのが RepeatedStratifiedKFold です — より高い計算コストでより安定した推定です。モデル選択には、単一の train/test 分割ではなく必ず CV を使いましょう。

machine-learning
from sklearn.model_selection import (cross_val_score, cross_validate,
    StratifiedKFold, KFold, RepeatedStratifiedKFold)

# Basic 5-fold CV
scores = cross_val_score(model, X, y, cv=5, scoring="accuracy")
print(f"{scores.mean():.3f} +/- {scores.std():.3f}")

# Stratified (preserves class balance — use for classification)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X, y, cv=cv, scoring="f1_macro")

# Multiple metrics at once
results = cross_validate(model, X, y, cv=cv,
    scoring=["accuracy", "f1_macro", "roc_auc_ovr"],
    return_train_score=True)
print(results["test_f1_macro"].mean())

# Repeated CV for more stable estimates
rcv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=42)

学習曲線

学習曲線が、dataset のサイズに対する学習と検証の性能をプロットします — バイアス対分散の最良の診断です。高い学習スコアと低い検証スコアの間の大きなギャップが過剰適合を意味し(データを増やす、正則化する、単純化する)、両スコアが低く近ければ学習不足です(より複雑なモデルか特徴の追加)。曲線が右端でまだ改善しているなら、より多くのデータが役立ちます。

machine-learning
from sklearn.model_selection import learning_curve
import matplotlib.pyplot as plt

train_sizes, train_scores, val_scores = learning_curve(
    model, X, y,
    train_sizes=np.linspace(0.1, 1.0, 10),
    cv=5, scoring="accuracy", n_jobs=-1, random_state=42,
)

train_mean = train_scores.mean(axis=1)
val_mean   = val_scores.mean(axis=1)

plt.plot(train_sizes, train_mean, "o-", label="Train")
plt.plot(train_sizes, val_mean,   "o-", label="Validation")
plt.xlabel("Training samples"); plt.ylabel("Accuracy")
plt.legend(); plt.show()

# Diagnose:
# - High train, low val  -> overfitting (high variance) -> more data or regularize
# - Both low and close   -> underfitting (high bias) -> more complex model/features
# - Gap closing with data -> more data helps

検証曲線(ハイパーパラメータ)

検証曲線が、単一のハイパーパラメータの値に対する性能をプロットします — モデルの挙動の理解と、grid search の前の合理的な範囲の発見に有用です。モデルの複雑さと共に学習スコアが上昇し続けるのに対し、検証スコアはピークを経て低下します。ピークが甘味点で、手前が学習不足、後が過剰適合です。

machine-learning
from sklearn.model_selection import validation_curve
import matplotlib.pyplot as plt

param_range = [1, 2, 4, 8, 16, 32, 64]
train_scores, val_scores = validation_curve(
    RandomForestClassifier(random_state=42),
    X, y,
    param_name="max_depth",
    param_range=param_range,
    cv=5, scoring="accuracy", n_jobs=-1,
)

plt.plot(param_range, train_scores.mean(axis=1), "o-", label="Train")
plt.plot(param_range, val_scores.mean(axis=1),   "o-", label="Validation")
plt.xlabel("max_depth"); plt.ylabel("Accuracy")
plt.legend(); plt.show()

# Sweet spot is where validation peaks before overfitting

分類レポートの読み方

classification_report の macro 平均はすべてのクラスを等しく扱います(まれなクラスが効くときに良い)。クラスの頻度を反映するのが weighted 平均です(多数派の性能が支配するときに良い)。平均化の戦略は、各クラスを見逃すビジネスコストに基づき選びましょう。深刻な不均衡では、PR-AUC とクラスごとの recall を補いに使いましょう — 精度や F1 ですら、多数派を予測するだけのモデルを隠せます。

machine-learning
from sklearn.metrics import classification_report

report = classification_report(y_test, y_pred, output_dict=True)

# Per-class metrics + macro/weighted averages
import pandas as pd
df_report = pd.DataFrame(report).T
print(df_report[["precision", "recall", "f1-score", "support"]])

# 'macro' avg     = unweighted mean across classes (treats all equally)
# 'weighted' avg  = support-weighted mean (reflects class imbalance)
# Focus on:
# - macro F1 if all classes matter equally (e.g. digit recognition)
# - weighted F1 if rare classes matter less
# - recall of the positive class if it's the costly one (fraud, disease)

# For imbalanced classification, also report:
# - Precision-Recall AUC
# - Brier score (probability calibration)

回帰指標の深掘り

回帰の指標はビジネスコストに基づき選びましょう。大きな誤差が不釣り合いに悪いなら RMSE(二乗のペナルティ)、同じ大きさのすべての誤差が等しく悪いなら MAE です。R2 は無次元で、dataset をまたいで比較できます。最悪のケースを示すのが max error です。カスタムの非対称な損失(例:過小予測をより罰する)が現実のコストに合います — 欠品のコストと過剰在庫のコストは違います。

machine-learning
from sklearn.metrics import (mean_squared_error, mean_absolute_error,
    r2_score, explained_variance_score, max_error)

# RMSE — penalizes large errors; same units as y
rmse = mean_squared_error(y_test, y_pred, squared=False)

# MAE — robust to outliers; same units as y
mae = mean_absolute_error(y_test, y_pred)

# R^2 — fraction of variance explained (1.0 = perfect, 0 = predict mean)
r2 = r2_score(y_test, y_pred)

# Explained variance — like R^2 but ignores mean offset
evs = explained_variance_score(y_test, y_pred)

# Max error — single largest absolute error (worst-case)
max_err = max_error(y_test, y_pred)

# Custom asymmetric loss: penalize under-prediction more
def asymmetric_error(y_true, y_pred, under_penalty=2.0):
    error = y_true - y_pred
    return np.where(error > 0, under_penalty * error**2, error**2).mean()
11

クロスバリデーションの戦略

K 分割のバリアント

正しい CV 戦略の選択は決定的に重要です。デフォルトが KFold です。分類には StratifiedKFold(クラスバランスを保持)。サンプルが相関しているとき(ユーザー/患者ごとに複数行)には GroupKFold — train と val の間での情報漏れを防ぎます。時系列データには TimeSeriesSplit(常に過去で学習し未来で検証)。間違った CV 戦略が、過剰に楽観的な推定を与えます。

machine-learning
from sklearn.model_selection import (KFold, StratifiedKFold,
    GroupKFold, TimeSeriesSplit, RepeatedKFold)

# Standard K-fold (regression or balanced classification)
kf = KFold(n_splits=5, shuffle=True, random_state=42)

# Stratified (classification — preserves class proportions)
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

# Group K-fold (when samples are not independent — e.g. multiple rows per patient)
gkf = GroupKFold(n_splits=5)  # pass groups=patient_ids to CV

# Time series split (no shuffle — preserves temporal order)
tscv = TimeSeriesSplit(n_splits=5)

# Use with cross_val_score:
scores = cross_val_score(model, X, y, cv=gkf, groups=groups, scoring="f1")

時系列クロスバリデーション

TimeSeriesSplit が時間順序を尊重します:各分割が過去で学習し未来で検証し、決して逆になりません。これが現実の予測に一致し、漏れを防ぎます。近くのサンプルが自己相関しているとき(明日の価格が今日の価格と相関するなど)には、gap パラメータを使いましょう。時系列データ上でのシャッフルした標準の KFold が、極めて楽観的な推定を与えます — よくある初心者の過ちです。

machine-learning
from sklearn.model_selection import TimeSeriesSplit
import matplotlib.pyplot as plt
import numpy as np

tscv = TimeSeriesSplit(n_splits=5, test_size=100)
# gap parameter (sklearn 1.0+): prevent leakage from train to test
tscv = TimeSeriesSplit(n_splits=5, test_size=100, gap=10)

for fold, (train_idx, test_idx) in enumerate(tscv.split(X)):
    X_tr, X_te = X[train_idx], X[test_idx]
    y_tr, y_te = y[train_idx], y[test_idx]
    model.fit(X_tr, y_tr)
    score = model.score(X_te, y_te)
    print(f"Fold {fold}: train={len(train_idx)}, test={len(test_idx)}, score={score:.3f}")

# NEVER shuffle time-series data for CV — that leaks future into past
# Use gap to avoid leakage from autocorrelated near-future points

グループを考慮した CV

データにグループがあるとき(患者、ユーザー、セッションごとに複数サンプル)、標準のランダム分割が情報を漏らします — モデルが train と test で同じエンティティを見るため、スコアが膨らみます。すべてのグループを完全に 1 分割の中に留めるのが GroupKFold です。典型的なシナリオ:医療データ(患者ごとに複数スキャン)、推薦(ユーザーごとに複数評価)、画像データ(シーンごとに複数フレーム)。グループを考慮した CV を使わないことが、ML で最もよくあるサイレントなバグの一つです。

machine-learning
from sklearn.model_selection import GroupKFold, GroupShuffleSplit

# When the same entity appears in multiple rows (e.g. multiple X-rays per patient),
# random splits leak: the model memorizes patient-specific features
# instead of learning generalizable patterns.

# Solution: keep all rows of a group in the same split
gkf = GroupKFold(n_splits=5)
scores = cross_val_score(model, X, y, cv=gkf, groups=df["patient_id"])

# GroupShuffleSplit: random train/test split respecting groups
gss = GroupShuffleSplit(n_splits=5, test_size=0.2, random_state=42)
for train_idx, test_idx in gss.split(X, groups=df["patient_id"]):
    ...

# Always pass the groups argument to CV functions
# Common scenarios: patients, users, sessions, image batches

ネストした CV(偏りのないハイパーパラメータ調整)

標準の GridSearchCV が報告する CV スコアは楽観的です — スコア付けに使ったのと同じ分割で最良のハイパーパラメータを選んでいるからです。これを修正するのがネストした CV です:外側の CV ループが、真にホールドアウトした分割上で、チューニング手順全体を評価します。結果が、(チューニングを含む)モデルリングパイプライン全体が新しいデータでどう性能を出すかの、偏りのない推定です。誠実なベンチマークに、特にモデルを比較するときに使いましょう。

machine-learning
from sklearn.model_selection import (GridSearchCV, cross_val_score,
    StratifiedKFold)

# Outer loop: estimate generalization performance
# Inner loop: tune hyperparameters
# Without nesting, GridSearchCV's CV score is optimistic (it selected the best
# hyperparameters using the same data)

inner_cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

grid = GridSearchCV(
    RandomForestClassifier(random_state=42),
    param_grid={"max_depth": [3, 5, 10], "n_estimators": [50, 100]},
    cv=inner_cv, scoring="f1", n_jobs=-1,
)

nested_scores = cross_val_score(grid, X, y, cv=outer_cv, scoring="f1")
print(f"Nested CV F1: {nested_scores.mean():.3f} +/- {nested_scores.std():.3f}")

# Fit the final model on all data
grid.fit(X, y)
best_model = grid.best_estimator_

前処理付きの CV(Pipeline)

前処理は学習分割上でのみ fit されなければなりません — さもないと、テスト分割の統計(平均、中央値、スケーリング係数)が学習へ漏れ、楽観的な CV スコアになります。修正はすべてを Pipeline で包むことです:scikit-learn が、各 CV 分割が学習部分で自分の前処理を fit することを保証します。これが、誠実な ML 評価のための最重要のベストプラクティスです。CV の前に全 dataset で前処理を fit してはいけません。

machine-learning
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score
from sklearn.impute import SimpleImputer

# RIGHT: wrap preprocessing in a Pipeline so each fold fits
# its own scaler/imputer on the training portion only
pipe = Pipeline([
    ("impute",  SimpleImputer(strategy="median")),
    ("scale",   StandardScaler()),
    ("model",   RandomForestClassifier(random_state=42)),
])

scores = cross_val_score(pipe, X, y, cv=5, scoring="f1")

# WRONG: fit scaler on the whole dataset, then CV
# (leaks test-fold statistics into training)
# scaler.fit(X)              # NO - includes future test folds
# X_scaled = scaler.transform(X)
# cross_val_score(model, X_scaled, y, cv=5)  # optimistic scores

# Pipelines also make deployment easier (one object, no leakage)
12

ハイパーパラメータ調整

Grid Search

GridSearchCV がすべての組み合わせを網羅的に評価します — 徹底的ですが高コストです(組合せ爆発)。小さくうまく選ばれたパラメータグリッドがあるときに使いましょう。適切な scoring 指標は必ず渡しましょう(デフォルトは accuracy で、不均衡な分類では誤りです)。返される推定器が使える状態になるよう、全学習データ上で最良のモデルを再学習するのが refit=True です。

machine-learning
from sklearn.model_selection import GridSearchCV

# Exhaustive search over all combinations
param_grid = {
    "n_estimators": [50, 100, 200],
    "max_depth":    [3, 5, 10, None],
    "min_samples_leaf": [1, 5, 10],
}
# 3 * 4 * 3 = 36 combinations, * 5 folds = 180 fits

grid = GridSearchCV(
    RandomForestClassifier(random_state=42),
    param_grid=param_grid,
    cv=5,
    scoring="f1",
    n_jobs=-1,
    refit=True,         # refit best model on full data
    return_train_score=True,
)
grid.fit(X_train, y_train)

print("Best params: ", grid.best_params_)
print("Best CV F1:  ", grid.best_score_)
best_model = grid.best_estimator_

Randomized Search

RandomizedSearchCV が分布から n_iter の組み合わせをサンプリングします — 多くのパラメータが効くとき、grid search よりはるかに効率的です。学習率と正則化の強さには loguniform を使いましょう(桁が大きく変わるため)。50〜100 イテレーションが通常、ほぼ最適な構成を見つけます。ランダム性が、grid search が見逃すかもしれない局所最適からの脱出にも役立ちます。

machine-learning
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint, loguniform

# Sample from distributions instead of enumerating all combos
# Much more efficient when the grid is large
param_dist = {
    "n_estimators":     randint(50, 500),     # discrete uniform
    "max_depth":        [3, 5, 10, None],
    "min_samples_leaf": randint(1, 20),
    "learning_rate":    loguniform(1e-3, 1e0),  # log-uniform
}

rand_search = RandomizedSearchCV(
    GradientBoostingClassifier(random_state=42),
    param_distributions=param_dist,
    n_iter=50,           # number of parameter settings sampled
    cv=5,
    scoring="f1",
    n_jobs=-1,
    random_state=42,
)
rand_search.fit(X_train, y_train)
print("Best params:", rand_search.best_params_)

ベイズ最適化(Optuna)

Optuna がベイズ最適化を使い、前の試行の結果に基づき次のハイパーパラメータを知的にサンプリングします — grid/ランダム検索よりはるかにサンプル効率が高いです。剪定(悪い試行の早期停止)、条件付きのパラメータ空間、多目的最適化もサポートします。study オブジェクトがすべての試行を保存するため、パラメータの重要性和最適化履歴を可視化できます。多くのハイパーパラメータを持つ高コストなモデルに最適です。

machine-learning
import optuna

def objective(trial):
    # Suggest hyperparameters
    n_estimators = trial.suggest_int("n_estimators", 50, 500)
    max_depth    = trial.suggest_int("max_depth", 3, 20)
    lr           = trial.suggest_float("learning_rate", 1e-3, 1e0, log=True)
    min_samples  = trial.suggest_int("min_samples_leaf", 1, 20)

    model = GradientBoostingClassifier(
        n_estimators=n_estimators, max_depth=max_depth,
        learning_rate=lr, min_samples_leaf=min_samples,
        random_state=42,
    )
    # 5-fold CV F1
    score = cross_val_score(model, X_train, y_train, cv=5,
                            scoring="f1", n_jobs=-1).mean()
    return score  # Optuna maximizes by default

study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=100, timeout=600)

print("Best trial:", study.best_trial.params)
print("Best F1:    ", study.best_trial.value)

Halving Search(逐次半減)

halving search が反復的なリソース配分の戦略です:少ないデータで多くの候補を評価し、最悪を取り除き、生存者をより多くのデータ(または推定器)で再評価します。完全な grid search よりはるかに速く、しばしば似た解を見つけます。さらに大きな空間には HalvingRandomSearchCV を使いましょう。候補をどれほど積極的に取り除くかは 'factor' が制御します。多くのハイパーパラメータと限られた時間があるときの、素晴らしいデフォルトです。

machine-learning
from sklearn.experimental import enable_halving_search_cv  # noqa
from sklearn.model_selection import HalvingGridSearchCV, HalvingRandomSearchCV

# Allocate more resources to promising candidates iteratively
halving = HalvingGridSearchCV(
    RandomForestClassifier(random_state=42),
    param_grid={"max_depth": [3, 5, 10, None],
                "n_estimators": [50, 100, 200]},
    cv=5,
    scoring="f1",
    factor=3,           # eliminate bottom 2/3 each round
    aggressive_elimination=False,
    n_jobs=-1,
)
halving.fit(X_train, y_train)
print("Best params:", halving.best_params_)
print("Best score: ", halving.best_score_)

# Much faster than full GridSearchCV — evaluates many candidates
# cheaply first, then invests more resources in the promising ones.

チューニングのベストプラクティス

最大のチューニングの罪:テストセットでの最適化、検証セットへの過剰適合までのチューニング、最終性能としての CV スコアの報告です。学習データ上の CV 経由でチューニングし、その後、きれいなホールドアウトのテストセット上で最終モデルを 1 回評価しましょう。選んだハイパーパラメータが頑健である(分割をまたぐ小さな std)こと、幸運なランダムシードではないことを確認するため、cv_results_ 全体を検査しましょう。大まかに始めて絞り込む — ほとんどの利得は少数の重要なパラメータから来ます。

machine-learning
# 1. Tune on a VALIDATION set or via CV — never on the test set
# 2. Use the metric you actually care about (scoring=...)
# 3. Set random_state for reproducibility
# 4. Start coarse (randomized, few iterations), then refine around the best
# 5. Don't over-tune — small improvements may be noise

# Inspect full results to understand hyperparameter sensitivity
import pandas as pd
results = pd.DataFrame(grid.cv_results_)
cols = ["param_max_depth", "param_n_estimators",
        "mean_test_score", "std_test_score", "rank_test_score"]
print(results[cols].sort_values("rank_test_score").head(10))

# Refit the best model on the FULL training set (automatic with refit=True)
# Then evaluate ONCE on the held-out test set
test_score = grid.best_estimator_.score(X_test, y_test)
print(f"Test score: {test_score:.3f}")
13

アンサンブル学習

Bagging(Bootstrap Aggregating)

Bagging が、ブートストラップサンプル(復元抽出)上で多くのモデルを学習し、予測を平均します — バイアスを増やさずに分散を減らします。より多様な木のために、分割ごとの特徴のランダム性を加えるのが Random Forest です。各木が学習しなかった約 37% のサンプル上で評価するのが、Out-of-Bag(OOB)スコアです — 別のセットを要さない、無料の検証推定です。検証セットを割けない小さな dataset に、OOB は最適です。

machine-learning
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier

# Bagging: train multiple models on bootstrap samples (with replacement)
bag = BaggingClassifier(
    estimator=DecisionTreeClassifier(),  # any base estimator
    n_estimators=100,
    max_samples=1.0,         # fraction of samples per bootstrap
    max_features=1.0,        # fraction of features per estimator
    bootstrap=True,
    n_jobs=-1,
    random_state=42,
)
bag.fit(X_train, y_train)

# Random Forest is bagging + random feature subsets at each split
# Out-of-bag (OOB) score: evaluate each tree on samples it didn't see
rf = RandomForestClassifier(n_estimators=200, oob_score=True,
                             random_state=42)
rf.fit(X_train, y_train)
print("OOB score:", rf.oob_score_)  # ~ validation accuracy for free

Boosting

Boosting がモデルを逐次的に学習し、それぞれが前のモデルの誤りを修正します — バイアス(といくらかの分散)を減らします。サンプルの重み付けし直しが AdaBoost で、残差への直接の適合が勾配ブースティングです。learning_rate と n_estimators がトレードオフします:低い learning_rate はより多くの推定器を要しますが、しばしばよりよく汎化します — 必ず早期停止を使いましょう。sklearn のヒストグラムベースの高速な実装が HistGradientBoosting で、LightGBM に匹敵します。

machine-learning
from sklearn.ensemble import (AdaBoostClassifier,
    GradientBoostingClassifier, HistGradientBoostingClassifier)

# AdaBoost: weight misclassified samples higher each round
ada = AdaBoostClassifier(
    estimator=DecisionTreeClassifier(max_depth=1),
    n_estimators=200, learning_rate=0.5, random_state=42,
)
ada.fit(X_train, y_train)

# Gradient Boosting: fit each new tree to the residuals of the previous
gb = GradientBoostingClassifier(
    n_estimators=200, learning_rate=0.1, max_depth=3,
    subsample=0.8,        # stochastic GB — adds randomness
    random_state=42,
)
gb.fit(X_train, y_train)

# HistGradientBoosting: faster, native NaN handling, large-data friendly
hgb = HistGradientBoostingClassifier(
    max_iter=200, learning_rate=0.1, max_leaf_nodes=31,
    l2_regularization=0.0, early_stopping=True,
    random_state=42,
)
hgb.fit(X_train, y_train)

Stacking(メタ学習)

Voting のアンサンブルが多様なモデルの予測を平均します — ソフト投票(確率)が通常ハード投票(多数決)に勝ちます。さらに進むのが stacking です:メタモデルが、ベースモデルの予測を最良に組み合わせる方法を学び、しばしば追加の性能を絞り出します。漏れを避けるため、メタモデルはベースモデルの out-of-fold 予測上で学習されます(cv で設定)。最大の利得のためには、多様なベースモデル(異なるアルゴリズム)を使いましょう — 3 つのランダムフォレストの組み合わせは無意味です。

machine-learning
from sklearn.ensemble import StackingClassifier, VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC

# Voting: simple average of predictions (hard=majority, soft=probabilities)
voting = VotingClassifier(
    estimators=[
        ("rf",  RandomForestClassifier(n_estimators=100, random_state=42)),
        ("svc", SVC(probability=True, random_state=42)),
        ("lr",  LogisticRegression(max_iter=1000)),
    ],
    voting="soft",     # use predict_proba
    weights=[2, 1, 1], # weight each model
)

# Stacking: train a meta-model on base model predictions
stacking = StackingClassifier(
    estimators=[
        ("rf",  RandomForestClassifier(n_estimators=100, random_state=42)),
        ("svc", SVC(probability=True, random_state=42)),
        ("lr",  LogisticRegression(max_iter=1000)),
    ],
    final_estimator=LogisticRegression(),  # meta-model
    cv=5,            # use CV predictions to train meta-model (avoids leakage)
    n_jobs=-1,
)
stacking.fit(X_train, y_train)

Voting 対 Stacking 対 Blending

3 つのアンサンブル戦略すべてが多様なモデルを組み合わせ、洗練度が増していきます:voting(最も単純、平均)、blending(ホールドアウトセット上のメタモデル)、stacking(CV 予測上のメタモデル、より堅牢)。実践では stacking が推奨です — CV ベースのメタ特徴がすべての学習データを使い、分散を減らします。blending はより単純で速いですが、メタモデルのためのデータが少なくなります。価値を加えるためには、すべてが多様なベースモデルを要求します。

machine-learning
# Voting:  simple average of predictions
# Stacking: meta-model trained on CV predictions of base models
# Blending: like stacking but meta-model trained on a single holdout set

# Blending (manual implementation):
# 1. Split train into train' and holdout
# 2. Train base models on train'
# 3. Get predictions on holdout
# 4. Train meta-model on (holdout_predictions, holdout_y)
# 5. Retrain base models on full train for final ensemble

from sklearn.model_selection import train_test_split
X_tr, X_hold, y_tr, y_hold = train_test_split(X_train, y_train, test_size=0.3,
                                               random_state=42)

# Train base models on X_tr
rf.fit(X_tr, y_tr); svc.fit(X_tr, y_tr); lr.fit(X_tr, y_tr)

# Get holdout predictions as new features
import numpy as np
holdout_preds = np.column_stack([
    rf.predict_proba(X_hold)[:, 1],
    svc.predict_proba(X_hold)[:, 1],
    lr.predict_proba(X_hold)[:, 1],
])
meta_model = LogisticRegression().fit(holdout_preds, y_hold)

多様性と相関

アンサンブルがメンバーに勝つのは、モデルが相関のない誤りをするときだけです。3 つのモデルがすべて同じ間違いをすれば、アンサンブルもします。予測の相関を測りましょう — 低いほど良いです。多様性を高める方法:アルゴリズムファミリー(木、線形、距離ベース)の混合、異なる特徴の部分集合での学習、異なるハイパーパラメータのレジームの使用。同アルゴリズム・異シードの多様性は弱く、アルゴリズム的な多様性が強いです。

machine-learning
import numpy as np
from scipy.stats import spearmanr

# An ensemble only helps if models make DIFFERENT errors
# Measure prediction correlation between base models
preds = np.column_stack([rf.predict_proba(X_test)[:, 1],
                          svc.predict_proba(X_test)[:, 1],
                          lr.predict_proba(X_test)[:, 1]])
corr = spearmanr(preds).correlation
print("Prediction correlation matrix:")
print(corr)

# Low correlation = diverse models = better ensemble
# High correlation = redundant models = no benefit

# Ways to encourage diversity:
# 1. Different algorithms (tree + linear + nearest-neighbor)
# 2. Different feature subsets
# 3. Different hyperparameters
# 4. Different training samples (bagging)
# 5. Different random seeds (weakest form of diversity)
14

深層学習の基本

PyTorch のテンソルと Autograd

PyTorch のテンソルが、自動微分のために勾配を追跡する numpy 風の配列です。テンソル上で autograd を有効化するのが requires_grad=True で、スカラー上の .backward() 呼び出しがすべての上流テンソルの勾配を計算します。加速のため .to(device) でテンソルを GPU へ移動しましょう。勾配グラフからテンソルを外すのが .detach() です(ロギングや numpy への変換用)。

machine-learning
import torch

# Tensors: like numpy arrays but on GPU and with autograd
x = torch.randn(3, 4, requires_grad=True)
y = torch.randn(4, 2, requires_grad=True)
z = x @ y               # matrix multiply
loss = z.sum()

# Automatic differentiation
loss.backward()         # populate .grad
print(x.grad.shape)     # torch.Size([3, 4])
print(y.grad.shape)     # torch.Size([4, 2])

# Move to GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x = x.to(device)

# Detach from graph (e.g. for logging)
numpy_array = z.detach().cpu().numpy()

学習ループの構造

すべての PyTorch 学習ループが同じ構造を持ちます:zero_grad、forward、loss、backward、step です。dropout と batchnorm の挙動の切り替えが model.train() / model.eval() で、切り替え忘れはサイレントなバグです。推論のため勾配追跡を無効化するのが torch.no_grad() で(メモリと計算を節約します)、バッチは常にモデルと同じデバイスへ移動しましょう。バッチングとシャッフルを扱うのが dataloader で、ループは反復するだけです。

machine-learning
import torch
import torch.nn as nn
import torch.optim as optim

model = nn.Sequential(
    nn.Linear(784, 128), nn.ReLU(),
    nn.Linear(128, 64),  nn.ReLU(),
    nn.Linear(64, 10),
).to(device)

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-3)

for epoch in range(epochs):
    model.train()                            # enable dropout/batchnorm
    for X_batch, y_batch in train_loader:
        X_batch, y_batch = X_batch.to(device), y_batch.to(device)

        optimizer.zero_grad()                # clear old gradients
        logits = model(X_batch)              # forward
        loss = criterion(logits, y_batch)    # compute loss
        loss.backward()                      # backprop
        optimizer.step()                     # update weights

    # Validation
    model.eval()                             # disable dropout/batchnorm
    with torch.no_grad():                    # no gradient tracking
        val_loss, correct = 0, 0
        for X_batch, y_batch in val_loader:
            logits = model(X_batch.to(device))
            val_loss += criterion(logits, y_batch.to(device))
            correct += (logits.argmax(1).cpu() == y_batch).sum().item()
    print(f"Epoch {epoch}: val_loss={val_loss/len(val_loader):.4f}, "
          f"val_acc={correct/len(val_loader.dataset):.4f}")

よくあるレイヤー

隠れ層の基本が Linear + ReLU です。画像には Conv2d + MaxPool、短いシーケンスには LSTM/GRU、長いシーケンスかテキストには Transformer です。学習を安定させるのが BatchNorm で、正則化するのが Dropout です。注意:PyTorch の CrossEntropyLoss が既に log-softmax を適用するため、分類モデルの末尾に Softmax のレイヤーを加えてはいけません — 生の logits を出力しましょう。

machine-learning
import torch.nn as nn

# Linear (fully connected)
nn.Linear(in_features=128, out_features=64)

# Activations
nn.ReLU()        # default for hidden layers
nn.GELU()        # smoother, used in transformers
nn.Sigmoid()     # outputs in (0, 1)
nn.Softmax(dim=1)# multi-class probabilities (built into CrossEntropyLoss)

# Convolution (images)
nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=1)
nn.MaxPool2d(kernel_size=2)   # downsample by 2
nn.BatchNorm2d(32)            # stabilize training
nn.Dropout(p=0.5)             # regularization

# Recurrent (sequences)
nn.LSTM(input_size=64, hidden_size=128, num_layers=2, batch_first=True)

# Transformer (attention)
nn.TransformerEncoderLayer(d_model=512, nhead=8, batch_first=True)

オプティマイザー

最も人気のあるオプティマイザーが Adam です — パラメータごとの適応的な学習率、速い収束、最小限のチューニング。Adam の weight-decay のバグを修正した AdamW が、transformer には推奨です。momentum 付きの SGD が CNN でよりよく汎化できますが、より多くのチューニングが必要です。学習率のスケジューラ(cosine annealing、one-cycle)がしばしば無料の 1〜2% の精度を加えます。最重要のハイパーパラメータが学習率です — まず必ずこれを調整しましょう。

machine-learning
import torch.optim as optim

# SGD with momentum — robust default
optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=1e-4)

# Adam — adaptive, often faster convergence
optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-4)

# AdamW — proper weight decay (preferred over Adam for transformers)
optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

# Learning rate scheduler — reduce LR over training
from torch.optim.lr_scheduler import CosineAnnealingLR, OneCycleLR
scheduler = CosineAnnealingLR(optimizer, T_max=epochs)
# or OneCycleLR for super-convergence (needs careful setup)

# In training loop:
optimizer.step()
scheduler.step()  # update LR each epoch (or batch for OneCycleLR)

過剰適合と正則化

過剰適合:学習損失が下がり続けるのに、検証損失が上がります。学習中にユニットをランダムに無効化し、冗長な表現を強制するのが Dropout です。重みをゼロ方向へ縮めるのが、重み減衰(L2)です。検証損失を監視し、停滞したら止めるのが早期停止です — 必ず最良のチェックポイントを保存しましょう。画像/テキストにとって最も強力な正則化器が、データ拡張です。他の方法が失敗したときの最も簡単な修正が、モデル容量の削減です。

machine-learning
# 1. Dropout — randomly zero out units during training
nn.Dropout(p=0.5)

# 2. Weight decay (L2 regularization) via optimizer
optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)

# 3. Early stopping — stop when validation loss stops improving
best_val, patience, counter = float("inf"), 5, 0
for epoch in range(epochs):
    val_loss = validate(model, val_loader)
    if val_loss < best_val:
        best_val, counter = val_loss, 0
        torch.save(model.state_dict(), "best.pt")  # save best
    else:
        counter += 1
        if counter >= patience:
            print("Early stopping at epoch", epoch)
            break

# 4. Data augmentation (especially for images/text)
# 5. Batch normalization (mild regularizing effect)
# 6. Reduce model capacity (fewer layers/units)
15

評価指標の深掘り

Precision、Recall、F1

precision と recall が、偽陽性と偽陰性の間のトレードオフを捉えます。ビジネスコストに基づき選びましょう:スパムには precision(偽陽性 = 重要なメールの喪失)、がんスクリーニングには recall(偽陰性 = 診断の見逃し)。両者を等しくバランスさせるのが F1 で、傾けられるのが F-beta です — F2 が recall を 2 倍重み付けし、F0.5 が precision を 2 倍重み付けします。F1 だけでなく、precision と recall の両方を必ず報告しましょう。

machine-learning
from sklearn.metrics import (precision_score, recall_score,
    f1_score, fbeta_score)

# Precision: TP / (TP + FP) — of predicted positives, how many are real
# Recall:    TP / (TP + FN) — of actual positives, how many we caught
# F1:        harmonic mean of precision and recall
# F-beta:    weighted (beta > 1 favors recall, < 1 favors precision)

precision = precision_score(y_test, y_pred)
recall    = recall_score(y_test, y_pred)
f1        = f1_score(y_test, y_pred)
f2        = fbeta_score(y_test, y_pred, beta=2.0)   # recall-weighted
f05       = fbeta_score(y_test, y_pred, beta=0.5)   # precision-weighted

# When to use which:
# - Precision matters when false positives are costly (spam filter)
# - Recall matters when false negatives are costly (cancer screening)
# - F2 when recall is more important; F0.5 when precision is more important

ROC-AUC と PR-AUC

ROC-AUC が、モデルが陽性を陰性より上にどれだけよくランクするか測ります — しきい値に依存しないため有用です。precision-recall 曲線の下の面積が PR-AUC(average_precision_score)で、不均衡データではより情報豊かです(ROC-AUC が素晴らしく見えるのに PR-AUC がひどいことがあります)。多クラスでは、'ovr'(one-vs-rest)と 'ovo'(one-vs-one)が AUC を異なり計算します。確信がなければ両方を報告しましょう。動作のしきい値の選択には、Youden の J を使いましょう。

machine-learning
from sklearn.metrics import (roc_auc_score, average_precision_score,
    roc_curve, precision_recall_curve)

# ROC-AUC: probability that model ranks a random positive
#          above a random negative. Threshold-independent.
roc_auc = roc_auc_score(y_test, y_proba)

# PR-AUC (average precision): area under precision-recall curve.
# More informative than ROC-AUC on imbalanced data.
pr_auc = average_precision_score(y_test, y_proba)

# Multiclass ROC-AUC
roc_auc_ovr = roc_auc_score(y_test, y_proba_multi,
                            multi_class="ovr", average="macro")
roc_auc_ovo = roc_auc_score(y_test, y_proba_multi,
                            multi_class="ovo", average="macro")

# Find the optimal threshold (Youden's J = TPR - FPR)
fpr, tpr, thresholds = roc_curve(y_test, y_proba)
j_scores = tpr - fpr
best_threshold = thresholds[j_scores.argmax()]

混同行列の可視化

集計の指標だけでなく、混同行列は必ず可視化しましょう — どのクラスが互いに混同されるか示し、モデルの弱点を明らかにします(数字分類器が 4 と 9 を混同するなど)。クラスごとの recall を見るには(真のクラスの)行ごとの正規化を — クラスが不均衡なとき重要です。これを 1 行にするのが ConfusionMatrixDisplay です。対角線の外のセルが、間違いが集中する場所です。

machine-learning
from sklearn.metrics import (confusion_matrix,
    ConfusionMatrixDisplay)
import matplotlib.pyplot as plt

cm = confusion_matrix(y_test, y_pred)

# Display with sklearn
disp = ConfusionMatrixDisplay(confusion_matrix=cm,
                              display_labels=class_names)
fig, ax = plt.subplots(figsize=(8, 6))
disp.plot(cmap="Blues", ax=ax, values_format="d")  # or ".2%" for normalized
plt.title("Confusion matrix")
plt.show()

# Normalized per row (true class) — see per-class recall
cm_norm = cm.astype(float) / cm.sum(axis=1, keepdims=True)
disp = ConfusionMatrixDisplay(confusion_matrix=cm_norm,
                              display_labels=class_names)
disp.plot(cmap="Blues", values_format=".2%")

回帰指標の総括

複数の指標を報告しましょう:大きな誤差への敏感さには RMSE、典型的な誤差には MAE、外れ値への頑健さには中央値 AE、最悪ケースの SLA には max error、無次元の解釈性には R2 です。歪んだターゲット(所得、価格)では、y の log 変換を試し、log 空間で指標を報告しましょう — これが乗法的な誤差と一致し、分散を安定させます。予測と実績の整合性確認は、散布図で必ず行いましょう。

machine-learning
from sklearn.metrics import (mean_squared_error, mean_absolute_error,
    r2_score, median_absolute_error, max_error,
    explained_variance_score, d2_tweedie_score)

# RMSE (penalizes large errors, same units as y)
rmse = mean_squared_error(y_test, y_pred, squared=False)

# MAE (robust to outliers, same units as y)
mae = mean_absolute_error(y_test, y_pred)

# Median AE (extremely robust to outliers)
med_ae = median_absolute_error(y_test, y_pred)

# Max error (worst single prediction — useful for SLAs)
max_err = max_error(y_test, y_pred)

# R^2 (1=perfect, 0=mean prediction, <0=worse than mean)
r2 = r2_score(y_test, y_pred)

# Explained variance (like R^2 but ignores bias)
evs = explained_variance_score(y_test, y_pred)

ビジネス整合の指標

ML の指標(accuracy、F1、AUC)は、実際に気にかけるもの — ビジネスの成果 — の代理です。ビジネスコストをカスタム指標へ翻訳しましょう:不正の偽陰性は $X の損失、偽陽性は $Y、ランク k の広告クリックは $Z の利益です。代理ではなく本物の目的(利益、救われる命、防止された解約)のため最適化しましょう。カスタムのしきい値最適化が、追加の 0.01 AUC を絞り出すよりしばしば多くの価値を生みます。

machine-learning
# Sometimes the right metric isn't in sklearn — define your own.

# Example 1: Cost matrix (asymmetric costs)
def cost_weighted_error(y_true, y_pred, cost_fp=1, cost_fn=10):
    cm = confusion_matrix(y_true, y_pred)
    tn, fp, fn, tp = cm.ravel()
    return (cost_fp * fp + cost_fn * fn) / len(y_true)

# Example 2: Profit at K (top-K precision weighted by revenue)
def profit_at_k(y_true, y_proba, revenue_per_hit, k=100):
    top_k_idx = np.argsort(y_proba)[::-1][:k]
    hits = y_true[top_k_idx].sum()
    return hits * revenue_per_hit - k * cost_per_contact

# Example 3: Custom threshold optimization
def optimize_threshold_for_profit(y_true, y_proba, profit_matrix):
    best_t, best_profit = 0.5, -float("inf")
    for t in np.linspace(0.01, 0.99, 99):
        y_pred = (y_proba >= t).astype(int)
        profit = profit_matrix(y_true, y_pred)
        if profit > best_profit:
            best_t, best_profit = t, profit
    return best_t, best_profit
16

パイプライン

基本の Pipeline

Pipeline が前処理とモデルリングを単一の推定器へチェーンし、CV 中に前処理が学習分割上でのみ fit されることを保証します(漏れを防ぎます)。デプロイも簡単になります — scaler、imputer、モデルが別々ではなく 1 オブジェクトです。明快さのため、名前付きステップを使いましょう。誠実で再現可能な ML の最もきれいな方法が Pipeline です — 最適化ではなくデフォルトにしましょう。

machine-learning
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestClassifier

pipe = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("scale",  StandardScaler()),
    ("clf",    RandomForestClassifier(random_state=42)),
])

# Use like any estimator
pipe.fit(X_train, y_train)
y_pred = pipe.predict(X_test)
score = pipe.score(X_test, y_test)

# Access steps
pipe.named_steps["clf"]
pipe[:-1].get_feature_names_out()  # see transformed feature names

# Pipelines prevent leakage: each CV fold fits its own preprocessing

ColumnTransformer(異種データ)

ColumnTransformer が、数値列とカテゴリ列に異なる前処理を適用します — 実世界の表形式データには不可欠です。各サブパイプラインが、自分の補完とエンコーディングを処理します。列挙されていない列の破棄が remainder='drop' で、そのまま保持するのが 'passthrough' です。漏れのない CV と異種の前処理を得るには、ColumnTransformer をモデルと共に Pipeline で包みましょう。これが、表形式 ML の本番対応パターンです。

machine-learning
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import (StandardScaler, OneHotEncoder)
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer

numeric_features     = ["age", "income", "score"]
categorical_features = ["city", "occupation"]

# Different preprocessing for different column types
preprocessor = ColumnTransformer(
    transformers=[
        ("num", Pipeline([
            ("impute", SimpleImputer(strategy="median")),
            ("scale",  StandardScaler()),
        ]), numeric_features),
        ("cat", Pipeline([
            ("impute", SimpleImputer(strategy="most_frequent")),
            ("onehot", OneHotEncoder(handle_unknown="ignore")),
        ]), categorical_features),
    ],
    remainder="drop",  # or 'passthrough' to keep other columns
)

full_pipe = Pipeline([
    ("preprocess", preprocessor),
    ("clf", RandomForestClassifier(random_state=42)),
])
full_pipe.fit(X_train, y_train)

チューニング付きの Pipeline

Pipeline は GridSearchCV ときれいに構成できます — 'step__param' の構文で、前処理とモデルのハイパーパラメータを一緒に調整できます。これが、このモデルのための最良の前処理の組み合わせを見つけます。これは、単独での最良の前処理としばしば異なります。モデルだけでなく、常にフルパイプラインを調整しましょう。共同チューニングがより誠実で(前処理を選ぶためにテストデータを覗かない)、しばしばより良い構成を見つけます。

machine-learning
from sklearn.model_selection import GridSearchCV

# Reference nested parameters with 'step__param' syntax
param_grid = {
    "preprocess__num__impute__strategy": ["mean", "median"],
    "clf__n_estimators": [50, 100, 200],
    "clf__max_depth":    [3, 5, 10, None],
}

grid = GridSearchCV(full_pipe, param_grid, cv=5, scoring="f1", n_jobs=-1)
grid.fit(X_train, y_train)
print("Best params:", grid.best_params_)

# Tune preprocessing AND model together — finds the best combo
# e.g. median imputation + 100 trees + max_depth=10

カスタム Transformer

カスタム transformer により、ドメイン固有の前処理(log 変換、日付特徴の抽出、テキストの清掃)が、再利用可能でパイプライン互換のコンポーネントへカプセル化されます。BaseEstimator と TransformerMixin を継承し、fit(多くは self を返すだけ)と transform を実装しましょう。これで、特徴エンジニアリングがバージョン管理され、テスト可能で、漏れがなくなります — ノートブックにロジックを散らすよりはるかに良いです。1 回限りの関数には FunctionTransformer を。

machine-learning
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np

class LogTransformer(BaseEstimator, TransformerMixin):
    def __init__(self, columns=None):
        self.columns = columns

    def fit(self, X, y=None):
        return self  # nothing to fit

    def transform(self, X):
        X = X.copy()
        if self.columns is None:
            return np.log1p(X)
        X[self.columns] = np.log1p(X[self.columns])
        return X

# Use in a pipeline
pipe = Pipeline([
    ("log",  LogTransformer(columns=["income", "price"])),
    ("scale", StandardScaler()),
    ("clf",   LogisticRegression()),
])

# For more complex logic, use FunctionTransformer or write a full class

Pipeline の保存と読み込み

sklearn パイプラインのシリアライズの標準が joblib(pickle ではない)です — numpy 配列を効率的に扱い、圧縮をそのままサポートします。本番では sklearn のバージョンを固定しましょう:あるバージョンで保存されたモデルは、別のバージョンでロードできる保証がありません。クロス言語のデプロイ(Java/Go から Python モデルを提供)には、skl2onnx で ONNX へ変換しましょう。推論時に前処理が同一になるよう、モデルだけではなく必ずフルパイプラインを保存しましょう。

machine-learning
import joblib

# Save the entire fitted pipeline
joblib.dump(full_pipe, "model.pkl")

# Later (e.g. in a web service)
loaded = joblib.load("model.pkl")
predictions = loaded.predict(new_data)

# Why joblib over pickle?
# - More efficient for numpy arrays (which sklearn models contain)
# - Handles objects with large numerical arrays via compression

# Version compatibility:
# - sklearn versions must match between save and load in production
# - Pin sklearn in requirements.txt: scikit-learn==1.4.2

# For cross-language deployment, use ONNX:
# import skl2onnx
# onx = skl2onnx.convert_sklearn(full_pipe, ...)
17

モデルの永続化

joblib 対 pickle

sklearn モデルには joblib を使いましょう — numpy 配列向けに最適化され、圧縮をそのままサポートします。任意の Python オブジェクトのフォールバックが pickle です。両者に同じセキュリティの注意点があります:信頼できない pickle/joblib ファイルを NEVER でロードしてはいけません — デシリアライズ時に任意のコードを実行できます。信頼できない環境へのモデルの提供には、ONNX か入力検証付きのモデルサーバーを使いましょう。

machine-learning
import joblib
import pickle

# joblib — preferred for sklearn (efficient with numpy arrays)
joblib.dump(model, "model.joblib", compress=3)
model = joblib.load("model.joblib")

# pickle — standard library, works for any picklable object
with open("model.pkl", "wb") as f:
    pickle.dump(model, f)
with open("model.pkl", "rb") as f:
    model = pickle.load(f)

# Compress to save disk space (joblib supports it natively)
joblib.dump(model, "model.joblib", compress=("xz", 3))

# Load partially for inspection without full deserialize
# (advanced, not commonly needed)

モデルのバージョニング

モデルはメタデータ付きで必ずバージョン管理しましょう:フレームワークのバージョン(sklearn、python)、特徴のリスト、学習データのハッシュ、指標、git commit、タイムスタンプ。これで本番問題のデバッグが扱いやすくなります — モデルが違う振る舞いをしたとき、メタデータを比較して何が変わったか分かります。セマンティックバージョニングを使いましょう:再学習は patch、新機能は minor、破壊的変更(古い予測を壊す新しい前処理)は major です。

machine-learning
# Save metadata alongside the model artifact
import joblib, json
from datetime import datetime

metadata = {
    "model_type": "RandomForestClassifier",
    "sklearn_version": sklearn.__version__,
    "python_version": sys.version,
    "features": list(X_train.columns),
    "target": "churn",
    "metrics": {"f1": 0.842, "roc_auc": 0.913},
    "trained_at": datetime.utcnow().isoformat(),
    "data_hash": hashlib.md5(pd.util.hash_pandas_object(X_train).values).hexdigest(),
    "git_commit": subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip(),
}

joblib.dump({"model": model, "metadata": metadata}, "model_v1.2.0.joblib")

# Convention: semantic versioning
# v1.0.0 -> initial release
# v1.1.0 -> retrained on new data (backward compatible)
# v2.0.0 -> breaking change (new features, new preprocessing)

ONNX エクスポート

ONNX がクロスプラットフォームのモデル形式です — sklearn パイプラインを一度変換すれば、Python の依存なしでどこでも(Python、C++、Java、JavaScript、Go)実行できます。本番に理想的です:学習環境(Python)と提供環境(Go のマイクロサービスなど)が異なれます。多くのモデルでは、ONNX ランタイムが sklearn より速いです。注意:ONNX に相当物のない sklearn の transformer やモデルもあります — コミットする前に skl2onnx の対応を確認しましょう。

machine-learning
# pip install skl2onnx onnxruntime
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType
import onnxruntime as rt

# Convert sklearn pipeline to ONNX
initial_type = [("float_input", FloatTensorType([None, X_train.shape[1]]))]
onnx_model = convert_sklearn(full_pipe, initial_types=initial_type,
                              target_opset=15)

with open("model.onnx", "wb") as f:
    f.write(onnx_model.SerializeToString())

# Run inference in any language (Python, C++, Java, JS, Go, ...)
sess = rt.InferenceSession("model.onnx")
input_name = sess.get_inputs()[0].name
predictions = sess.run(None, {input_name: X_test.astype(np.float32)})[0]

# Benefits: no Python at inference, fast, cross-platform

モデルモニタリングの基本

世界が変わるにつれ、本番でモデルは劣化します — ドリフトを監視しましょう。データドリフト:入力特徴の分布の変化(ユーザーの人口統計の変化など)。コンセプトドリフト:特徴とターゲットの関係の変化(不正パターンの進化など)。単純で解釈可能なドリフト指標が PSI(Population Stability Index)で — 0.25 を超える値が再学習を求めます。ドリフトのアラートと定期的な再学習のスケジュールを組み合わせ、事後分析を可能にするため予測は必ずログに残しましょう。

machine-learning
# After deployment, monitor for:
# 1. Data drift: input distribution changes
# 2. Concept drift: P(y|X) changes
# 3. Prediction drift: output distribution changes
# 4. Performance degradation: metric drops over time

# Simple data drift check: PSI (Population Stability Index)
def psi(expected, actual, bins=10):
    expected_pct = np.histogram(expected, bins=bins)[0] / len(expected)
    actual_pct   = np.histogram(actual,   bins=bins)[0] / len(actual)
    # Avoid log(0)
    expected_pct = np.clip(expected_pct, 1e-4, None)
    actual_pct   = np.clip(actual_pct,   1e-4, None)
    return np.sum((actual_pct - expected_pct) * np.log(actual_pct / expected_pct))

# PSI < 0.1: stable, 0.1-0.25: minor drift, > 0.25: significant drift
for col in X.columns:
    score = psi(X_train[col], X_new[col])
    if score > 0.25:
        print(f"Drift detected in {col}: PSI={score:.3f}")

再学習の戦略

データがどれだけ速く変わるかに基づき、再学習の戦略を選びましょう。スケジュール(最も単純、予測可能)。性能トリガー(反応的、必要なときだけ再学習)。ドリフトトリガー(性能低下の前の早期警報)。オンライン学習(不正や推薦のような速く変わるデータのための継続的な更新)。新しいモデルは最近のデータで現在のものと必ず検証し、ライブ予測を比較するためにシャドウデプロイし、指標が後退したら自動ロールバックを持たせましょう。

machine-learning
# 1. Scheduled retraining (simplest)
#    Retrain weekly/monthly regardless of performance
schedule = "0 2 * * 0"  # every Sunday at 2am

# 2. Performance-triggered retraining
#    Retrain when a metric drops below threshold
if current_f1 < production_f1 * 0.95:  # 5% drop
    trigger_retrain()

# 3. Drift-triggered retraining
#    Retrain when PSI exceeds threshold
if max_psi > 0.25:
    trigger_retrain()

# 4. Online learning (incremental updates)
from sklearn.linear_model import SGDClassifier
model = SGDClassifier()
for X_batch, y_batch in stream:
    model.partial_fit(X_batch, y_batch, classes=[0, 1])

# Always:
# - Validate new model beats old on recent data before promoting
# - Shadow deploy: run new model in parallel, compare predictions
# - Roll back automatically if metrics regress
# - Keep training data fresh (drop old samples)
18

正則化

L1(Lasso)対 L2(Ridge)

L1(Lasso)が絶対値のペナルティを加え、いくつかの係数を正確にゼロへ押し込みます — 組み込みの特徴選択で、多くの特徴が無関係なときに理想的です。L2(Ridge)が二乗のペナルティを加え係数を滑らかに縮めます — 多くの特徴がそれぞれ少しずつ効くときに向きます。両者を混ぜた ElasticNet が、特徴が相関しているときに推奨です(Lasso 単独はランダムに 1 つを選び他をゼロにします)。ペナルティが公平になるよう、まず必ず特徴をスケールしましょう。

machine-learning
from sklearn.linear_model import Lasso, Ridge, ElasticNet
import numpy as np

# L1 (Lasso): penalty = alpha * sum(|coef|)
# Drives some coefficients to exactly 0 -> sparse -> feature selection
lasso = Lasso(alpha=0.1)
lasso.fit(X_train_scaled, y_train)
print("Non-zero coefs:", (lasso.coef_ != 0).sum(), "/", len(lasso.coef_))

# L2 (Ridge): penalty = alpha * sum(coef^2)
# Shrinks coefficients smoothly toward 0, keeps all features
ridge = Ridge(alpha=1.0)
ridge.fit(X_train_scaled, y_train)

# ElasticNet: mix of L1 and L2
# penalty = alpha * (l1_ratio * L1 + (1 - l1_ratio) * L2)
en = ElasticNet(alpha=0.1, l1_ratio=0.5)
en.fit(X_train_scaled, y_train)

# Rule of thumb:
# - L1: many features, only a few matter (sparse)
# - L2: many features, all matter a little
# - ElasticNet: correlated features (Lasso picks one randomly)

木の正則化

木にとって最も強力な正則化器が max_depth と min_samples_leaf です — 木が個々のサンプルを記憶するのを防ぎます。コスト複雑性の剪定を行うのが ccp_alpha です(より原理的な事後の剪定)。ランダムフォレストでは、ランダム性経由で正則化を加えるのが max_features と bootstrap です。勾配ブースティングでは、learning_rate と early_stopping が決定的です(低い LR + 早期停止 + 十分な木が通常勝ちます)。さらに確率性経由の正則化を加えるのが、subsample と colsample_bytree です。

machine-learning
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier

# Decision tree regularization hyperparameters
tree = DecisionTreeClassifier(
    max_depth=5,             # limit tree depth (strongest lever)
    min_samples_split=20,    # min samples to split a node
    min_samples_leaf=10,     # min samples per leaf
    max_leaf_nodes=20,       # cap total leaves
    max_features="sqrt",     # features considered per split
    ccp_alpha=0.01,          # cost-complexity pruning
)

# Random forest adds more regularization via:
rf = RandomForestClassifier(
    n_estimators=200,
    max_depth=None,
    min_samples_leaf=5,
    max_features="sqrt",     # random feature subset per split
    bootstrap=True,          # bagging
    max_samples=0.8,         # subsample ratio
)

# For boosting (XGBoost), also use:
# - learning_rate (smaller = more regularization)
# - subsample, colsample_bytree (randomness)
# - reg_lambda, reg_alpha (L2/L1 on leaf weights)
# - gamma (minimum loss reduction to split)
# - early_stopping_rounds

Dropout と BatchNorm(深層学習)

Dropout が学習中に活性をランダムにゼロにし、ネットワークが冗長な表現を学ぶことを強制します — 強力な正則化器です。大きなレイヤーでは高く、小さいレイヤーでは低く、出力ではしばしばゼロにします。バッチごとに活性を正規化するのが BatchNorm で、学習を安定させ、(バッチ統計がノイズを加えることで)穏やかな正則化効果も加えます。思い出しましょう:dropout と batchnorm は train 対 eval で異なる振る舞いをするため、推論では必ず model.eval() を、学習再開には model.train() を呼びましょう。

machine-learning
import torch.nn as nn

model = nn.Sequential(
    nn.Linear(784, 256),
    nn.BatchNorm1d(256),     # normalize activations -> faster, stable training
    nn.ReLU(),
    nn.Dropout(0.5),         # randomly zero 50% of activations during training

    nn.Linear(256, 128),
    nn.BatchNorm1d(128),
    nn.ReLU(),
    nn.Dropout(0.3),         # less dropout closer to output

    nn.Linear(128, 10),      # no dropout before output (or use very low)
)

# IMPORTANT: dropout is OFF during inference (model.eval())
# BatchNorm uses batch stats in training and running stats in eval

# Common patterns:
# - Higher dropout in big layers, lower in small layers
# - No dropout right after input or right before output
# - BatchNorm before activation (debated; try both)

早期停止

早期停止が、検証損失の改善が止まったとき学習を止め、過剰適合を防ぎ計算を節約します。最終モデルではなく、最良のモデル(最も低い val 損失)を必ず保存しましょう — 最終モデルは過剰適合しているかもしれません。許容する非改善エポック数の制御が patience です。勾配ブースティングでは、木レベルで同じことをするのが early_stopping_rounds です。最高の価値と最低の労力の正則化器の一つが早期停止です — 深層学習には必ず使いましょう。

machine-learning
import torch

best_val_loss = float("inf")
patience, counter = 5, 0
best_state = None

for epoch in range(max_epochs):
    train_loss = train_one_epoch(model, train_loader, optimizer, criterion)
    val_loss   = validate(model, val_loader, criterion)

    if val_loss < best_val_loss:
        best_val_loss = val_loss
        counter = 0
        best_state = {k: v.clone() for k, v in model.state_dict().items()}
    else:
        counter += 1
        if counter >= patience:
            print(f"Early stopping at epoch {epoch}")
            break

# Restore the best model
model.load_state_dict(best_state)

# For XGBoost/LightGBM, use early_stopping_rounds:
# model.fit(X_train, y_train,
#           eval_set=[(X_val, y_val)],
#           early_stopping_rounds=20)

データ拡張

ラベル付きデータが限られているときの最も強力な正則化器がデータ拡張です — ラベルを保つ変換で dataset を合成的に拡大します。画像:反転、切り出し、色のジッター、回転(ドメインに適したものに — 医療の X 線は反転せず、自然画像は反転する)。テキスト:同義語の置換、逆翻訳、ランダムな削除。表形式:SMOTE(不均衡)か mixup(回帰)。データ拡張が実質、無料のラベル付きデータを与えます。

machine-learning
# Images (torchvision)
import torchvision.transforms as T

train_transform = T.Compose([
    T.RandomResizedCrop(224),
    T.RandomHorizontalFlip(),
    T.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
    T.RandomRotation(10),
    T.ToTensor(),
    T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

# Text (NLPAug or simple Python)
import random
def augment_text(text):
    # Synonym replacement, random deletion, back-translation
    words = text.split()
    if random.random() < 0.3:
        idx = random.randrange(len(words))
        words[idx] = synonym(words[idx])
    if random.random() < 0.2:
        words = [w for w in words if random.random() > 0.1]
    return " ".join(words)

# Tabular (SMOTE for imbalance, mixup for regression)
# mixup: X_mix = alpha*X1 + (1-alpha)*X2, y_mix = alpha*y1 + (1-alpha)*y2

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.