tensorflow 中的獲取動態獲取 BatchSzie 的大小

import tensorflow as tf
import sys

with tf.variable_scope('ha'):
    a1 = tf.get_variable('a', shape=[], dtype=tf.int32)
    with tf.variable_scope('haha'):
        a2 = tf.get_variable('a', shape=[], dtype=tf.int32)
        with tf.variable_scope('hahaha'):
            a3 = tf.get_variable('a', shape=[], dtype=tf.int32)

with tf.variable_scope('ha', reuse=True):
    # 不會創建新的變量
    a4 = tf.get_variable('a', shape=[], dtype=tf.int32)
    
sum = a1 + a2 + a3 + a4

fts_s = tf.placeholder(tf.float32, shape=(None, 100), name='fts_s')
b = tf.zeros(shape=(tf.shape(fts_s)[0], tf.shape(fts_s)[1]))

concat = tf.concat(axis=1, values=[fts_s, b])

init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    for var in tf.global_variables():
        print var.name
    import numpy as np
    ft_sample = np.ones((10, 100))
    con_value = sess.run([concat], feed_dict={fts_s: ft_sample})
    print con_value[0].shape

results:

ha/a:0
ha/haha/a:0
ha/haha/hahaha/a:0
(10, 200)

小總結:
1: 對於未知的shape, 最常用的就是batch-size 通常是 None 代替, 那麼在代碼中需要用到實際數據的batch size的時候應該怎麼做呢?
可以傳一個tensor類型, tf.shape(Name) 返回一個tensor 類型的數據, 然後取batchsize 所在的維度即可. 這樣就能根據具體的數據去獲取batch size的大小

2: 對於變量命名, 要善於用 variable_scope 來規範化命名, 以及 reuse 參數可以控制共享變量

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章