%print(y_test[1])!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"> CNN による画像分類,モデルの作成と学習と検証(MobileNetV2,ResNet50,DenseNet 121,DenseNet 169,NASNet,TensorFlow データセットのCIFAR-10 データセットを使用)(Google Colab 上もしくはパソコン上)

金子邦彦研究室人工知能CIFAR 10 の画像分類を行う畳み込みニューラルネットワーク (CNN) の学習,転移学習CNN による画像分類,モデルの作成と学習と検証(MobileNetV2,ResNet50,DenseNet 121,DenseNet 169,NASNet,TensorFlow データセットのCIFAR-10 データセットを使用)(Google Colab 上もしくはパソコン上)

CNN による画像分類,モデルの作成と学習と検証(MobileNetV2,ResNet50,DenseNet 121,DenseNet 169,NASNet,TensorFlow データセットのCIFAR-10 データセットを使用)(Google Colab 上もしくはパソコン上)

CIFAR-10 データセット下図)の画像分類を行う. 所定の 10種類に画像分類を行うものである. その 10種類は,airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck である.

[image]

CNN の作成,学習,画像分類を行う. TensorFlow データセットCIFAR-10 データセットを使用する. CNN としては,次のものを使用する.

目次

  1. Google Colaboratory での実行
  2. Windows での実行
  3. CIFAR-10 データセットのロード
  4. CIFAR-10 データセットの確認
  5. ニューラルネットワークの作成(MobileNetV2 を使用)
  6. ニューラルネットワークの作成(ResNet50 を使用)
  7. ニューラルネットワークの作成(DenseNet 121 を使用)
  8. ニューラルネットワークの作成(DenseNet 169 を使用)
  9. ニューラルネットワークの作成(NASNet を使用)

サイト内の関連ページ

関連する外部ページ

1. Google Colaboratory での実行

Google Colaboratory のページ:

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

https://colab.research.google.com/drive/1fNGbsjqt2FgO_QGoW0n74CQR77iAX2li?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
    

CIFAR-10 データセットのロード

【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. CIFAR-10 データセットのロード
    • x_train: サイズ 32 ×32 の 60000枚の濃淡画像
    • y_train: 50000枚の濃淡画像それぞれの,種類番号(0 から 9 のどれか)
    • x_test: サイズ 32 ×32 の 10000枚の濃淡画像
    • y_test: 10000枚の濃淡画像それぞれの,種類番号(0 から 9 のどれか)
    tensorflow_datasets の loadで, 「batch_size = -1」を指定して,一括読み込みを行っている.
    cifar10, cifar10_metadata = tfds.load('cifar10', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
    x_train, y_train, x_test, y_test = cifar10['train'][0], cifar10['train'][1], cifar10['test'][0], cifar10['test'][1]
    print(cifar10_metadata)
    

    [image]

CIFAR-10 データセットの確認

  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])
    plt.colorbar()
    plt.gca().grid(False)
    plt.show()
    

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

    [image]

データの準備

  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]

5. MobileNetV2 の作成,CIFAR-10 による学習,画像分類の実行

  1. ニューラルネットワークの作成
    Keras の MobileNet を使う. 「weights=None」を指定することにより,最初,重みはランダムに設定する.

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

    NUM_CLASSES = 10
    input_shape = (32, 32, 3)
    m1 = tf.keras.applications.mobilenet.MobileNet(input_shape=input_shape, weights=None, classes=NUM_CLASSES)
    m1.summary()
    m1.compile(
        optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
        loss='sparse_categorical_crossentropy',
        metrics=['sparse_categorical_crossentropy', 'accuracy'])
    

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

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

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

    from tensorflow.keras.utils import plot_model
    import pydot
    plot_model(m1)
    
  3. ニューラルネットワークの学習を行う

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

    epochs = 20
    history = m1.fit(x_train, y_train,
                        epochs=epochs,
                        validation_data=(x_test, y_test), 
                        verbose=1)
    

    [image]
  4. CNN による画像分類

    分類してみる.

    print(m1.predict(x_test))
    

    [image]

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

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

    [image]

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

    print(y_test)
    

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

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

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

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

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

6. ResNet50 の作成,CIFAR-10 による学習,画像分類の実行

  1. ニューラルネットワークの作成
    Keras の ResNet50 を使う. 「weights=None」を指定することにより,最初,重みはランダムに設定する.

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

    NUM_CLASSES = 10
    input_shape = (32, 32, 3)
    m2 = tf.keras.applications.resnet50.ResNet50(input_shape=input_shape, weights=None, classes=NUM_CLASSES)
    m2.summary()
    m2.compile(
        optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
        loss='sparse_categorical_crossentropy',
        metrics=['sparse_categorical_crossentropy', 'accuracy'])
    

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

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

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

    from tensorflow.keras.utils import plot_model
    import pydot
    plot_model(m2)
    
  3. ニューラルネットワークの学習を行う

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

    epochs = 20
    history = m2.fit(x_train, y_train,
                        epochs=epochs,
                        validation_data=(x_test, y_test), 
                        verbose=1)
    

    [image]
  4. CNN による画像分類

    分類してみる.

    print(m2.predict(x_test))
    

    [image]

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

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

    [image]

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

    print(y_test)
    

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

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

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

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

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

  7. 学習時と検証時の,精度の違い
    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    
    plt.clf()   # 図のクリア
    plt.plot(epochs, acc, 'bo', label='Training acc')
    plt.plot(epochs, val_acc, 'b', label='Validation acc')
    plt.title('Training and validation accuracy')
    plt.xlabel('Epochs')
    plt.ylabel('Accuracy')
    plt.legend()
    
    plt.show()
    

    [image]

