简体   繁体   English

如何用起始值预填充 tensorflow 参差不齐的张量

[英]How to pre-pad tensorflow ragged tensor with beginning values

This question is similar to this question:这个问题类似于这个问题:

pad last dimension of tensor 填充张量的最后一个维度

with the exception that I would like to pre-pad this tensor with the beginning values.除了我想用起始值预先填充这个张量。 Given the ragged tensor:鉴于参差不齐的张量:

 [[1],
 [4, 2],
 [1, 2, 3]]

I would expect the output to be:我希望 output 是:

[[1 1 1],
 [4 4 2],
 [1 2 3]]

I would like to be able to apply the solution to a larger ragged tensor.我希望能够将解决方案应用于更大的参差不齐的张量。

Just use the properties of a ragged tensor:只需使用参差不齐的张量的属性:

import tensorflow as tf

x = tf.ragged.constant([[1],
                        [4, 2],
                        [1, 2, 3]])

rows_to_pad = tf.abs(x.row_lengths() - tf.reduce_max(x.row_lengths()))

padded_x = tf.concat([tf.RaggedTensor.from_row_lengths(
    values=tf.repeat(tf.gather(x.merge_dims(0, -1), x.row_starts()), rows_to_pad, axis=0),
    row_lengths=rows_to_pad), x], axis=-1).to_tensor()
[[1 1 1]
 [4 4 2]
 [1 2 3]]

A different ragged tensor:一个不同的参差不齐的张量:

x = tf.ragged.constant([[1, 4, 5, 6, 7, 8, 3],
                        [4, 2],
                        [1, 2, 3], 
                        [1, 2, 3, 4, 5], 
                        [1]])

Pre-padded:预填充:

[[1 4 5 6 7 8 3]
 [4 4 4 4 4 4 2]
 [1 1 1 1 1 2 3]
 [1 1 1 2 3 4 5]
 [1 1 1 1 1 1 1]]

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

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