python - Tensorflow 张量 reshape 并用零填充

标签 python numpy tensorflow

有没有办法 reshape 张量并用零填充任何溢出?我知道 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() 将给您一个错误)。但是,您可以使用几个不同的运算符获得相同的结果:

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])

关于python - Tensorflow 张量 reshape 并用零填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34141430/

相关文章:

python - 属性错误: module 'tensorflow.contrib.learn' has no attribute 'TensorFlowLinearClassifier'

python - 在 Tensorflow 中训练 wordvec,导入到 Gensim

python - 如何在 Windows 上安装 numpy 和 pandas

python - 无法导入 python-mysqldb

python - 如何在多维数组中插入列?

python - 是否有函数调用可以替代此代码中的 for 循环?

python - Tensorflow Keras 模型 : how to get the best score from a history object

python - 列表上环绕运行窗口

python - 在 Python 中转换为数据框

python - 如果有多个元素,则查找 numpy 数组中最大元素的位置