我就廢話不多說了,大家還是直接看代碼吧~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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 參數可以控制共享變量
補充知識:tensorflow RNN 使用動態的batch_size
在使用tensorflow實現RNN模型時,需要初始化隱藏狀態 如下:
1
2
3
|
lstm_cell_1 = [tf.nn.rnn_cell.DropoutWrapper(tf.nn.rnn_cell.BasicLSTMCell(HIDDEN_SIZE),output_keep_prob = dropout_keep_prob) for _ in range (NUM_LAYERS)] cell_1 = tf.nn.rnn_cell.MultiRNNCell(lstm_cell_1) self .init_state_1 = cell_1.zero_state( self .batch_size,tf.float32) |
如果我們直接使用超參數batch_size初始化 在使用模型預測的結果時會很麻煩。我們可以使用動態的batch_size,就是將batch_size作為一個placeholder,在運行時,將batch_size作為輸入輸入就可以實現根據數據量的大小使用不同的batch_size。
代碼實現如下:
self.batch_size = tf.placeholder(tf.int32,[],name='batch_size')
self.state = cell.zero_state(self.batch_size,tf.float32)
以上這篇tensorflow 動態獲取 BatchSzie 的大小實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/zjm750617105/article/details/82959175