Tensorflow 變量的共享


   

https://github.com/chenghuige/tensorflow-exp/blob/master/examples/sparse-tensor-classification/

   

tensorflow-exp/example/sparse-tensor-classification/train-validate.py

當你需要train的過程中validate的時候,如果用placeholder來接收輸入數據 那么一個compute graph可以完成這個任務。如果你用的是TFRecord的方式 輸入嵌入到compute graph,那么對應input(for train) input_1(for validate),就會產生兩個compute graph,但是要注意的是validate過程中需要share使用等同於train過程的w_h等變量,如果直接build兩次graph就回闡釋下面的示意圖

   

這種並沒有共享 w_h等數據,因此validate 會有問題(注意Input_1里面對應的w_h_1)

cost, accuracy = build_graph(X, label)

_, accuracy_test = build_graph((index_test, value_test), label_test)

train_op = gen_optimizer(cost, FLAGS.learning_rate)

#train_op_test = gen_optimizer(cost_test, FLAGS.learning_rate)

   

來自 <http://git.oschina.net/chenghuige/tensorflow-exp/blob/master/example/sparse-tensor-classification/train-validate.py?dir=0&filepath=example%2Fsparse-tensor-classification%2Ftrain-validate.py&oid=04e0aca92d157121cac257125e2c6a66f68c1e4c&sha=b5f3b6b833ddbb99cc2c9ea763a59a3ab5c564b7>

這里 tf.get_variable_scope().reuse_variables()並不起作用,因為build_graph里面並沒有使用ge_variable機制

   

第一種解決方案 用類 self.w_h

解決此類問題的方法之一就是使用類來創建模塊,在需要的地方使用類來小心地管理他們需要的變量. 一個更高明的做法,不用調用類,而是利用TensorFlow 提供了變量作用域 機制,當構建一個視圖時,很容易就可以共享命名過的變量.

   

來自 <http://wiki.jikexueyuan.com/project/tensorflow-zh/how_tos/variable_scope/index.html>

使用類的方式,共享w_h等變量

class Mlp(object):

def __init__(self):

hidden_size = 200

num_features = NUM_FEATURES

num_classes = NUM_CLASSES

with tf.device('/cpu:0'):

self.w_h = init_weights([num_features, hidden_size], name = 'w_h')

self.b_h = init_bias([hidden_size], name = 'b_h')

self.w_o = init_weights([hidden_size, num_classes], name = 'w_o')

self.b_o = init_bias([num_classes], name = 'b_o')

   

def model(self, X, w_h, b_h, w_o, b_o):

h = tf.nn.relu(matmul(X, w_h) + b_h)

return tf.matmul(h, w_o) + b_o

 

def forward(self, X):

py_x = self.model(X, self.w_h, self.b_h, self.w_o, self.b_o)

return py_x

   

X = (index, value)

algo = Mlp()

cost, accuracy = build_graph(X, label, algo)

cost_test, accuracy_test = build_graph((index_test, value_test), label_test, algo)

train_op = gen_optimizer(cost, FLAGS.learning_rate)

   

類似這種做法的例子tensorflow/tensorflow/models/embedding/word2vec.py

第二中 變量共享

   

 

變量作用域機制在TensorFlow中主要由兩部分組成:

  • tf.get_variable(<name>, <shape>, <initializer>): 通過所給的名字創建或是返回一個變量.
  • tf.variable_scope(<scope_name>): 通過 tf.get_variable()為變量名指定命名空間.

方法 tf.get_variable() 用來獲取或創建一個變量,而不是直接調用tf.Variable.它采用的不是像`tf.Variable這樣直接獲取值來初始化的方法.一個初始化就是一個方法,創建其形狀並且為這個形狀提供一個張量.這里有一些在TensorFlow中使用的初始化變量:

   

代碼

https://github.com/chenghuige/tensorflow-exp/blob/master/examples/sparse-tensor-classification/train-validate-share.py

   

來自 <http://wiki.jikexueyuan.com/project/tensorflow-zh/how_tos/variable_scope/index.html>

   

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM