为num_splits使用变量为tf.split()

bbh*_*hat 9 python tensorflow

是否可以将num_split参数的占位符输入用于tf.split()?

我理想地喜欢这样做:

num_splits = tf.placeholder(tf.int32)
inputs = tf.placeholder(tf.int32, [5, None])
split_inputs = tf.split(1, num_splits, inputs)
Run Code Online (Sandbox Code Playgroud)

我的方法可能有问题.我希望枚举可变形状张量的维度.谢谢!

Yar*_*tov 15

对于核心图操作,存在一种"张量张量输出"的一般哲学,因此如果您可以重构计算以处理可变大小的单张量而不是可变数量的张量,则可以简化操作.

喜欢行动pack,unpack,split处理多张量,但他们在图施工时间,这就是为什么编译为"张量入/张出" OPS num_splits需要修复.OPS像dynamic_partition,dynamic_stitch,dequeue_many接管一些的该功能用于单张量与可变0个维度.

如果你真的需要处理可变数量的张量,典型的方法是将计算分解为多个session.run调用,每次run调用一个输入张量,并使用队列将事物连接在一起.有一个slice_input_producer沿着第0维分割可变大小的输入并为每一行产生张量,所以如果你想myfunction在每一行的循环中进行评估,inputs你可以这样做

def myfunction(vector):
  result = tf.reduce_sum(vector)
  print_result = tf.Print(result, [result], "myfunction called ")
  return print_result

MAX_ROWS = 10

# input matrix with 2 columns and unknown number of rows (<MAX_ROWS)
inputs = tf.placeholder(tf.int32, [None, 2])
# copy of inputs, will need to have a persistent copy of it because we will
# be fetching rows in different session.run calls
data = tf.Variable(inputs, validate_shape=False)
# input producer that iterates over the rows and pushes them onto Queue
row = tf.train.slice_input_producer([data], num_epochs=1, shuffle=False)[0]
myfunction_op = myfunction(row)

# this op will save placeholder values into the variable
init_op = tf.initialize_all_variables()

# Coordinator is not necessary in this case, but you'll need it if you have
# more than one Queue in order to close all queues together
sess = tf.Session()
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)

sess.run([init_op], feed_dict={inputs:[[0, 0], [1, 1], [2, 2]]})

try:
  for i in range(MAX_ROWS):
    sess.run([myfunction_op])
except tf.errors.OutOfRangeError:
  print('Done iterating')
finally:
  # When done, ask other threads to stop.
  coord.request_stop()
Run Code Online (Sandbox Code Playgroud)

如果你运行它,你应该看到

myfunction called [0]
myfunction called [2]
myfunction called [4]
Done iterating
Run Code Online (Sandbox Code Playgroud)