Tensorflow Tensor重塑和填充零 [英] Tensorflow Tensor reshape and pad with zeros

查看:536
本文介绍了Tensorflow Tensor重塑和填充零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以重塑张量并用零填充任何溢出?我知道ndarray.reshape可以做到这一点,但据我所知,将Tensor转换为ndarray将需要GPU和CPU之间的触发器.

Is there a way to reshape a tensor and pad any overflow with zeros? I know ndarray.reshape does this, but as I understand it, converting a Tensor to an ndarray would require flip-flopping between the GPU and CPU.

Tensorflow的reshape()文档说TensorShapes需要具有相同数量的元素,所以也许最好的方法是先先pad()然后再reshape()?

Tensorflow's reshape() documentation says the TensorShapes need to have the same number of elements, so perhaps the best way would be a pad() and then reshape()?

我正在努力实现:

a = tf.Tensor([[1,2],[3,4]])
tf.reshape(a, [2,3])
a => [[1, 2, 3],
      [4, 0 ,0]]

推荐答案

Tensorflow现在提供pad函数,该函数可以通过多种方式对张量执行填充(如opencv2的数组的padding函数): https://www.tensorflow.org/api_docs/python/tf/pad

Tensorflow now offers the pad function which performs padding on a tensor in a number of ways(like opencv2's padding function for arrays): https://www.tensorflow.org/api_docs/python/tf/pad

tf.pad(tensor, paddings, mode='CONSTANT', name=None)

上述文档中的示例:

# 't' is [[1, 2, 3], [4, 5, 6]].
# 'paddings' is [[1, 1,], [2, 2]].
# rank of 't' is 2.
pad(t, paddings, "CONSTANT") ==> [[0, 0, 0, 0, 0, 0, 0],
                                  [0, 0, 1, 2, 3, 0, 0],
                                  [0, 0, 4, 5, 6, 0, 0],
                                  [0, 0, 0, 0, 0, 0, 0]]

pad(t, paddings, "REFLECT") ==> [[6, 5, 4, 5, 6, 5, 4],
                                 [3, 2, 1, 2, 3, 2, 1],
                                 [6, 5, 4, 5, 6, 5, 4],
                                 [3, 2, 1, 2, 3, 2, 1]]

pad(t, paddings, "SYMMETRIC") ==> [[2, 1, 1, 2, 3, 3, 2],
                                   [2, 1, 1, 2, 3, 3, 2],
                                   [5, 4, 4, 5, 6, 6, 5],
                                   [5, 4, 4, 5, 6, 6, 5]]

这篇关于Tensorflow Tensor重塑和填充零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