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

TensorFlowとPythonを使ってStack Overflowの質問データセットを読み込む方法

TensorFlowはGoogleが提供する機械学習フレームワークです。オープンソースとして公開されており、Pythonと組み合わせてアルゴリズムやディープラーニングアプリケーションの実装など、幅広い用途に活用されています。研究開発から本番環境まで対応しており、複雑な数学的演算を高速に実行するための最適化技術を備えているのが特長です。

その理由は、NumPyと多次元配列を基盤としている点にあります。この多次元配列は「テンソル」とも呼ばれます。TensorFlowは深層ニューラルネットワークの構築をサポートし、高いスケーラビリティを持つほか、人気の高いデータセットが多数同梱されています。また、GPU演算を利用でき、リソース管理も自動化されます。豊富な機械学習ライブラリが付属し、ドキュメントやサポートも充実しているため、深層ニューラルネットワークモデルの構築・学習、さらにはデータセットの関連する特性を予測するアプリケーションの作成まで行えます。

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

pip install tensorflow

以降のコードはGoogle Colaboratory上で実行することを想定しています。Google Colab(Colaboratory)を利用すれば、ブラウザ上で直接Pythonコードを実行でき、面倒な設定は一切不要です。さらにGPU(グラフィックス処理装置)にも無料でアクセスできます。ColaboratoryはJupyter Notebookをベースに構築されています。それでは、Pythonを使ってStack Overflowの質問データセットを読み込むコードを見てみましょう。

サンプルコード

batch_size = 32
seed = 42
print("The training parameters have been defined")
raw_train_ds = preprocessing.text_dataset_from_directory(
    train_dir,
    batch_size=batch_size,
    validation_split=0.25,
    subset='training',
    seed=seed)
for text_batch, label_batch in raw_train_ds.take(1):
    for i in range(10):
        print("Question: ", text_batch.numpy()[i][:100], '...')
        print("Label:", label_batch.numpy()[i])

コード出典:https://www.tensorflow.org/tutorials/load_data/text

出力結果

The training parameters have been defined
Found 8000 files belonging to 4 classes.
Using 6000 files for training.
Question: b'"my tester is going to the wrong constructor i am new to programming so if i ask a
question that can' ...
Label: 1
Question: b'"blank code slow skin detection this code changes the color space to lab and using a
threshold finds' ...
Label: 3
Question: b'"option and validation in blank i want to add a new option on my system where i
want to add two text' ...
Label: 1
Question: b'"exception: dynamic sql generation for the updatecommand is not supported against
a selectcommand th' ...
Label: 0
Question: b'"parameter with question mark and super in blank, i\'ve come across a method that
is formatted like t' ...
Label: 1
Question: b'call two objects wsdl the first time i got a very strange wsdl. ..i would like to call the
object (i' ...
Label: 0
Question: b'how to correctly make the icon for systemtray in blank using icon sizes of any
dimension for systemt' ...
Label: 0
Question: b'"is there a way to check a variable that exists in a different script than the original
one? i\'m try' ...
Label: 3
Question: b'"blank control flow i made a number which asks for 2 numbers with blank and
responds with the corre' ...
Label: 0
Question: b'"credentials cannot be used for ntlm authentication i am getting
org.apache.commons.httpclient.auth.' ...
Label: 1

解説

  • データはディスクから読み込まれ、学習に適した形式へと準備されます。

  • 「text_dataset_from_directory」ユーティリティを使用して、ラベル付きデータセットを作成しています。

  • 「tf.data」は強力なツール群であり、入力パイプラインの構築に活用されます。

  • ディレクトリ構造が「text_dataset_from_directory」ユーティリティに渡されます。

  • Stack Overflowの質問データセットは、訓練用データセットとテスト用データセットに分割されています。

  • 「validation_split」メソッドを使って検証用データセットが作成されます。

  • ラベルは0、1、2、3のいずれかの値を取ります。

  1. TensorFlowとPythonを使ってデータセットを視覚化する方法

    ここでは、花のデータセットを使用します。このデータセットは、Googleが提供するAPI経由でダウンロードでき、「get_file」メソッドにAPIのURLを引数として渡すことで、データを開発環境に取得できます。 ダウンロードしたデータは「matplotlib」ライブラリを使って視覚化できます。「imshow」メソッドを使用すると、コンソール上に画像を表示することが可能です。 TensorFlowとKerasの連携 関連記事: TensorFlowとは何か?KerasはどのようにTensorFlowと連携してニューラルネットワークを構築するのか? 本記事ではKeras Sequential

  2. TensorFlowとPythonを使って花のデータセットを可視化する方法

    花のデータセットは、matplotlibライブラリを使用することで簡単に可視化できます。imshowメソッドを使うと、画像をコンソール上に表示でき、データセット全体を反復処理しながら最初の数枚の画像だけを出力するといったことも可能です。使用するデータセットについて本記事では、数千枚の花の画像を含む「flowers(花)」データセットを使用します。このデータセットには5つのサブディレクトリが含まれており、各クラス(花の種類)ごとに1つのサブディレクトリが割り当てられています。なお、以下のコードはGoogle Colaboratoryで実行することを想定しています。Google Colab(Col