【问题标题】:Equivalent of np.resize in TensorFlowTensorFlow 中的 np.resize 等价物
【发布时间】:2020-10-20 19:34:26
【问题描述】:

我有一个一维数组x 并希望以与np.resize 相同的方式将其重塑为请求的形状,即如果x 中有太多元素,则它们会被删除,如果它太多很少,它们是循环添加的,例如

x = np.array([1, 2, 3, 4, 5, 6])
y = np.resize(x, shape=(2, 2))
assert y == np.array([[1, 2], [3, 4]])
z = np.resize(x, shape=(3, 3))
assert z == np.array([[1, 2, 3], [4, 5, 6], [1, 2, 3]])

我想知道如何仅使用 TensorFlow 中的张量运算符来做到这一点。

【问题讨论】:

    标签: tensorflow tensor


    【解决方案1】:

    我不确定这在 TF 中的单个操作中是否可行,但可以使用crops 或tf.tile 编写函数,然后对结果进行整形。

    【讨论】:

      【解决方案2】:

      感谢Poe Datorhints 我最终得到了以下解决方案:

      def tf_resize(t, shape):
          """
          Args:
            t: a `Tensor`
            shape: requested output shape
          """
          input_size = tf.size(t)
          output_size = tf.reduce_prod(shape)
          t_flatten = tf.reshape(t, [input_size])
          result = tf.tile(t_flatten, [output_size // input_size + 1])
          return tf.reshape(result[0:output_size], shape=shape)
      

      【讨论】:

        猜你喜欢
        • 2017-03-18
        • 2017-01-14
        • 2016-05-11
        • 1970-01-01
        • 2019-03-24
        • 2020-11-04
        • 1970-01-01
        • 2017-06-05
        • 1970-01-01
        相关资源
        最近更新 更多