在张量流中填充和重塑张量的正确方法是什么?

时间:2021-07-26 00:56:53

标签: python numpy tensorflow keras

给定以下张量:

<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 的正确方法是什么?

1 个答案:

答案 0 :(得分: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)

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

相关问题