首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在tensorflow中填充序列

如何在tensorflow中填充序列
EN

Stack Overflow用户
提问于 2020-06-12 18:57:32
回答 1查看 282关注 0票数 1

我有一个包含粗糙张量的数据集,如下所示:

代码语言:javascript
复制
non_ragged_dataset = tf.data.Dataset.from_tensor_slices([1, 5, 3, 2, 8])
non_ragged_dataset = non_ragged_dataset.map(tf.range)
batched_non_ragged_dataset = non_ragged_dataset.apply(
    tf.data.experimental.dense_to_ragged_batch(2))
for element in batched_non_ragged_dataset:
    print(element)
----output----
<tf.RaggedTensor [[0], [0, 1, 2, 3, 4]]>
<tf.RaggedTensor [[0, 1, 2], [0, 1]]>
<tf.RaggedTensor [[0, 1, 2, 3, 4, 5, 6, 7]]>

每个RaggedTensor表示一个序列,形状为(None,None)。我想将序列转换为length=5,即shape=(5,None),如下所示:

代码语言:javascript
复制
<tf.RaggedTensor [[0], [0, 1, 2, 3, 4], [0], [0], [0]]>
<tf.RaggedTensor [[0, 1, 2], [0, 1], [0], [0], [0]]>
<tf.RaggedTensor [[0, 1, 2, 3, 4, 5, 6, 7], [0], [0], [0], [0]]>

有什么办法吗?谢谢大家!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-12 19:49:46

您可以将所需的行数连接到每个参差不齐的张量:

代码语言:javascript
复制
import tensorflow as tf

def pad_ragged_arrays(length):
    def transform(r):
        pad_size = tf.math.maximum(length - r.nrows(), 0)
        return tf.concat([r, tf.zeros([pad_size, 1], dtype=r.dtype)], axis=0)
    return transform

length = 5
dataset = (tf.data.Dataset.from_tensor_slices([1, 5, 3, 2, 8])
           .map(tf.range)
           .apply(tf.data.experimental.dense_to_ragged_batch(2))
           .map(pad_ragged_arrays(length)))
for element in dataset:
    print(element)
# <tf.RaggedTensor [[0], [0, 1, 2, 3, 4], [0], [0], [0]]>
# <tf.RaggedTensor [[0, 1, 2], [0, 1], [0], [0], [0]]>
# <tf.RaggedTensor [[0, 1, 2, 3, 4, 5, 6, 7], [0], [0], [0], [0]]>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62342837

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档