scikit-learn について
Python の機械学習実践者向けに、scikit-learn の共通する fit、transform、predict インターフェースを解説するガイドです。従来型機械学習の前処理、モデル評価、調整の流れを扱います。
主な機能
- 01分類、回帰、クラスタリング
- 02データのスケーリング、エンコード、欠損値補完
- 03Pipeline による前処理とモデルの統合
- 04交差検証とモデル評価
- 05グリッドサーチと次元削減
活用シーン
- 01表形式データの分類モデル構築
- 02モデル比較とハイパーパラメーター調整
- 03生データからモデル用特徴量を作成
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ tondevrel/ scientific-agent-skills --skill scikit-learnインストール後、Claude Code で/scikit-learnを入力して読み込まれたか確認します。
詳細
scikit-learn - Python での機械学習
古典的な機械学習のための堅牢なライブラリです。統一された API を備えており、すべてのオブジェクトが学習、変換、予測に同じインターフェースを使用します。
使用する場面
- 分類:カテゴリを判定します(スパムと正常メール、病気の診断)。
- 回帰:連続値を予測します(住宅価格、株価の推移)。
- クラスタリング:類似したオブジェクトをグループ化します(市場のセグメンテーション、画像圧縮)。
- 次元削減:情報を保ちながら特徴量の数を減らします(PCA、可視化)。
- モデル選択:モデルを比較し、ハイパーパラメーターを調整します(交差検証、グリッドサーチ)。
- 前処理:生データを特徴量に変換します(スケーリング、エンコーディング、欠損値補完)。
リファレンスドキュメント
公式ドキュメント:https://scikit-learn.org/stable/
ユーザーガイド:https://scikit-learn.org/stable/user_guide.html
検索パターン:sklearn.pipeline.Pipeline、sklearn.model_selection、sklearn.ensemble、sklearn.preprocessing
基本原則
「Estimator」インターフェース
- エスティメーター:
fit(X, y)を実装します。データから学習します。 - トランスフォーマー:
transform(X)(およびfit_transform(X))を実装します。データを変更します。 - 予測器:
predict(X)を実装します。新しいデータに対する推定値を返します。
scikit-learn を使う場面
- 表形式データ(Excel のようなデータ、CSV)。
- 従来型の ML(ランダムフォレスト、SVM、線形モデル)。
- 特徴量エンジニアリングとパイプラインの自動化。
- 小規模から中規模のデータセット。
使用しない場面
- ディープラーニング/ニューラルネットワーク(PyTorch または TensorFlow を使用してください)。
- 大規模な自然言語処理(spaCy または HuggingFace を使用してください)。
- 大規模な「ビッグデータ」(Spark MLlib または Dask-ML を使用してください)。
- リアルタイムのストリーミング予測(専用の推論エンジンを検討してください)。
クイックリファレンス
インストール
pip install scikit-learn
標準的なインポート
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.metrics import classification_report, mean_squared_error
基本パターン - 学習/予測
from sklearn.ensemble import RandomForestClassifier
# 1. Prepare data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# 2. Instantiate and fit
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
# 3. Predict and evaluate
predictions = model.predict(X_test)
print(classification_report(y_test, predictions))
重要なルール
✅ すること
- 何よりも先に分割する - データの特性を調べる前に、必ず
train_test_splitを使用してください。 - パイプラインを使う - 前処理とモデリングを組み合わせて、データリークを防ぎます。
- データをスケーリングする - SVM、KNN、線形回帰などのモデルでは、特徴量のスケーリングが必要です。
- クラスの不均衡を確認する - 分類では
train_test_splitにstratify=yを指定してください。 - 交差検証する - 単一の訓練/テスト分割を過信せず、
cross_val_scoreを使用してください。 - 欠損値を処理する - モデルの学習前に
SimpleImputerなどを使用してください。 - カテゴリを標準化する - 名義データには
OneHotEncoder、順序データにはOrdinalEncoderを使用してください。
❌ しないこと
- テストデータで学習する - テストセットに対して
.fit()や.fit_transform()を呼び出さないでください。 - カテゴリデータをそのまま使う - Scikit-learn には数値入力が必要です。先に文字列をエンコードしてください。
- クラスの不均衡を無視する - 不均衡なデータセットでは正解率は誤解を招くため、F1 スコアまたは AUC を使用してください。
- 過学習させる - テストスコアが完璧になるまでハイパーパラメーターの調整を続けないでください。
- ランダム状態を無視する - 実験の再現性を確保するため、
random_stateを設定してください。
アンチパターン(絶対に避ける)
# ❌ BAD: Data Leakage (Fitting scaler on the whole dataset)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X) # Data from "future" test set leaks into training!
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y)
# ✅ GOOD: Fit scaler only on training data
X_train, X_test, y_train, y_test = train_test_split(X, y)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test) # Use training mean/std
# ❌ BAD: Repeating preprocessing manually
# (Error-prone and hard to maintain)
# ✅ GOOD: Use Pipelines (Automates everything safely)
pipe = Pipeline([
('scaler', StandardScaler()),
('model', RandomForestClassifier())
])
pipe.fit(X_train, y_train)
前処理(sklearn.preprocessing)
スケーリングとエンコーディング
from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder
# Scaling numerical data
scaler = StandardScaler()
X_num_scaled = scaler.fit_transform(X_numeric)
# Encoding categorical data
encoder = OneHotEncoder(sparse_output=False, handle_unknown='ignore')
X_cat_encoded = encoder.fit_transform(X_categorical)
# Handling missing values
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(strategy='median')
X_imputed = imputer.fit_transform(X_with_nan)
Column Transformer(推奨の方法)
from sklearn.compose import ColumnTransformer
numeric_features = ['age', 'salary']
categorical_features = ['city', 'job_type']
preprocessor = ColumnTransformer(
transformers=[
('num', StandardScaler(), numeric_features),
('cat', OneHotEncoder(), categorical_features)
])
# Now use this in a pipeline
pipeline = Pipeline([
('prep', preprocessor),
('clf', LogisticRegression())
])
分類
よく使われるアルゴリズム
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import GradientBoostingClassifier
# Logistic Regression (Baseline)
log_reg = LogisticRegression(max_iter=1000)
# Support Vector Machine
svm = SVC(kernel='rbf', probability=True)
# Gradient Boosting
gb = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1)
回帰
よく使われるアルゴリズム
from sklearn.linear_model import Ridge, Lasso, ElasticNet
from sklearn.ensemble import RandomForestRegressor
# Regularized Linear Models
ridge = Ridge(alpha=1.0) # L2
lasso = Lasso(alpha=0.1) # L1
# Non-linear Regression
rf_reg = RandomForestRegressor(n_estimators=100, max_depth=10)
モデル評価
指標
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, r2_score, mean_absolute_error
# Classification
acc = accuracy_score(y_true, y_pred)
f1 = f1_score(y_true, y_pred, average='weighted')
# Regression
r2 = r2_score(y_true, y_pred)
mae = mean_absolute_error(y_true, y_pred)
交差検証
from sklearn.model_selection import cross_val_score
scores = cross_val_score(pipeline, X, y, cv=5, scoring='f1_macro')
print(f"Mean F1: {scores.mean():.4f} (+/- {scores.std():.4f})")
ハイパーパラメーターの調整
グリッドサーチとランダムサーチ
from sklearn.model_selection import GridSearchCV
param_grid = {
'clf__n_estimators': [50, 100, 200],
'clf__max_depth': [None, 10, 20],
'clf__min_samples_split': [2, 5]
}
grid_search = GridSearchCV(pipeline, param_grid, cv=3, scoring='accuracy', n_jobs=-1)
grid_search.fit(X_train, y_train)
print(f"Best params: {grid_search.best_params_}")
best_model = grid_search.best_estimator_
次元削減
PCA(主成分分析)
from sklearn.decomposition import PCA
# Reduce to 2 components for visualization
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
print(f"Explained variance ratio: {pca.explained_variance_ratio_}")
クラスタリング
K-Means と DBSCAN
from sklearn.cluster import KMeans, DBSCAN
# K-Means (Requires specifying K)
kmeans = KMeans(n_clusters=3, n_init='auto')
clusters = kmeans.fit_predict(X)
# DBSCAN (Density-based, finds K automatically)
dbscan = DBSCAN(eps=0.5, min_samples=5)
clusters = dbscan.fit_predict(X)
実践的なワークフロー
1. エンドツーエンドの分類パイプライン
def build_and_train_model(X, y):
# 1. Identify types
num_cols = X.select_dtypes(include=['int64', 'float64']).columns
cat_cols = X.select_dtypes(include=['object', 'category']).columns
# 2. Setup Preprocessing
preprocessor = ColumnTransformer([
('num', StandardScaler(), num_cols),
('cat', OneHotEncoder(handle_unknown='ignore'), cat_cols)
])
# 3. Create Pipeline
clf = Pipeline([
('preprocessor', preprocessor),
('classifier', RandomForestClassifier(random_state=42))
])
# 4. Train
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y)
clf.fit(X_train, y_train)
return clf, X_test, y_test
# model, X_test, y_test = build_and_train_model(df.drop('target', axis=1), df['target'])
2. カスタム特徴量エンジニアリング(トランスフォーマー)
from sklearn.base import BaseEstimator, TransformerMixin
class LogTransformer(BaseEstimator, TransformerMixin):
def __init__(self, columns=None):
self.columns = columns
def fit(self, X, y=None):
return self
def transform(self, X):
X_copy = X.copy()
for col in self.columns:
X_copy[col] = np.log1p(X_copy[col])
return X_copy
パフォーマンスの最適化
n_jobs の使用
# Use all CPU cores for training/tuning
model = RandomForestClassifier(n_jobs=-1)
grid = GridSearchCV(model, param_grid, n_jobs=-1)
大規模データの処理(partial_fit)
from sklearn.linear_model import SGDClassifier
# Online learning (incremental fit)
model = SGDClassifier()
for X_chunk, y_chunk in data_stream:
model.partial_fit(X_chunk, y_chunk, classes=np.unique(y_all))
よくある落とし穴と解決策
クラスの不均衡
# ❌ Problem: Model predicts only the majority class
# ✅ Solution: Adjust class weights
model = RandomForestClassifier(class_weight='balanced')
# OR use SMOTE from imbalanced-learn library
収束に関する警告
# ❌ Problem: "ConvergenceWarning: Liblinear failed to converge"
# ✅ Solution: Increase max_iter or scale data
model = LogisticRegression(max_iter=2000)
# Often solved by applying StandardScaler first!
テストセットに含まれ、トレーニングセットに含まれないカテゴリ値
# ❌ Problem: ValueError when unseen categories appear in test
# ✅ Solution: Use handle_unknown in OneHotEncoder
encoder = OneHotEncoder(handle_unknown='ignore')
Scikit-learn は Python の ML の基盤です。その API は非常に成功しているため、ほかの多くのライブラリ(XGBoost、LightGBM)がその API を模倣しています。
コメント
Markdown 対応