MNIST データセット(Python を使用)
【目次】
* MNIST データセット
MNIST データセットは,公開されているデータセット(オープンデータ)である.
0 から 9 までの 10 種類の手書き文字についての, モノクロ画像と,各画像に付いた「0から9までの数値」のラベルから構成されるデータセットである.
- 画像の枚数:合計 70000枚.
(内訳)70000枚の内訳は次の通りである
60000枚:教師データ
10000枚:検証データ
- 画像のサイズ: 28x28 である.
- 画素はグレースケールであり,画素値は0~255である.0が白,255が黒.
【文献】
Y. Lecun, L. Bottou, Y. Bengio and P. Haffner, Gradient-based learning applied to document recognition, vol. 86, no. 11, pp. 2278-2324, 1998.
【サイト内の関連ページ】
- MNIST データセットを扱う Python プログラム: 別ページ で説明している.
- MNIST データセットによる学習と分類(TensorFlow データセット,TensorFlow,Python を使用)(Windows 上,Google Colaboratroy の両方を記載)
【関連する外部ページ】
- MNIST データセット の詳細は, THE MNIST DATABASE of handwritten digits のページで説明されている.その URL は次の通り.
- TensorFlow データセットの MNIST データセット: https://www.tensorflow.org/datasets/catalog/mnist
1. Google Colab へのリンク
Google Colaboratory のページ:
https://colab.research.google.com/drive/1awZ1ex4KbAJ6hw4VfjKwE-kuiNVVHrfJ?usp=sharing
2. 前準備
Python 3.12 のインストール(Windows 上) [クリックして展開]
以下のいずれかの方法で Python 3.12 をインストールする。Python がインストール済みの場合、この手順は不要である。
方法1:winget によるインストール
管理者権限のコマンドプロンプトで以下を実行する。管理者権限のコマンドプロンプトを起動するには、Windows キーまたはスタートメニューから「cmd」と入力し、表示された「コマンドプロンプト」を右クリックして「管理者として実行」を選択する。
winget install --id Python.Python.3.12 -e --scope machine --silent --accept-source-agreements --accept-package-agreements --override "/quiet InstallAllUsers=1 PrependPath=1 Include_test=0 Include_pip=1 Include_launcher=1 InstallLauncherAllUsers=1 TargetDir=\"C:\Program Files\Python312\""
powershell -Command "$p='C:\Program Files\Python312'; $s=\"$p\Scripts\"; $m=[Environment]::GetEnvironmentVariable('Path','Machine'); if($m -notlike \"*$s*\") { [Environment]::SetEnvironmentVariable('Path', \"$p;$s;$m\", 'Machine') }"
--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動すると PATH が自動的に設定される。
方法2:インストーラーによるインストール
- Python 公式サイト(https://www.python.org/downloads/)にアクセスし、「Download Python 3.x.x」ボタンから Windows 用インストーラーをダウンロードする。
- ダウンロードしたインストーラーを実行する。
- 初期画面の下部に表示される「Add python.exe to PATH」に必ずチェックを入れてから「Customize installation」を選択する。このチェックを入れ忘れると、コマンドプロンプトから
pythonコマンドを実行できない。 - 「Install Python 3.xx for all users」にチェックを入れ、「Install」をクリックする。
インストールの確認
コマンドプロンプトで以下を実行する。
python --version
バージョン番号(例:Python 3.12.x)が表示されればインストール成功である。「'python' は、内部コマンドまたは外部コマンドとして認識されていません。」と表示される場合は、インストールが正常に完了していない。
AIエディタ Windsurf のインストール(Windows 上) [クリックして展開]
Pythonプログラムの編集・実行には、AIエディタの利用を推奨する。ここでは、Windsurfのインストールを説明する。Windsurf がインストール済みの場合、この手順は不要である。
管理者権限のコマンドプロンプトで以下を実行する。管理者権限のコマンドプロンプトを起動するには、Windows キーまたはスタートメニューから「cmd」と入力し、表示された「コマンドプロンプト」を右クリックして「管理者として実行」を選択する。
winget install --scope machine --id Codeium.Windsurf -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --custom "/SP- /SUPPRESSMSGBOXES /NORESTART /CLOSEAPPLICATIONS /DIR=""C:\Program Files\Windsurf"" /MERGETASKS=!runcode,addtopath,associatewithfiles,!desktopicon"
powershell -Command "$env:Path=[System.Environment]::GetEnvironmentVariable('Path','Machine')+';'+[System.Environment]::GetEnvironmentVariable('Path','User'); windsurf --install-extension MS-CEINTL.vscode-language-pack-ja --force; windsurf --install-extension ms-python.python --force; windsurf --install-extension Codeium.windsurfPyright --force"
--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動すると PATH が自動的に設定される。
【関連する外部ページ】
Windsurf の公式ページ: https://windsurf.com/
TensorFlow, TensorFlow データセット, Keras, numpy, matplotlib のインストール
Windows の場合
Windows では,コマンドプロンプトを管理者として実行し, 次のコマンドを実行する.
python -m pip install -U tensorflow-gpu tensorflow_datasets keras numpy matplotlib
(このページで,Build Tools for Visual Studio 2022,NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNNのインストールも説明している.)
Ubuntu の場合
Ubuntu では,次のコマンドを実行.
# パッケージリストの情報を更新
sudo apt update
sudo apt -y install python3-numpy python3-matplotlib
sudo pip3 install -U tensorflow-gpu tensorflow_datasets keras
(このページで,NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNNのインストールも説明している.)
3. MNIST データセットのロード
Python 3.12 のインストール(Windows 上) [クリックして展開]
以下のいずれかの方法で Python 3.12 をインストールする。Python がインストール済みの場合、この手順は不要である。
方法1:winget によるインストール
管理者権限のコマンドプロンプトで以下を実行する。管理者権限のコマンドプロンプトを起動するには、Windows キーまたはスタートメニューから「cmd」と入力し、表示された「コマンドプロンプト」を右クリックして「管理者として実行」を選択する。
winget install --id Python.Python.3.12 -e --scope machine --silent --accept-source-agreements --accept-package-agreements --override "/quiet InstallAllUsers=1 PrependPath=1 Include_test=0 Include_pip=1 Include_launcher=1 InstallLauncherAllUsers=1 TargetDir=\"C:\Program Files\Python312\""
powershell -Command "$p='C:\Program Files\Python312'; $s=\"$p\Scripts\"; $m=[Environment]::GetEnvironmentVariable('Path','Machine'); if($m -notlike \"*$s*\") { [Environment]::SetEnvironmentVariable('Path', \"$p;$s;$m\", 'Machine') }"
--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動すると PATH が自動的に設定される。
方法2:インストーラーによるインストール
- Python 公式サイト(https://www.python.org/downloads/)にアクセスし、「Download Python 3.x.x」ボタンから Windows 用インストーラーをダウンロードする。
- ダウンロードしたインストーラーを実行する。
- 初期画面の下部に表示される「Add python.exe to PATH」に必ずチェックを入れてから「Customize installation」を選択する。このチェックを入れ忘れると、コマンドプロンプトから
pythonコマンドを実行できない。 - 「Install Python 3.xx for all users」にチェックを入れ、「Install」をクリックする。
インストールの確認
コマンドプロンプトで以下を実行する。
python --version
バージョン番号(例:Python 3.12.x)が表示されればインストール成功である。「'python' は、内部コマンドまたは外部コマンドとして認識されていません。」と表示される場合は、インストールが正常に完了していない。
AIエディタ Windsurf のインストール(Windows 上) [クリックして展開]
Pythonプログラムの編集・実行には、AIエディタの利用を推奨する。ここでは、Windsurfのインストールを説明する。Windsurf がインストール済みの場合、この手順は不要である。
管理者権限のコマンドプロンプトで以下を実行する。管理者権限のコマンドプロンプトを起動するには、Windows キーまたはスタートメニューから「cmd」と入力し、表示された「コマンドプロンプト」を右クリックして「管理者として実行」を選択する。
winget install --scope machine --id Codeium.Windsurf -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --custom "/SP- /SUPPRESSMSGBOXES /NORESTART /CLOSEAPPLICATIONS /DIR=""C:\Program Files\Windsurf"" /MERGETASKS=!runcode,addtopath,associatewithfiles,!desktopicon"
powershell -Command "$env:Path=[System.Environment]::GetEnvironmentVariable('Path','Machine')+';'+[System.Environment]::GetEnvironmentVariable('Path','User'); windsurf --install-extension MS-CEINTL.vscode-language-pack-ja --force; windsurf --install-extension ms-python.python --force; windsurf --install-extension Codeium.windsurfPyright --force"
--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動すると PATH が自動的に設定される。
【関連する外部ページ】
Windsurf の公式ページ: https://windsurf.com/
- パッケージのインポート,TensorFlow のバージョン確認など
import tensorflow as tf import numpy as np import tensorflow_datasets as tfds %matplotlib inline import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
- TensorFlow データセット から MNIST データセット をロード
- x_train: サイズ 28 × 28 の 60000枚の濃淡画像
- y_train: 60000枚の濃淡画像それぞれの,種類番号(0 から 9 のどれか)
- x_test: サイズ 28 × 28 の 10000枚の濃淡画像
- y_test: 10000枚の濃淡画像それぞれの,種類番号(0 から 9 のどれか)
結果は,TensorFlow の Tensor である.
type は型,shape はサイズ,np.max と np.mi は最大値と最小値.
tensorflow_datasets の loadで, 「batch_size = -1」を指定して,一括読み込みを行っている.
mnist, mnist_metadata = tfds.load('mnist', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1) x_train, y_train, x_test, y_test = mnist['train'][0], mnist['train'][1], mnist['test'][0], mnist['test'][1] print(mnist_metadata)
4. MNIST データセットの確認
- データセットの中の画像を表示
MatplotLib を用いて,0 番目の画像を表示する
NUM = 0 plt.figure() plt.imshow(x_train[NUM,:,:,0], cmap='gray') plt.colorbar() plt.gca().grid(False) plt.show()
- データセットの情報を表示
print(mnist_metadata) print(mnist_metadata.features["label"].num_classes) print(mnist_metadata.features["label"].names)
- データの確認表示
MatplotLib を用いて,複数の画像を並べて表示する.
class_names = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] plt.style.use('default') plt.figure(figsize=(10,10)) for i in range(25): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(x_train[i], cmap=plt.cm.binary) plt.xlabel(class_names[y_train[i]]) plt.show()
- tf.data.Dataset オブジェクトによるデータセットの生成
ロード時に「as_supervised=False」としたときは,「image, label = data['image'], data['label']」
ds_train = mnist['train'] it = ds_train.cache().shuffle(1000).batch(128).prefetch(tf.data.experimental.AUTOTUNE) for data in it.take(1): image, label = data[0], data[1] print(image) print(label)
5. MNIST データセットのデータフレームへの変換
- データセットをデータフレームに変換
train = tfds.as_dataframe(mnist['train'], mnist_metadata) test = tfds.as_dataframe(mnist['test'], mnist_metadata) print(train) print(test)
- データフレームの行列と属性数
行数は len(<データフレーム>), 属性数は len(<データフレーム>.columns)
print(len(train)) print(len(train.columns)) print(len(test)) print(len(test.columns))
- データセットの先頭 10行をデータフレームに変換
train = tfds.as_dataframe(mnist['train'].take(10), mnist_metadata) test = tfds.as_dataframe(mnist['test'].take(10), mnist_metadata) print(train) print(test)
- データフレームの行列と属性数
行数は len(<データフレーム>), 属性数は len(<データフレーム>.columns)
print(len(train)) print(len(train.columns)) print(len(test)) print(len(test.columns))