有没有办法重塑张量并用零填充任何溢出?我知道 ndarray.reshape 会这样做,但据我了解,将 Tensor 转换为 ndarray 需要在 GPU 和 CPU 之间进行翻转。
Tensorflow 的 reshape() 文档说 TensorShapes 需要具有相同数量的元素,所以也许最好的方法是 pad() 然后 reshape()?
我正在努力实现:
a = tf.Tensor([[1,2],[3,4]])
tf.reshape(a, [2,3])
a => [[1, 2, 3],
[4, 0 ,0]]
据我所知,没有内置运算符可以执行此操作(tf.reshape() https://www.tensorflow.org/versions/master/api_docs/python/array_ops.html#reshape如果形状不匹配,则会出现错误)。但是,您可以使用几个不同的运算符获得相同的结果:
a = tf.constant([[1, 2], [3, 4]])
# Reshape `a` as a vector. -1 means "set this dimension automatically".
a_as_vector = tf.reshape(a, [-1])
# Create another vector containing zeroes to pad `a` to (2 * 3) elements.
zero_padding = tf.zeros([2 * 3] - tf.shape(a_as_vector), dtype=a.dtype)
# Concatenate `a_as_vector` with the padding.
a_padded = tf.concat([a_as_vector, zero_padding], 0)
# Reshape the padded vector to the desired shape.
result = tf.reshape(a_padded, [2, 3])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)