[英]What is the correct way of pad and reshape a tensor in tensorflow?
給定以下張量:
<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
的正確方法是什么?
如果您使用tf.keras
tf.pad
應該是張量填充的首選(請參閱文檔)。
從看起來你有形狀(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)
默認填充為零,請參閱文檔以獲取其他選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.