MNIST 多項ロジスティック回帰

Machine LearningMachine LearningBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、MNISTデータセットからの手書き数字を分類するためにロジスティック回帰アルゴリズムをどのように使用するかを学びます。MNIST数字分類タスクのサブセットに対してL1ペナルティを付けた多項ロジスティック回帰を適合させるために、SAGAアルゴリズムを使用します。

VMのヒント

VMの起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebookを使って練習しましょう。

時々、Jupyter Notebookが読み込み終了するまで数秒待つ必要がある場合があります。Jupyter Notebookの制限により、操作の検証は自動化できません。

学習中に問題に遭遇した場合は、Labbyにお問い合わせください。セッション後にフィードバックを提供してください。そうすれば、迅速に問題を解決します。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL sklearn(("Sklearn")) -.-> sklearn/CoreModelsandAlgorithmsGroup(["Core Models and Algorithms"]) sklearn(("Sklearn")) -.-> sklearn/DataPreprocessingandFeatureEngineeringGroup(["Data Preprocessing and Feature Engineering"]) sklearn(("Sklearn")) -.-> sklearn/ModelSelectionandEvaluationGroup(["Model Selection and Evaluation"]) sklearn(("Sklearn")) -.-> sklearn/UtilitiesandDatasetsGroup(["Utilities and Datasets"]) ml(("Machine Learning")) -.-> ml/FrameworkandSoftwareGroup(["Framework and Software"]) sklearn/CoreModelsandAlgorithmsGroup -.-> sklearn/linear_model("Linear Models") sklearn/DataPreprocessingandFeatureEngineeringGroup -.-> sklearn/preprocessing("Preprocessing and Normalization") sklearn/ModelSelectionandEvaluationGroup -.-> sklearn/model_selection("Model Selection") sklearn/UtilitiesandDatasetsGroup -.-> sklearn/utils("Utilities") sklearn/UtilitiesandDatasetsGroup -.-> sklearn/datasets("Datasets") ml/FrameworkandSoftwareGroup -.-> ml/sklearn("scikit-learn") subgraph Lab Skills sklearn/linear_model -.-> lab-49297{{"MNIST 多項ロジスティック回帰"}} sklearn/preprocessing -.-> lab-49297{{"MNIST 多項ロジスティック回帰"}} sklearn/model_selection -.-> lab-49297{{"MNIST 多項ロジスティック回帰"}} sklearn/utils -.-> lab-49297{{"MNIST 多項ロジスティック回帰"}} sklearn/datasets -.-> lab-49297{{"MNIST 多項ロジスティック回帰"}} ml/sklearn -.-> lab-49297{{"MNIST 多項ロジスティック回帰"}} end

ライブラリのインポート

この実験に必要なライブラリをインポートして始めましょう。scikit-learnライブラリを使ってデータセットを取得し、モデルを学習させ、モデルの性能を評価します。

import time
import matplotlib.pyplot as plt
import numpy as np

from sklearn.datasets import fetch_openml
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.utils import check_random_state

MNISTデータセットの読み込み

scikit-learnのfetch_openml関数を使ってMNISTデータセットを読み込みます。また、train_samplesの数を5000に設定することで、データのサブセットを選択します。

## Turn down for faster convergence
t0 = time.time()
train_samples = 5000

## Load data from https://www.openml.org/d/554
X, y = fetch_openml(
    "mnist_784", version=1, return_X_y=True, as_frame=False, parser="pandas"
)

前処理

データをシャッフルし、データセットを訓練用とテスト用に分割し、StandardScalerを使ってデータをスケーリングすることで、データの前処理を行います。

random_state = check_random_state(0)
permutation = random_state.permutation(X.shape[0])
X = X[permutation]
y = y[permutation]
X = X.reshape((X.shape[0], -1))

X_train, X_test, y_train, y_test = train_test_split(
    X, y, train_size=train_samples, test_size=10000
)

scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

モデルの学習

L1ペナルティ付きのロジスティック回帰とSAGAアルゴリズムを使ってモデルを学習します。Cの値を訓練サンプル数で割った50.0に設定します。

## Turn up tolerance for faster convergence
clf = LogisticRegression(C=50.0 / train_samples, penalty="l1", solver="saga", tol=0.1)
clf.fit(X_train, y_train)

モデルの評価

モデルの性能を、疎密度と正解率を計算することで評価します。

sparsity = np.mean(clf.coef_ == 0) * 100
score = clf.score(X_test, y_test)

print("Sparsity with L1 penalty: %.2f%%" % sparsity)
print("Test score with L1 penalty: %.4f" % score)

モデルの可視化

各クラスの分類ベクトルをプロットすることで、モデルを可視化します。

coef = clf.coef_.copy()
plt.figure(figsize=(10, 5))
scale = np.abs(coef).max()
for i in range(10):
    l1_plot = plt.subplot(2, 5, i + 1)
    l1_plot.imshow(
        coef[i].reshape(28, 28),
        interpolation="nearest",
        cmap=plt.cm.RdBu,
        vmin=-scale,
        vmax=scale,
    )
    l1_plot.set_xticks(())
    l1_plot.set_yticks(())
    l1_plot.set_xlabel("Class %i" % i)
plt.suptitle("Classification vector for...")

run_time = time.time() - t0
print("Example run in %.3f s" % run_time)
plt.show()

まとめ

この実験では、MNISTデータセットからの手書き数字を分類するためにロジスティック回帰をどのように使用するかを学びました。また、ロジスティック回帰に対するL1ペナルティ付きのSAGAアルゴリズムをどのように使用するかも学びました。疎な重みベクトルを持つことで0.8を超える正解率を達成し、モデルをより解釈可能にしました。ただし、このデータセットでは、L2ペナルティ付きの線形モデルや非線形の多層パーセプトロンモデルが達成できる精度よりも、この精度はかなり低いことにも留意しました。