0

変数とバイアステンソルをトレーニングステップ中にチェックポイントとして保存します。私はtf.contrib.layersからfully_connected()を使用して、いくつかの完全に接続されたレイヤーを実装しました。これを行うには、完全接続されたレイヤーの変数とバイアスのテンソルを抽出する必要があります。それを行う方法?fully_connectedで変数とバイアステンソルにアクセス

答えて

2

ちょうどそれを言及する:

  • ちょうどそれらを保存するために重みとバイアスを抽出する必要はありません。 tf.layersまたはtf.contrib.layersの場合、trainableがTrueに設定されている場合、重みとバイアスはGraphKeys.TRAINABLE_VARIABLESに追加され、GraphKeys.GLOBAL_VARIABLESのサブセットです。したがって、ある時点でsaver = tf.train.Saver(var_list=tf.global_variables())saver.save(sess, save_path, global_step)を使用すると、重みとバイアスが保存されます。
  • 実際に変数を抽出する必要がある場合、一方の方法は、tf.get_variableまたはtf.get_default_graph().get_tensor_by_nameに正しい変数名を使用することです。
  • tf.layer.Densetf.layers.Conv2DなどのTensorFlowクラスに気付いたことがあります。一旦構築されると、体重とバイアステンソルを返す方法がweights/variablesになります。
0

tf.trainable_variables()は、訓練可能なネットワーク内のすべての変数のリストを提供します。ここで述べたようにこれは、variable_scopeとname_scopeを使用することによって、より良い行うことができます:How to get weights from tensorflow fully_connected

In [1]: import tensorflow as tf 

In [2]: a1 = tf.get_variable(name='a1', shape=(1,2), dtype=tf.float32) 

In [3]: fc = tf.contrib.layers.fully_connected(a1, 4) 

In [4]: sess = tf.Session() 
2017-12-17 21:09:18.127498: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations. 
2017-12-17 21:09:18.127554: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations. 
2017-12-17 21:09:18.127578: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations. 
2017-12-17 21:09:18.127598: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations. 
2017-12-17 21:09:18.127618: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations. 

In [5]: tf.trainable_variables() 
Out[5]: 
[<tf.Variable 'a1:0' shape=(1, 2) dtype=float32_ref>, 
<tf.Variable 'fully_connected/weights:0' shape=(2, 4) dtype=float32_ref>, 
<tf.Variable 'fully_connected/biases:0' shape=(4,) dtype=float32_ref>] 

In [6]: for var in tf.trainable_variables(): 
    ...:  if 'weights' in var.name or 'biases' in var.name: 
    ...:   print(var) 
    ...:   
<tf.Variable 'fully_connected/weights:0' shape=(2, 4) dtype=float32_ref> 
<tf.Variable 'fully_connected/biases:0' shape=(4,) dtype=float32_ref> 

In [7]: 
関連する問題