TensorFlow 2.4 : ガイド : 基本 – 変数へのイントロダクション (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 12/23/2020
* 本ページは、TensorFlow org サイトの Guide – TensorFlow Basics の以下のページを翻訳した上で
適宜、補足説明したものです:
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
- Windows PC のブラウザからご参加が可能です。スマートデバイスもご利用可能です。
人工知能研究開発支援 | 人工知能研修サービス | テレワーク & オンライン授業を支援 |
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。 |
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション |
E-Mail:sales-info@classcat.com ; WebSite: https://www.classcat.com/ |
Facebook: https://www.facebook.com/ClassCatJP/ |
ガイド : 基本 – 変数へのイントロダクション
TensorFlow 変数は貴方のプログラムが操作する共有される、永続的な状態を表すために推奨される方法です。このガイドは TensorFlow で tf.Variable のインスタンスをどのように作成し、更新し、そして管理するかをカバーします。
変数は tf.Variable クラスを通して作成されて追跡されます。tf.Variable は tensor を表し、その値はその上で ops を実行することにより変更できます。特定の ops はこの tensor の値を読みそして変更することを可能にします。tf.keras のような高位ライブラリはモデルパラメータをストアするために tf.Variable を利用します。
セットアップ
このノートブックは変数配置について議論します。貴方の変数がどのデバイスの上に置かれているか見たいときは、この行をアンコメントします。
import tensorflow as tf # Uncomment to see where your variables get placed (see below) # tf.debugging.set_log_device_placement(True)
変数を作成する
変数を作成するには、初期値を供給します。tf.Variable は初期値と同じ dtype を持ちます。
my_tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]]) my_variable = tf.Variable(my_tensor) # Variables can be all kinds of types, just like tensors bool_variable = tf.Variable([False, False, False, True]) complex_variable = tf.Variable([5 + 4j, 6 + 1j])
変数は tensor のように見えて動作します、そして実際に、tf.Tensor により支援されるデータ構造です。tensor のように、それらは dtype と shape を持ち、そして NumPy にエクスポートできます。
print("Shape: ", my_variable.shape) print("DType: ", my_variable.dtype) print("As NumPy: ", my_variable.numpy())
Shape: (2, 2) DType: <dtype: 'float32'> As NumPy: [[1. 2.] [3. 4.]]
殆どの tensor 演算は変数上で期待どおりに動作します、変数は reshape できませんけれども。
print("A variable:", my_variable) print("\nViewed as a tensor:", tf.convert_to_tensor(my_variable)) print("\nIndex of highest value:", tf.argmax(my_variable)) # This creates a new tensor; it does not reshape the variable. print("\nCopying and reshaping: ", tf.reshape(my_variable, ([1,4])))
A variable: <tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy= array([[1., 2.], [3., 4.]], dtype=float32)> Viewed as a tensor: tf.Tensor( [[1. 2.] [3. 4.]], shape=(2, 2), dtype=float32) Index of highest value: tf.Tensor([1 1], shape=(2,), dtype=int64) Copying and reshaping: tf.Tensor([[1. 2. 3. 4.]], shape=(1, 4), dtype=float32)
上で記されたように、変数は tensor により支援されます。tf.Variable.assign を使用して tensor を再割当てできます。assign の呼び出しは (通常は) 新しい tensor を割当てません ; 代わりに、既存の tensor のメモリが再利用されます。
a = tf.Variable([2.0, 3.0]) # This will keep the same dtype, float32 a.assign([1, 2]) # Not allowed as it resizes the variable: try: a.assign([1.0, 2.0, 3.0]) except Exception as e: print(f"{type(e).__name__}: {e}")
ValueError: Cannot assign to variable Variable:0 due to variable shape (2,) and value shape (3,) are incompatible
演算で変数を tensor のように使用する場合、通常は支援 tensor 上で演算します。
既存の変数からの新しい変数の作成は支援 tensor を複製します。2 つの変数は同じメモリを共有しません。
a = tf.Variable([2.0, 3.0]) # Create b based on the value of a b = tf.Variable(a) a.assign([5, 6]) # a and b are different print(a.numpy()) print(b.numpy()) # There are other versions of assign print(a.assign_add([2,3]).numpy()) # [7. 9.] print(a.assign_sub([7,9]).numpy()) # [0. 0.]
[5. 6.] [2. 3.] [7. 9.] [0. 0.]
ライフサイクル、名前付け、そして監視
Python ベースの TensorFlow では、tf.Variable インスタンスは他の Python オブジェクトと同じライフサイクルを持ちます。変数への参照がないときそれは自動的に割当て解除されます (= deallocate)。
変数はまた名前付けできます、これはそれらを追跡してデバッグするのに役立つことができます。2 つの変数に同じ名前を与えることができます。
# Create a and b; they will have the same name but will be backed by # different tensors. a = tf.Variable(my_tensor, name="Mark") # A new variable with the same name, but different value # Note that the scalar add is broadcast b = tf.Variable(my_tensor + 1, name="Mark") # These are elementwise-unequal, despite having the same name print(a == b)
tf.Tensor( [[False False] [False False]], shape=(2, 2), dtype=bool)
変数名はモデルをセーブしてロードするとき保存されます。デフォルトで、モデルの変数は一意な変数名を自動的に獲得しますので、(貴方が望まない限りは) それらを貴方自身で割当てる必要はありません。
変数は微分のために重要ですが、幾つかの変数は微分されることを必要としません。作成時に trainable を false に設定することにより変数のための勾配を無効にできます。勾配を必要としない変数の例は訓練ステップ・カウンターです。
step_counter = tf.Variable(1, trainable=False)
変数と tensor を配置する
より良いパフォーマンスのために、TensorFlow は tensor と変数をその dtype と互換な最速のデバイス上に配置することを試みます。これは殆どの変数は (1 つが利用可能であれば) GPU 上に置かれることを意味します。
けれども、これを override できます。このスニペットでは、GPU が利用可能な場合でさえ、float tensor と変数を CPU 上に置きます。デバイス配置ロギングを有効にすることにより (セットアップ参照)、変数がどこに置かれるかを見ることができます。
Note: 手動の配置は動作しますが、分散ストラテジーは貴方の計算を最適化するためにより便利でスケーラブルな方法であり得ます。
このノートブックを GPU あり/なしで異なるバックエンドで実行する場合、異なるロギングを見るでしょう。デバイス配置のロギングはセッションの開始時に有効にされなければいけないことに注意してください。
with tf.device('CPU:0'): # Create some tensors a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) c = tf.matmul(a, b) print(c)
Executing op VarHandleOp in device /job:localhost/replica:0/task:0/device:CPU:0 Executing op AssignVariableOp in device /job:localhost/replica:0/task:0/device:CPU:0 Executing op DestroyResourceOp in device /job:localhost/replica:0/task:0/device:GPU:0 Executing op ReadVariableOp in device /job:localhost/replica:0/task:0/device:CPU:0 Executing op MatMul in device /job:localhost/replica:0/task:0/device:CPU:0 tf.Tensor( [[22. 28.] [49. 64.]], shape=(2, 2), dtype=float32)
変数や tensor の位置を一つのデバイス上に設定して他のデバイス上で計算を行なうことが可能です。これは遅延を取り込むでしょう、データはデバイス間でコピーされる必要があるからです。
けれども、複数の GPU ワーカーを持ちながら変数の 1 つのコピーだけを望む場合に、これを行なうかもしれません。
with tf.device('CPU:0'): a = tf.Variable([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) b = tf.Variable([[1.0, 2.0, 3.0]]) with tf.device('GPU:0'): # Element-wise multiply k = a * b print(k)
Executing op VarHandleOp in device /job:localhost/replica:0/task:0/device:CPU:0 Executing op AssignVariableOp in device /job:localhost/replica:0/task:0/device:CPU:0 Executing op DestroyResourceOp in device /job:localhost/replica:0/task:0/device:CPU:0 Executing op VarHandleOp in device /job:localhost/replica:0/task:0/device:CPU:0 Executing op AssignVariableOp in device /job:localhost/replica:0/task:0/device:CPU:0 Executing op ReadVariableOp in device /job:localhost/replica:0/task:0/device:CPU:0 Executing op ReadVariableOp in device /job:localhost/replica:0/task:0/device:CPU:0 Executing op Mul in device /job:localhost/replica:0/task:0/device:GPU:0 tf.Tensor( [[ 1. 4. 9.] [ 4. 10. 18.]], shape=(2, 3), dtype=float32)
Note: tf.config.set_soft_device_placement がデフォルトで有効にされていますので、GPU なしのデバイス上このコードを実行する場合でさえも、それは依然として動作します。乗算ステップは CPU 上で発生します。
分散訓練のより多くについては、ガイド を見てください。
以上