【问题标题】:Reshape batch of tensors into batch of vectors in TensorFlow在 TensorFlow 中将一批张量重塑为一批向量
【发布时间】:2017-04-07 18:16:41
【问题描述】:

在创建计算图期间,我有一个张量 x,例如形状为[-1, a, b, c],我想将其重塑为[-1, a*b*c] 我试着这样做:

n = functools.reduce(operator.mul, x.shape[1:], 1)
tf.reshape(x, [-1, n])

但我有一个错误:

TypeError: unsupported operand type(s) for *: 'int' and 'Dimension'

我的问题是:有 TensorFlow 做这个操作吗?

【问题讨论】:

    标签: python tensorflow reshape dimension


    【解决方案1】:

    正如错误消息告诉您的那样,类型存在问题。如果您创建 TensorFlow 占位符,例如与

    >>> import tensorflow as tf
    >>> x = tf.placeholder(tf.float16, shape=(None, 3,7,4))
    

    并在其上调用shape,则返回值为

    >>> x.shape
    TensorShape([Dimension(None), Dimension(3), Dimension(7), Dimension(4)])
    

    每个元素都是一个

    >>> x.shape[1]
    <class 'tensorflow.python.framework.tensor_shape.Dimension'>
    

    即TensorFlow 的 Dimension 类。当然,operator.mul 函数不知道如何处理这种类型。幸运的是,tf.TensorShape 有一个 as_list() 函数,它将形状作为整数列表返回。

    >>> x.shape.as_list()
    [None, 3, 7, 4]
    

    这样,您就可以计算出n 的元素数量,就像您习惯的那样:

    >>> import functools, operator
    >>> n = functools.reduce(operator.mul, x.shape.as_list()[1:], 1)
    >>> n 
    84
    >>> y = tf.reshape(x, [-1, n])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 2016-02-15
      • 2020-09-01
      • 1970-01-01
      • 2017-11-05
      相关资源
      最近更新 更多