【问题标题】:Dynamically tile a tensor depending on the batch size根据批量大小动态平铺张量
【发布时间】:2017-01-29 16:58:02
【问题描述】:

我有一个一维张量,我想将它堆叠/打包/平铺成一个二维张量,例如y=[a, a, a]。如果我知道我希望它重复多少次,我可以使用 tf.tilereshape

但我不这样做,因为大小取决于批量大小。占位符值为None,它不是有效输入。我知道 tf.slice 可以输入 -1 并让 tensorflow 弄清楚,但我看不出 tensorflow 如何推断出正确的大小。我确实有一个张量 x,它的形状与 y 相同,但我没有看到 tile_like 函数。

有什么建议吗?

【问题讨论】:

标签: python tensorflow


【解决方案1】:

您可以使用tf.shape 找出张量的运行时形状,并将其用作tf.tile 参数的基础:

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, shape=[None, 3])

y = tf.tile([2, 3], tf.shape(x)[0:1])

sess = tf.Session()
print(sess.run(y, feed_dict={x: np.zeros([11, 3])}))

我已验证此代码适用于 Tensorflow 1.0 版本候选者。希望对您有所帮助!

【讨论】:

    【解决方案2】:

    感谢@Peter Hawkins 的出色回答。在许多情况下,需要额外的 reshape 步骤才能将 batch_size 添加为第一个维度。我添加了一个可选的额外步骤来重塑张量:

    import tensorflow as tf
    import numpy as np
    
    batch_dependent_tensor = tf.placeholder(tf.float32, shape=[None, 3])
    other_tensor = tf.constant([2, 3])
    
    y = tf.tile(other_tensor, tf.shape(batch_dependent_tensor)[0:1])
    
    # Reshaping the y tensor by adding the batch_size as the first dimension
    new_shape = tf.concat([tf.shape(batch_dependent_tensor)[0:1], tf.shape(other_tensor)[0:1]], axis=0)
    y_reshaped = tf.reshape(y, new_shape)
    
    sess = tf.Session()
    y_val, y_reshaped_val = sess.run([y, y_reshaped], feed_dict={batch_dependent_tensor: np.zeros([11, 3])})
    print("y_val has shape %s, and value: %s" %(y_val.shape, y_val))
    print("y_reshaped_val has shape %s, and value: %s" %(y_reshaped_val.shape, y_reshaped_val))
    
    """
    # print output:
    
    y_val has shape (22,), and value: [2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3]
    y_reshaped_val has shape (11, 2), and value: [[2 3]
     [2 3]
     [2 3]
     [2 3]
     [2 3]
     [2 3]
     [2 3]
     [2 3]
     [2 3]
     [2 3]
     [2 3]]
    """
    

    请注意,如果 other_tensor 的秩 > 1(它是矩阵或更高维度的张量),则需要对代码进行一些修改。

    【讨论】:

      猜你喜欢
      • 2019-04-24
      • 2016-12-12
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 2020-01-03
      相关资源
      最近更新 更多