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

TensorFlowのEstimatorとPythonを使ってモデルをトレーニング(コンパイル)する方法

TensorFlowでは、Estimatorのtrainメソッドを使用することで、モデルのコンパイルと学習を行うことができます。

本記事では、Keras Sequential APIを使用します。このAPIは、各レイヤーが正確に1つの入力テンソルと1つの出力テンソルを持つ、シンプルなレイヤーの積み重ねで構成される逐次モデルを構築するのに適しています。

前提知識

少なくとも1つの畳み込み層(Convolutional Layer)を含むニューラルネットワークは、畳み込みニューラルネットワーク(CNN)と呼ばれ、学習モデルの構築に利用できます。また、TensorFlow Textには、TensorFlow 2.0と組み合わせて使用できるテキスト関連のクラスやオペレーションがまとめられており、系列モデリングの前処理などに活用できます。

以下のコードはGoogle Colaboratory上で実行しています。Google Colab(Colaboratory)はブラウザ上でPythonコードを実行できる環境で、事前設定が不要であり、GPU(グラフィックス処理ユニット)へ無料でアクセスできます。ColaboratoryはJupyter Notebookをベースに構築されています。

Estimatorとは

Estimatorは、TensorFlowにおける完全なモデルの高レベルな表現です。スケーリングや非同期学習を容易に行えるよう設計されています。

ここでは、アヤメ(Iris)データセットを使用してモデルを学習させます。このデータセットには4つの特徴量と1つのラベルが含まれています。

  • がく片の長さ(sepal length)
  • がく片の幅(sepal width)
  • 花びらの長さ(petal length)
  • 花びらの幅(petal width)

コード例

print("The model is being trained")
classifier.train(input_fn=lambda: input_fn(train, train_y, training=True), steps=5000)

コード出典:https://www.tensorflow.org/tutorials/estimator/premade#first_things_first

出力結果

WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.
INFO:tensorflow:Calling model_fn.
WARNING:tensorflow:Layer dnn is casting an input tensor from dtype float64 to the layer's dtype of float32, which is new behavior in TensorFlow 2. The layer has dtype float32 because its dtype defaults to floatx.
If you intended to run this layer in float32, you can safely ignore this warning. If in doubt, this warning is likely only an issue if you are porting a TensorFlow 1.X model to TensorFlow 2.
To change all layers to have dtype float64 by default, call `tf.keras.backend.set_floatx('float64')`. To change just this layer, pass dtype='float64' to the layer constructor. If you are the author of this layer, you can disable autocasting by passing autocast=False to the base Layer constructor.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmpbhg2uvbr/model.ckpt.
INFO:tensorflow:loss = 1.1140382, step = 0
INFO:tensorflow:global_step/sec: 312.415
INFO:tensorflow:loss = 0.8781501, step = 100 (0.321 sec)
INFO:tensorflow:global_step/sec: 375.535
INFO:tensorflow:loss = 0.80712265, step = 200 (0.266 sec)
...
INFO:tensorflow:loss = 0.37167495, step = 4900 (0.273 sec)
INFO:tensorflow:Saving checkpoints for 5000 into /tmp/tmpbhg2uvbr/model.ckpt.
INFO:tensorflow:Loss for final step: 0.36297452.
<tensorflow_estimator.python.estimator.canned.dnn.DNNClassifierV2 at 0x7fc9983ed470>

※出力ログは長いため、途中の中間ステップ(step 300〜4800付近)は省略して表示しています。実際には5000ステップまで損失(loss)が段階的に減少しながら学習が進行します。

解説

Estimatorオブジェクトを作成すると、以下のような操作を呼び出すことができます。

  • モデルの学習: Estimatorのtrainメソッドを呼び出すことで実行されます。input_fn引数には入力データを供給する関数を渡し、steps引数で学習ステップ数を指定します。
  • モデルの評価: 学習済みモデルの性能をevaluateメソッドで評価できます。
  • 予測の実行: 学習済みモデルを使ってpredictメソッドにより新しいデータに対する予測を行えます。
  • 再学習: 必要に応じて、同じモデルを再度trainメソッドで追加学習することも可能です。

出力結果を見ると、初期の損失値が約1.11だったのに対し、5000ステップの学習完了時には約0.36まで低下しており、モデルがデータから適切に学習できていることが確認できます。また、チェックポイント(checkpoint)が自動的に保存されるため、学習の中断・再開にも対応できます。

  1. PythonとKerasを使ってモデル全体を保存・再利用する方法を徹底解説

    TensorFlowとKerasとはTensorFlowは、Googleが提供する機械学習フレームワークです。オープンソースとして公開されており、Pythonと組み合わせて使用することで、各種アルゴリズムやディープラーニングアプリケーションの実装が可能になります。研究用途から本番環境まで幅広く活用されています。KerasはPythonで書かれたディープラーニングAPIです。高水準APIとして設計されており、生産性の高いインターフェースによって機械学習の問題を効率的に解決できます。TensorFlowフレームワーク上で動作し、素早い実験・試行を支援するために開発されました。高いスケーラビリティと

  2. Kerasを使ってPythonでモデルをプロットする方法をわかりやすく解説

    TensorFlowとはTensorFlowは、Googleが提供している機械学習フレームワークです。オープンソースとして公開されており、Pythonと組み合わせて使用することで、アルゴリズムの実装やディープラーニングアプリケーションの開発など、幅広い用途に活用できます。研究目的から本番環境での運用まで対応しており、複雑な数値計算を高速に実行するための最適化技術が数多く組み込まれています。TensorFlowにおける「テンソル(Tensor)」は、データを扱うための基本的なデータ構造です。テンソルは多次元配列(またはリスト)であり、データフローグラフと呼ばれる計算グラフのノード同士をエッジでつ