简体   繁体   English

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

[英]What is the correct way of pad and reshape a tensor in tensorflow?

Given the following tensor:给定以下张量:

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

What is the correct way of reshape it and pad it into (32, 59) ?重塑它并将其填充到(32, 59)的正确方法是什么? From keras docs I tried to:从 keras 文档我试图:

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

Nevertheles I am getting:尽管如此,我得到了:

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

Also, I tried:另外,我试过:

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

However, I am getting:但是,我得到:

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.

What is the correct way of doing a 32 padding and reshape it into 32,59 ?进行 32 填充并将其重塑为32,59的正确方法是什么?

If you're useing tf.keras tf.pad should be preferred choice for tensor padding ( see docs ).如果您使用tf.keras tf.pad应该是张量填充的首选(请参阅文档)。

From what it looks like you have tensor of shape (59, ) and want to pad the tensor to shape (32, 59) .从看起来你有形状(59, )的张量并且想要将张量填充到形状(32, 59) This would be done as这将做为

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

default padding is with zeros, see the docs for other options.默认填充为零,请参阅文档以获取其他选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM