Python
 Computer >> コンピューター >  >> プログラミング >> Python

TensorFlowとPythonでIMDBデータセットをダウンロードして探索する方法を解説

はじめに:TensorFlowとは

TensorFlowはGoogleが提供する機械学習フレームワークです。オープンソースとして公開されており、Pythonと組み合わせてアルゴリズムの実装やディープラーニングアプリケーションの開発など、幅広い用途で活用されています。研究目的から本番環境での運用まで対応できる点が大きな特徴です。

TensorFlowはNumPyおよび多次元配列(いわゆる「テンソル」)を基盤として動作します。このフレームワークは深層ニューラルネットワークの構築をサポートしており、高い拡張性を備え、多くの人気データセットが同梱されています。また、GPU計算を利用でき、リソース管理も自動化されます。多数の機械学習ライブラリが含まれており、ドキュメントやサポートも充実しています。深層ニューラルネットワークモデルの実行やトレーニングを行い、各データセットの関連する特徴を予測するアプリケーションを作成することが可能です。

Windows環境では、以下のコマンドで「tensorflow」パッケージをインストールできます。

pip install tensorflow

テンソルはTensorFlowで使われる基本的なデータ構造であり、フロー図のエッジ(辺)をつなぐ役割を果たします。このフロー図は「データフローグラフ」と呼ばれます。テンソルとは多次元配列またはリストのことであり、「ランク」「形状」「データ型」という3つの主要な属性によって識別されます。

IMDBデータセットについて

「IMDB」データセットには5万件以上の映画レビューが収録されており、主に自然言語処理(NLP)関連のタスクで使用される定番データセットです。

以下のコードはGoogle Colaboratoryで実行することを想定しています。Google Colab(Colaboratory)はブラウザ上でPythonコードを実行できるサービスで、環境設定は不要、GPUにも無料でアクセスできます。ColaboratoryはJupyter Notebookをベースに構築されています。

コード例

import matplotlib.pyplot as plt
import os
import re
import shutil
import string
import tensorflow as tf

from tensorflow.keras import layers
from tensorflow.keras import losses
from tensorflow.keras import preprocessing
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
print("The tensorflow version is ")
print(tf.__version__)
url = "https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz"

dataset = tf.keras.utils.get_file("aclImdb_v1.tar.gz", url,
                                  untar=True, cache_dir='.',
                                  cache_subdir='')
print("The dataset is being downloaded")
dataset_dir = os.path.join(os.path.dirname(dataset), 'aclImdb')
print("The directories in the downloaded folder are ")
os.listdir(dataset_dir)

train_dir = os.path.join(dataset_dir, 'train')
os.listdir(train_dir)
print("The sample of data : ")
sample_file = os.path.join(train_dir, 'pos/1181_9.txt')
with open(sample_file) as f:
  print(f.read())

remove_dir = os.path.join(train_dir, 'unsup')
shutil.rmtree(remove_dir)
batch_size = 32
seed = 42
print("The batch size is")
print(batch_size)

raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory(
    'aclImdb/train',
    batch_size=batch_size,
    validation_split=0.2,
    subset='training',
    seed=seed)

for text_batch, label_batch in raw_train_ds.take(1):
  for i in range(3):
    print("Review", text_batch.numpy()[i])
    print("Label", label_batch.numpy()[i])

print("Label 0 corresponds to", raw_train_ds.class_names[0])
print("Label 1 corresponds to", raw_train_ds.class_names[1])
raw_val_ds = tf.keras.preprocessing.text_dataset_from_directory(
    'aclImdb/train',
    batch_size=batch_size,
    validation_split=0.2,
    subset='validation',
    seed=seed)
raw_test_ds = tf.keras.preprocessing.text_dataset_from_directory(
    'aclImdb/test',
    batch_size=batch_size)

コード出典: https://www.tensorflow.org/tutorials/keras/text_classification

実行結果

The tensorflow version is
2.4.0
The dataset is being downloaded
The directories in the downloaded folder are
The sample of data :
Rachel Griffiths writes and directs this award winning short film. A heartwarming story about coping with grief and cherishing the memory of those we've loved and lost. Although, only 15 minutes long, Griffiths manages to capture so much emotion and truth onto film in the short space of time. Bud Tingwell gives a touching performance as Will, a widower struggling to cope with his wife's death. Will is confronted by the harsh reality of loneliness and helplessness as he proceeds to take care of Ruth's pet cow, Tulip. The film displays the grief and responsibility one feels for those they have loved and lost. Good cinematography, great direction, and superbly acted. It will bring tears to all those who have lost a loved one, and survived.
The batch size is
32
Found 25000 files belonging to 2 classes.
Using 20000 files for training.
Review b'"Pandemonium" is a horror movie spoof that comes off more stupid than funny. ...'
Label 0
Review b"David Mamet is a very interesting and a very un-equal director. ..."
Label 0
Review b'Great documentary about the lives of NY firefighters during the worst terrorist attack of all time..'
Label 1
Label 0 corresponds to neg
Label 1 corresponds to pos
Found 25000 files belonging to 2 classes.
Using 5000 files for validation.
Found 25000 files belonging to 2 classes.

コードの解説

  • 必要なパッケージをインポートし、エイリアスを設定します。
  • IMDBデータをダウンロードし、Colabからアクセスできる場所に保存します。
  • 元データのサンプルをコンソールに表示して内容を確認します。
  • 元データを訓練用データセットと検証用・テスト用データセットに分割します。
  • 訓練データを使用してモデルを構築します。
  • 与えられたレビューを「ネガティブ」か「ポジティブ」かに分類できるように準備します。

この一連の手順により、IMDBデータセットを効率的にダウンロードし、テキスト分類タスク向けに前処理された状態で扱えるようになります。バッチサイズ32、シード値42で分割することで、再現性のある結果が得られます。

  1. TensorFlowとPythonでIMDBデータセットのエポックごとの精度と損失を可視化するグラフを作成する方法

    TensorFlowはGoogleが提供する機械学習フレームワークです。オープンソースとして公開されており、Pythonと組み合わせてアルゴリズムや深層学習アプリケーションの実装などに広く利用されています。研究用途から本番環境まで、さまざまな場面で活用されているフレームワークです。 「IMDB」データセットには、5万件を超える映画レビューが収録されています。このデータセットは、主に自然言語処理(NLP)に関連するタスクで使用されることが一般的です。 以下のコードはGoogle Colaboratory上で実行しています。Google Colab(Colaboratory)を利用すると、ブラウ

  2. 【入門】PythonとTensorFlowでテンソルを作成し、メッセージを表示する方法

    TensorFlowはGoogleが提供する機械学習フレームワークです。オープンソースとして公開されており、Pythonと組み合わせて使用することで、アルゴリズムの実装やディープラーニングアプリケーションの開発など、幅広い用途に活用できます。研究目的から本番環境での運用まで対応しており、複雑な数値計算を高速に実行するための最適化技術も備えています。TensorFlowの特徴TensorFlowはNumPyおよび多次元配列を基盤としています。この多次元配列は「テンソル(tensor)」とも呼ばれます。主な特徴は以下の通りです。ディープニューラルネットワークの構築・学習をサポート高いスケーラビリテ