金子邦彦研究室人工知能Windows で動く人工知能関係 Pythonアプリケーション,オープンソースソフトウエア)Fashion MNIST データセットによる学習と分類(TensorFlow データセット,TensorFlow,Python を使用)(Windows 上,Google Colaboratroy の両方を記載)

Fashion MNIST データセットによる学習と分類(TensorFlow データセット,TensorFlow,Python を使用)(Windows 上,Google Colaboratroy の両方を記載)

ニューラルネットワークの作成,学習,データの分類を行う. TensorFlow データセットのFashion MNIST データセットを使用する.

目次

  1. Google Colaboratory での実行
  2. Windows での実行
  3. Fashion MNIST データセットのロード
  4. Fashion MNIST データセットの確認
  5. Keras を用いたニューラルネットワークの作成
  6. ニューラルネットワークの学習と検証

説明資料: [パワーポイント]

サイト内の関連ページ

関連する外部ページ

1. Google Colaboratory での実行

Google Colaboratory のページ:

次のリンクをクリックすると,Google Colaboratoryノートブックが開く. そして,Google アカウントでログインすると,Google Colaboratory のノートブック内のコード等を編集したり再実行したりができる.編集した場合でも,他の人に影響が出たりということはない.そして,編集後のものを,各自の Google ドライブ内に保存することもできる.

https://colab.research.google.com/drive/1D0r9WthikzMLWCVCBgLRFXjMkCg17kQs?usp=sharing

2. Windows での実行

Python のインストール(Windows 上)

サイト内の関連ページ

関連する外部ページ

Python の公式ページ: https://www.python.org/

TensorFlow,Keras,TensorFlow データセットのインストール

  1. Windows で,コマンドプロンプト管理者として実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

  2. 次のコマンドを実行.

    python -m pip uninstall -y tensorflow tensorflow-cpu tensorflow-gpu tensorflow-intel tensorflow-text tensorflow-estimator tf-models-official tf_slim tensorflow_datasets tensorflow-hub keras keras-tuner keras-visualizer
    python -m pip install -U tensorflow==2.10.1 tf_slim tensorflow_datasets==4.8.3 tensorflow-hub keras keras-tuner keras-visualizer
    

サイト内の関連ページ

Windows での TensorFlowKeras のインストール: 別ページ »で説明

(このページで,Build Tools for Visual Studio 2022,NVIDIA ドライバ, NVIDIA CUDA ツールキットNVIDIA cuDNNのインストールも説明している.)

Graphviz のインストール

Windows での Graphviz のインストール: 別ページ »で説明している.

numpy,matplotlib, seaborn, scikit-learn, pandas, pydot のインストール

  1. Windows で,コマンドプロンプト管理者として実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

  2. 次のコマンドを実行する.

    python -m pip install -U numpy matplotlib seaborn scikit-learn pandas pydot
    

Fashion MNIST データセットのロード

【Python の利用】

Python は,次のコマンドで起動できる.

Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.