9. ニューラルネットワークの作成(DenseNet 121 を使用)

  1. ニューラルネットワークの作成と確認とコンパイル
    Keras の DenseNet121 を使う. 「weights=None」を指定することにより,最初,重みはランダムに設定する.

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

    NUM_CLASSES = 10
    input_shape = (32, 32, 3)
    m3 = tf.keras.applications.densenet.DenseNet121(input_shape=input_shape, weights=None, classes=NUM_CLASSES)
    m3.summary()
    m3.compile(
        optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
        loss='sparse_categorical_crossentropy',
        metrics=['sparse_categorical_crossentropy', 'accuracy'])
    

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

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

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

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

10. ニューラルネットワークの学習(DenseNet 121 を使用)

  1. ニューラルネットワークの学習を行う

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

    epochs = 20
    history = m3.fit(x_train, y_train,
                        epochs=epochs,
                        validation_data=(x_test, y_test), 
                        verbose=1)
    

    [image]
  2. CNN による画像分類

    分類してみる.

    print(m3.predict(x_test))
    

    [image]

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

    m3.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://www.tensorflow.org/tutorials/keras/overfit_and_underfit?hl=ja で公開されているプログラムを使用

    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    def plot_history(histories, key='binary_crossentropy'):
      plt.figure(figsize=(16,10))
    
      for name, history in histories:
        val = plt.plot(history.epoch, history.history['val_'+key],
                       '--', label=name.title()+' Val')
        plt.plot(history.epoch, history.history[key], color=val[0].get_color(),
                 label=name.title()+' Train')
    
      plt.xlabel('Epochs')
      plt.ylabel(key.replace('_',' ').title())
      plt.legend()
    
      plt.xlim([0,max(history.epoch)])
    
    
    plot_history([('history', history)], key='sparse_categorical_crossentropy')
    

    [image]
    plot_history([('history', history)], key='accuracy')
    

    [image]

11. ニューラルネットワークの作成(DenseNet 169 を使用)

  1. ニューラルネットワークの作成と確認とコンパイル
    Keras の DenseNet169 を使う. 「weights=None」を指定することにより,最初,重みはランダムに設定する.

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

    NUM_CLASSES = 10
    input_shape = (32, 32, 3)
    m4 = tf.keras.applications.densenet.DenseNet169(input_shape=input_shape, weights=None, classes=NUM_CLASSES)
    m4.summary()
    m4.compile(
        optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
        loss='sparse_categorical_crossentropy',
        metrics=['sparse_categorical_crossentropy', 'accuracy'])
    

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

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

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

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

12. ニューラルネットワークの学習(DenseNet 169 を使用)

  1. ニューラルネットワークの学習を行う

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

    epochs = 20
    history = m4.fit(x_train, y_train,
                        epochs=epochs,
                        validation_data=(x_test, y_test), 
                        verbose=1)
    

    [image]
  2. CNN による画像分類

    分類してみる.

    print(m4.predict(x_test))
    

    [image]

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

    m4.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://www.tensorflow.org/tutorials/keras/overfit_and_underfit?hl=ja で公開されているプログラムを使用

    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    def plot_history(histories, key='binary_crossentropy'):
      plt.figure(figsize=(16,10))
    
      for name, history in histories:
        val = plt.plot(history.epoch, history.history['val_'+key],
                       '--', label=name.title()+' Val')
        plt.plot(history.epoch, history.history[key], color=val[0].get_color(),
                 label=name.title()+' Train')
    
      plt.xlabel('Epochs')
      plt.ylabel(key.replace('_',' ').title())
      plt.legend()
    
      plt.xlim([0,max(history.epoch)])
    
    
    plot_history([('history', history)], key='sparse_categorical_crossentropy')
    

    [image]
    plot_history([('history', history)], key='accuracy')
    

    [image]

13. ニューラルネットワークの作成(NASNet を使用)

  1. ニューラルネットワークの作成と確認とコンパイル
    KerasNASNet を使う. 「weights=None」を指定することにより,最初,重みはランダムに設定する.

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

    NUM_CLASSES = 10
    input_shape = (32, 32, 3)
    m5 = tf.keras.applications.nasnet.NASNetMobile(input_shape=input_shape, weights=None, classes=NUM_CLASSES)
    m5.summary()
    m5.compile(
        optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
        loss='sparse_categorical_crossentropy',
        metrics=['sparse_categorical_crossentropy', 'accuracy'])
    

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

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

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

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

14. ニューラルネットワークの学習(NASNet を使用)

  1. ニューラルネットワークの学習を行う

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

    epochs = 20
    history = m5.fit(x_train, y_train,
                        epochs=epochs,
                        validation_data=(x_test, y_test), 
                        verbose=1)
    

    [image]
  2. CNN による画像分類

    分類してみる.

    print(m5.predict(x_test))
    

    [image]

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

    cvm5.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://www.tensorflow.org/tutorials/keras/overfit_and_underfit?hl=ja で公開されているプログラムを使用

    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    def plot_history(histories, key='binary_crossentropy'):
      plt.figure(figsize=(16,10))
    
      for name, history in histories:
        val = plt.plot(history.epoch, history.history['val_'+key],
                       '--', label=name.title()+' Val')
        plt.plot(history.epoch, history.history[key], color=val[0].get_color(),
                 label=name.title()+' Train')
    
      plt.xlabel('Epochs')
      plt.ylabel(key.replace('_',' ').title())
      plt.legend()
    
      plt.xlim([0,max(history.epoch)])
    
    
    plot_history([('history', history)], key='sparse_categorical_crossentropy')
    

    [image]
    plot_history([('history', history)], key='accuracy')
    

    [image]