2.

scikit-learn 入門クイックスタート完全ガイド

編集
この記事の要点
  • scikit-learn は Python の機械学習デファクト標準ライブラリ。pip install scikit-learn で導入
  • 全モデルが estimator API で統一: fit() / predict() / score()
  • 基本フロー: データ準備 → train_test_split → モデル選択 → fit()predict() → 評価
  • Pipeline で前処理 + モデルを一体化、GridSearchCV でハイパーパラメータ自動探索
  • 主要モデル: LogisticRegression / SVM / RandomForest / KMeans / PCA。Pandas と相性抜群

scikit-learn とは

scikit-learn(sklearn)は、Python 用の機械学習ライブラリです。線形回帰、分類、クラスタリング、次元削減、モデル評価まで、機械学習で必要な処理の大半を統一された API で提供します。NumPy / SciPy / matplotlib と組み合わせて、エンドツーエンドの機械学習パイプラインを書けます。

カテゴリ代表的なモデル
分類LogisticRegression, SVC, RandomForestClassifier, KNeighborsClassifier
回帰LinearRegression, Ridge, Lasso, RandomForestRegressor, GradientBoostingRegressor
クラスタリングKMeans, DBSCAN, AgglomerativeClustering
次元削減PCA, TSNE, TruncatedSVD
前処理StandardScaler, OneHotEncoder, LabelEncoder, SimpleImputer
モデル選択train_test_split, cross_val_score, GridSearchCV

STEP1: インストール

# 仮想環境を作る(推奨)
python -m venv venv
source venv/bin/activate    # Windows は venv\Scripts\activate

# scikit-learn と関連ライブラリ
pip install scikit-learn pandas numpy matplotlib jupyter

# バージョン確認
python -c "import sklearn; print(sklearn.__version__)"
# 1.4.x 以上を推奨

STEP2: 最小サンプル(iris データの分類)

機械学習の Hello World、アヤメ品種分類:

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

# 1. データを読み込む
iris = load_iris()
X, y = iris.data, iris.target
print(X.shape, y.shape)         # (150, 4) (150,)
print(iris.feature_names)        # 萼長, 萼幅, 花弁長, 花弁幅
print(iris.target_names)         # setosa, versicolor, virginica

# 2. 訓練データとテストデータに分割
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 3. モデルを作って学習
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)

# 4. 予測
y_pred = model.predict(X_test)

# 5. 評価
accuracy = model.score(X_test, y_test)
print(f'正解率: {accuracy:.3f}')      # 約 0.97

estimator API の統一

scikit-learn の最大の強みは、すべてのモデルが同じ APIで扱える点です。LogisticRegression を SVM に差し替えても、コードはほとんど変えなくて済みます:

from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier

models = {
    'LogReg':  LogisticRegression(max_iter=200),
    'SVM':     SVC(kernel='rbf'),
    'RF':      RandomForestClassifier(n_estimators=100),
    'KNN':     KNeighborsClassifier(n_neighbors=5),
}

for name, model in models.items():
    model.fit(X_train, y_train)
    score = model.score(X_test, y_test)
    print(f'{name}: {score:.3f}')
メソッド意味
fit(X, y)モデルを訓練する
predict(X)新しいデータの予測
predict_proba(X)確率付き予測(分類器)
score(X, y)精度(分類は accuracy、回帰は R²)
transform(X)変換(前処理・次元削減)
fit_transform(X)fit と transform を同時に

前処理

機械学習モデルの多くは、入力スケールに敏感です。標準化カテゴリ変換を行います:

from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer

# 標準化(平均 0、標準偏差 1)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled  = scaler.transform(X_test)   # ★ test には fit しない

# カテゴリの One-Hot エンコーディング
encoder = OneHotEncoder(sparse_output=False)
X_cat_encoded = encoder.fit_transform([['赤'], ['青'], ['赤'], ['緑']])

# 欠損値の補完
imputer = SimpleImputer(strategy='mean')
X_filled = imputer.fit_transform([[1, 2], [None, 3], [4, None]])

Pipeline で一体化

前処理 + モデルを 1 つのオブジェクトにまとめると、テストデータへの適用やデプロイが格段に楽になります:

from sklearn.pipeline import Pipeline

pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('clf',    LogisticRegression(max_iter=200)),
])

# Pipeline は fit / predict / score を持つ普通の estimator
pipe.fit(X_train, y_train)
pipe.score(X_test, y_test)
y_pred = pipe.predict(X_test)

GridSearchCV でハイパーパラメータ探索

from sklearn.model_selection import GridSearchCV

param_grid = {
    'clf__C':      [0.1, 1.0, 10.0],
    'clf__solver': ['lbfgs', 'liblinear'],
}

grid = GridSearchCV(pipe, param_grid, cv=5, scoring='accuracy', n_jobs=-1)
grid.fit(X_train, y_train)

print('Best params:', grid.best_params_)
print('Best score :', grid.best_score_)
print('Test score :', grid.score(X_test, y_test))

クロスバリデーション

from sklearn.model_selection import cross_val_score, KFold

scores = cross_val_score(pipe, X, y, cv=5, scoring='accuracy')
print(f'5-fold CV: {scores.mean():.3f} ± {scores.std():.3f}')

# 層化サンプリング(分類問題で推奨)
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(pipe, X, y, cv=skf)

評価指標(分類)

from sklearn.metrics import (
    classification_report, confusion_matrix, accuracy_score,
    precision_score, recall_score, f1_score, roc_auc_score
)

y_pred = pipe.predict(X_test)

print(classification_report(y_test, y_pred, target_names=iris.target_names))
print(confusion_matrix(y_test, y_pred))

# 個別指標
print('Accuracy:', accuracy_score(y_test, y_pred))
print('F1 macro:', f1_score(y_test, y_pred, average='macro'))

Pandas との連携

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder

# CSV を読み込み
df = pd.read_csv('titanic.csv')

# 特徴量とターゲットを分離
X = df.drop('survived', axis=1)
y = df['survived']

# 数値とカテゴリで別の前処理
preprocessor = ColumnTransformer([
    ('num', StandardScaler(), ['age', 'fare']),
    ('cat', OneHotEncoder(handle_unknown='ignore'), ['sex', 'class']),
])

pipe = Pipeline([
    ('pre', preprocessor),
    ('clf', RandomForestClassifier(n_estimators=200)),
])

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
pipe.fit(X_train, y_train)
print(pipe.score(X_test, y_test))

モデルの保存と読み込み

import joblib

# 保存
joblib.dump(pipe, 'model.joblib')

# 読み込み
loaded = joblib.load('model.joblib')
loaded.predict(X_test[:5])

FAQ

Q: TensorFlow や PyTorch との違いは?
A: scikit-learn は古典的機械学習に特化(決定木、SVM、線形モデルなど)。深層学習は TensorFlow / PyTorch を使います。両者は併用します。

Q: データ量が多いと遅い
A: n_jobs=-1 で並列化、HistGradientBoostingClassifierLightGBM / XGBoost 等の高速代替を検討。

Q: モデルの解釈をしたい
A: feature_importances_(RF / GBDT)、coef_(線形)、SHAP や LIME ライブラリと組み合わせます。

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. インストール方法(Linux)
  2. 入門者向けクイックスタート

最近更新/作成されたページ