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

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

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

目次

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

関連する外部ページ

1. Google Colaboratory での実行

Google Colaboratory のページ:

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

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

IMDb データセットのロード

【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. IMDb データセットのロード

    x_train: 25000件のデータ,批評文

    y_train: 25000件のデータ,ラベル(ラベルの値は 0 または 1)

    x_test: 25000件のデータ,批評文

    y_test: 25000件のデータ,ラベル(ラベルの値は 0 または 1)

    IMDb での映画の批評は,批評文とスコア(10点満点)である.

    IMDb の URL: https://www.imdb.com/

    IMDb データセットでは,7点以上の批評は positive,4点以下の批評は negative としている.つまり,2種類ある. そして,IMDb データセットには,positive か negative の批評のみが含まれている(中間の点数である 5点,6点のものは含まれていない).そして, positive,negative の批評が同数である. 学習用として,positive,negative がそれぞれ 25000. テスト用として,positive,negative がそれぞれ 25000.

    IMDb データセットのURL: https://ai.stanford.edu/%7Eamaas/data/sentiment/

    imdb = tf.keras.datasets.imdb
    (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=10000)
    

    [image]

IMDb データセットの確認

  1. IMDb データセット要素数の確認
    print(len(x_train))
    print(len(y_train))
    print(len(x_test))
    print(len(y_test))
    

    [image]
  2. IMDb データセットの確認

    まず,単語を整数にマッピングするなどを行う.

    # 単語を整数にマッピングする辞書
    word_index = imdb.get_word_index()
    
    # インデックスの最初の方は予約済み
    word_index = {k:(v+3) for k,v in word_index.items()}
    word_index["<PAD>"] = 0
    word_index["<START>"] = 1
    word_index["<UNK>"] = 2  # unknown
    word_index["<UNUSED>"] = 3
    
    reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
    
    def decode_review(text):
        return ' '.join([reverse_word_index.get(i, '?') for i in text])
    

    [image]

    批評文の確認

    0番目の批評文とその単語数を表示.

    x_train は費用文のデータセットである. x_train[0] は 0 番目の批評文である. 批評文は整数のリストになっている. それぞれの整数は,単語をコード化したものである. それぞれの整数を decode_review を使って単語に変換.

    print(decode_review(x_train[0]))
    print(len(x_train[0]))
    

    [image]

    1番目の批評文とその単語数を表示.

    print(decode_review(x_train[1]))
    print(len(x_train[1]))
    

    [image]

    ラベルの確認

    print(y_train[0])
    

    [image]
    print(y_train[1])
    

    [image]

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

  1. ニューラルネットワークを使うために,データの前処理

    パッデングを行う. 批評文のそれぞれは長さが異なるのを,同じ長さ 256 にそろえる.

    詳細は https://www.tensorflow.org/tutorials/keras/text_classification?hl=ja に説明がある.

    x_train = tf.keras.preprocessing.sequence.pad_sequences(x_train, value=word_index["<PAD>"], padding='post', maxlen=256)
    x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, value=word_index["<PAD>"], padding='post', maxlen=256)
    

    [image]
  2. x_train, y_train の確認
    print(x_train)
    print(len(x_train[0]))
    
    print(y_train)
    print(len(y_train))
    

    [image]
  3. ニューラルネットワークの作成と確認とコンパイル
    • ニューラルネットワークの種類: 層構造 (Sequential Model)
    • 1番目の層: embedding
    • 2番めの層: 平均プーリング
    • 3番目の層: sigmoid, 値は確率を表す 0 から 1 の間の浮動小数点数
    # 入力の形式は映画レビューで使われている語彙数(10,000語)
    VOCAB_SIZE = 10000
    
    m = tf.keras.Sequential(
        [
            layers.Embedding(VOCAB_SIZE, 16),
            layers.GlobalAveragePooling1D(),
            layers.Dense(16, activation='relu'),
            layers.Dense(1, activation=tf.nn.sigmoid)
        ]
    )
    m.summary()
    

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

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

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

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

    [image]

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

  1. 学習(訓練)

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

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

    [image]
  2. ニューラルネットワークによるデータの2クラス分類
    print(m.predict(x_test))
    

    [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. 学習曲線のプロット

    学習時と検証時で,大きく損失や精度が違っており,過学習が起きていることが確認できる