Python のまとめ: 別ページ »にまとめ

  1. Windows で,コマンドプロンプトを実行.
  2. jupyter qtconsole の起動

    これ以降の操作は,jupyter qtconsole で行う.

    jupyter qtconsole
    

    Python 開発環境として,Python コンソール(Jupyter Qt Console), Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, spyder のインストール

    Windows で,コマンドプロンプト管理者として実行し,次のコマンドを実行する.

    python -m pip install -U pip setuptools jupyterlab jupyter jupyter-console jupytext PyQt5 nteract_on_jupyter spyder
    
  3. パッケージのインポート,TensorFlow のバージョン確認など
    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow as tf
    from tensorflow.keras import layers
    from tensorflow.keras import backend as K 
    K.clear_session()
    import numpy as np
    import tensorflow_datasets as tfds
    from tensorflow.keras.preprocessing import image
    
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    # TensorFlow のバージョン
    print(tf.__version__)
    
    # GPU を利用しているか
    gpus = tf.config.list_physical_devices(device_type = 'GPU')
    if len(gpus)>0:
        print(f">> GPU detected. {gpus[0].name}")
        tf.config.experimental.set_memory_growth(gpus[0], True)
    

    [image]
  4. Fashion 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」を指定して,一括読み込みを行っている.

    fashion_mnist, fashion_mnist_metadata = tfds.load('fashion_mnist', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
    x_train, y_train, x_test, y_test = fashion_mnist['train'][0], fashion_mnist['train'][1], fashion_mnist['test'][0], fashion_mnist['test'][1]
    print(fashion_mnist_metadata)
    

    [image]

Fashion MNIST データセットの確認

  1. 型と形と最大値と最小値の確認
    print(type(x_train), x_train.shape, np.max(x_train), np.min(x_train))
    print(type(x_test), x_test.shape, np.max(x_test), np.min(x_test))
    print(type(y_train), y_train.shape, np.max(y_train), np.min(y_train))
    print(type(y_test), y_test.shape, np.max(y_test), np.min(y_test))
    

    [image]
  2. データセットの中の画像を表示

    MatplotLib を用いて,0 番目の画像を表示する

    NUM = 0
    plt.figure()
    plt.imshow(x_train[NUM,:,:,0], cmap='gray')
    plt.colorbar()
    plt.gca().grid(False)
    plt.show()
    

    [image]
  3. データセットの情報を表示
    print(fashion_mnist_metadata)
    print(fashion_mnist_metadata.features["label"].num_classes)
    print(fashion_mnist_metadata.features["label"].names)
    

    [image]
  4. 主成分分析の結果である主成分スコアのプロット

    x_train, x_test は主成分分析で2次元にマッピング, y_train, y_test は色.

    import pandas as pd
    import seaborn as sns
    sns.set()
    import sklearn.decomposition
    # 主成分分析
    def prin(A, n):
        pca = sklearn.decomposition.PCA(n_components=n)
        return pca.fit_transform(A)
    
    # 主成分分析で2つの成分を得る
    def prin2(A):
        return prin(A, 2)
    
    # M の最初の2列を,b で色を付けてプロット
    def scatter_plot(M, b, alpha):
        a12 = pd.DataFrame( M[:,0:2], columns=['a1', 'a2'] )
        a12['target'] = b
        sns.scatterplot(x='a1', y='a2', hue='target', data=a12, palette=sns.color_palette("hls", np.max(b) + 1), legend="full", alpha=alpha)
    
    # 主成分分析プロット
    def pcaplot(A, b, alpha):
        scatter_plot(prin2(A), b, alpha)
    
    pcaplot(np.reshape(x_train, (x_train.shape[0], -1)), y_train, 0.1)
    

    [image]
    pcaplot(np.reshape(x_test, (x_test.shape[0], -1)), y_test, 0.1)
    

    [image]

Keras を用いたニューラルネットワークの作成

  1. x_train, x_test, y_train, y_test の numpy ndarray への変換と,値の範囲の調整(値の範囲が 0 〜 255 であるのを,0 〜 1 に調整)
    x_train = x_train.numpy().astype("float32") / 255.0
    x_test = x_test.numpy().astype("float32") / 255.0
    y_train = y_train.numpy()
    y_test = y_test.numpy()
    print(type(x_train), x_train.shape, np.max(x_train), np.min(x_train))
    print(type(x_test), x_test.shape, np.max(x_test), np.min(x_test))
    print(type(y_train), y_train.shape, np.max(y_train), np.min(y_train))
    print(type(y_test), y_test.shape, np.max(y_test), np.min(y_test))
    

    [image]
  2. データの確認表示

    MatplotLib を用いて,複数の画像を並べて表示する.

    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(y_train[i])
    
    plt.show()
    

    [image]
  3. モデルの作成と確認
    • ニューラルネットワークの種類: 層構造 (Sequential Model)
    • ニューラルネットワークの構成
      • Flatten の層: 画像(28かける28)を 1次元の配列に変換する.
      • 1層目: Dense全結合),ニューロン(ユニット)の個数: 64
      • 2層目: Dense全結合),ニューロン(ユニット)の個数: 10
      • 2層目のニューロン(ユニット)の種類: softmax
      • 1番目のDense の層と2番目のDense の層の間の結合については,ドロップアウトを行う.
    num_classes = 10
    input_shape = (28, 28)
    m = tf.keras.Sequential(
        [
            tf.keras.Input(shape=input_shape),
            layers.Flatten(),
            layers.Dense(units=64, activation='relu'),
            layers.Dropout(0.5),
            layers.Dense(units=num_classes, activation='softmax')
        ]
    )
    print(m.summary())
    

    [image]
  4. モデルのビジュアライズ

    Keras のモデルのビジュアライズについては: https://keras.io/ja/visualization/

    ここでの表示で,エラーメッセージが出る場合でも,モデル自体は問題なくできていると考えられる.続行する

    from tensorflow.keras.utils import plot_model
    import pydot
    plot_model(m)
    

    [image]

ニューラルネットワークの学習と検証

  1. コンパイル,学習を行う

    オプティマイザ損失関数メトリクスを設定する.

    ニューラルネットワーク学習は fit メソッドにより行う. 教師データを使用する. 教師データを投入する.

    EPOCHS = 20
    m.compile(
        optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
        loss='sparse_categorical_crossentropy',
        metrics=['sparse_categorical_crossentropy', 'accuracy']
    )
    history = m.fit(x_train, y_train, 
                        batch_size=128, 
                        epochs=EPOCHS,
                        validation_data=(x_test, y_test), 
                        verbose=1)
    

    [image]

    SGD を使う場合のプログラム例

    m.compile(optimizer=tf.keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
    
  2. ディープラーニングによるデータの分類

    x_test を分類してみる.

    print(m.predict(x_test))
    

    [image]

    それぞれの数値の中で、一番大きいものはどれか?

    m.predict(x_test).argmax(axis=1)
    

    [image]

    y_test 内にある正解のラベル(クラス名)を表示する(上の結果と比べるため)

    print(y_test)
    

    [image]
  3. 学習曲線の確認

    過学習や学習不足について確認.

    import pandas as pd
    hist = pd.DataFrame(history.history)
    hist['epoch'] = history.epoch
    print(hist)
    

    [image]
  4. 学習曲線のプロット

    関連する外部ページ】 訓練の履歴の可視化については,https://keras.io/ja/visualization/