【问题标题】:What is the correct way of pad and reshape a tensor in tensorflow?在张量流中填充和重塑张量的正确方法是什么?
【发布时间】:2021-07-26 00:56:53
【问题描述】:

给定以下张量:

<tf.Tensor: shape=(59,), dtype=int64, numpy=
array([1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 2, 2, 1, 1, 1, 1, 1, 2, 2, 1, 1,
       1, 0, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1])>

重塑它并将其填充到(32, 59) 的正确方法是什么?从 keras 文档我尝试:

keras.preprocessing.sequence.pad_sequences(t, 32)

尽管如此,我得到了:

ValueError: `sequences` must be a list of iterables. Found non-iterable: tf.Tensor(1, shape=(), dtype=int64)

另外,我试过了:

tf.reshape(tf.data.Dataset.from_tensors(a[0]).padded_batch(32), [32,59])

但是,我得到:

ValueError: Attempt to convert a value (<PaddedBatchDataset shapes: (None, 59), types: tf.int64>) with an unsupported type (<class 'tensorflow.python.data.ops.dataset_ops.PaddedBatchDataset'>) to a Tensor.

进行 32 填充并将其重塑为 32,59 的正确方法是什么?

【问题讨论】:

  • 你可以重复( 59 , ) 32 次来生成一个数组( 32 , 59 )。使用tf.repeat()
  • 你能举个例子吗? @ShubhamPanchal 谢谢
  • 它能解决您的问题吗?这与填充不同。
  • 如果我填充它并重塑它会更好@ShubhamPnchal
  • 查看docs 示例。

标签: python numpy tensorflow keras


【解决方案1】:

如果您使用 tf.keras tf.pad 应该是张量填充 (see docs) 的首选。

从看起来你有形状为(59, ) 的张量并想要填充张量以形成(32, 59) 的形状。这将作为

# 15 rows before, 16 rows after, 0 cols before and after
paddings = tf.constant([[15, 16], [0, 0]])
# first reshape tensor to (1, 59), then pad it
padded = tf.pad(tensor[tf.newaxis, ...], paddings)

默认填充为零,请参阅文档了解其他选项。

【讨论】:

  • 感谢您的帮助。如果我有任意大小的张量,我想将它们全部重塑为(32, n),其中n 是原始形状怎么办?
  • 我试过了:x2=tf.reshape(x, [59,1]) paddings = tf.constant([[15, 16], [0, 0]]) tf.pad(x2, paddings),最后我得到了一个张量shape=(90, 1)
  • 您希望结果是(32, 59) 还是(59, 32)?你想沿着你添加的维度填充,例如,填充应该是tf.constant([[0, 0], [15, 16]]),因为你添加了第一个维度而不是我在答案中所做的第0个维度。关于您之前的问题,n 是标量吗?如果是这样,答案应该有效。如果我们在谈论n 维度张量,这只是巧妙地构造paddings 张量的问题,我可以尝试想一些事情,但是当我不知道我填充的张量的维度时,我觉得很奇怪.
猜你喜欢
  • 2018-07-19
  • 2020-10-13
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
  • 2020-05-10
  • 1970-01-01
相关资源
最近更新 更多