将密集的张量切成参差不齐的平面值

时间:2020-10-16 18:02:04

标签: python tensorflow

我有一个2D密集张量和一个长度向量,它们是我想选择的每一行的前K个元素:

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

seq_len = tf.constant([3, 3, 2, 5])

所需的输出为:

tf.constant([1, 1, 1, 2, 0, 2, 1, 1, 3, 1, 1, 1, 1])

我尝试过密集操作->衣衫agged以获取固定值,但这不起作用:

>>> tf.RaggedTensor.from_row_lengths(x, seq_len)

InvalidArgumentError: Arguments to _from_row_partition do not form a valid RaggedTensor
Condition x == y did not hold.
First 1 elements of x:
[13]
First 1 elements of y:
[4]

我不能密集->稀疏,因为我想在输出中保留零。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以将密集的张量切片为参差不齐的张量,如下所示

import tensorflow as tf

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

seq_len = tf.constant([3, 3, 2, 5])

要获得所需的输出,可以使用参数padding

tf.RaggedTensor.from_tensor(x, padding=0)

输出:

<tf.RaggedTensor [[1, 1, 1], [2, 0, 2], [1, 1], [3, 1, 1, 1, 1]]>