TensorFlow 実例 - テキスト分類プロジェクト

テキスト分類は自然言語処理(NLP)における基礎的なタスクであり、文書を自動的に1つ以上の事前定義されたカテゴリに分類することを指します。実際のアプリケーションでは、テキスト分類は広く使用されています:

  • スパムメール検出
  • 感情分析
  • ニュース分類
  • カスタマーサービスの会話分類
  • 製品レビューの分類

TensorFlowを使用してテキスト分類を実装する場合、通常以下の手順が含まれます:

  1. データの準備と前処理
  2. テキストのベクトル化
  3. モデルの構築
  4. モデルのトレーニング
  5. モデルの評価
  6. モデルのデプロイ

環境の準備

プロジェクトを開始する前に、以下のPythonライブラリがインストールされていることを確認してください:

!pip install tensorflow
!pip install numpy
!pip install pandas
!pip install matplotlib

必要なライブラリをインポート:

実例

import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

TensorFlowのバージョンを確認:

実例

print(tf.__version__)
# 出力例:2.8.0

データセットの準備

IMDB映画レビューデータセットを使用します。これは古典的な二値分類データセットで、50,000件の映画レビューが含まれており、肯定的(1)または否定的(0)な評価としてラベル付けされています。

データセットの読み込み

実例

# TensorFlowデータセットからIMDBデータを読み込む
imdb = tf.keras.datasets.imdb

# 最も頻繁に出現する上位10,000語のみを保持
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

データ探索

データ形式を確認:

実例

print("トレーニングサンプル数: {}, テストサンプル数: {}".format(len(train_data), len(test_data)))
# 出力:トレーニングサンプル数: 25000, テストサンプル数: 25000

# 最初のレビューを表示
print(train_data[0])
# 出力:[1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, ...]

データの前処理

整数シーケンスをマルチホットエンコーディングに変換:

実例

def vectorize_sequences(sequences, dimension=10000):
    results = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        results[i, sequence] = 1.
    return results

x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)

# ラベルを浮動小数点数に変換
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')

モデルの構築

モデルアーキテクチャ

シンプルな全結合ニューラルネットワークを構築します:

実例

model = tf.keras.Sequential([
    layers.Dense(16, activation='relu', input_shape=(10000,)),
    layers.Dense(16, activation='relu'),
    layers.Dense(1, activation='sigmoid')
])

モデルのコンパイル

実例

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])

パラメータの説明:

  • optimizer: オプティマイザー。学習プロセスを制御します。
  • loss: 損失関数。モデルの予測と実際のラベルの差分を測定します。
  • metrics: 評価指標。トレーニングとテストのステップを監視します。

モデルのトレーニング

検証セットの作成

実例

x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]

トレーニングプロセス

実例

history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=20,
                    batch_size=512,
                    validation_data=(x_val, y_val))

トレーニング結果の可視化

実例

history_dict = history.history

# トレーニング損失と検証損失をプロット
plt.plot(history_dict['loss'], 'bo', label='Training loss')
plt.plot(history_dict['val_loss'], 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()

# トレーニング精度と検証精度をプロット
plt.plot(history_dict['accuracy'], 'bo', label='Training acc')
plt.plot(history_dict['val_accuracy'], 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

モデルの評価と予測

テストセットの性能評価

実例

results = model.evaluate(x_test, y_test)
print(results)
# 出力例:[0.3245, 0.8732] は損失と精度を表します

予測の実行

実例

predictions = model.predict(x_test)
print(predictions[0])  # 最初のテストサンプルの予測確率

モデル最適化のアドバイス

  1. ネットワークアーキテクチャの調整:

    • 隠れ層の数を増やしたり減らしたりする
    • 異なるニューロン数を試す
    • 異なる活性化関数を使用する
  2. 正則化技術:

    • ドロップアウト層を追加して過学習を防ぐ
    • L1/L2正則化を使用する
  3. オプティマイザーの選択:

    • Adam、SGDなど他のオプティマイザーを試す
    • 学習率を調整する
  4. テキスト前処理の改善:

    • マルチホットエンコーディングの代わりに単語埋め込み(Embedding)を使用する
    • 事前学習済み単語ベクトル(Word2Vec、GloVeなど)を試す

完全なコード例

実例

import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
import matplotlib.pyplot as plt

# データを読み込む
imdb = tf.keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

# データの前処理
def vectorize_sequences(sequences, dimension=10000):
    results = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        results[i, sequence] = 1.
    return results

x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')

# モデルの構築
model = tf.keras.Sequential([
    layers.Dense(16, activation='relu', input_shape=(10000,)),
    layers.Dense(16, activation='relu'),
    layers.Dense(1, activation='sigmoid')
])

# モデルのコンパイル
model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])

# モデルのトレーニング
history = model.fit(x_train, y_train,
                   epochs=4,
                   batch_size=512,
                   validation_data=(x_test, y_test))

# モデルの評価
results = model.evaluate(x_test, y_test)
print("テスト損失と精度:", results)

# 予測を実行
predictions = model.predict(x_test)
print("最初のレビューの予測確率:", predictions[0])
その他の拡張