如何在tensorflow中填充序列

如何在tensorflow中填充序列,tensorflow,sequence,pad,Tensorflow,Sequence,Pad,我有一个包含不规则张量的数据集,如下所示: 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

我有一个包含不规则张量的数据集,如下所示:

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]]>
<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]]>
non_ragged_dataset=tf.data.dataset.from_tensor_切片([1,5,3,2,8])
non_ragged_dataset=non_ragged_dataset.map(tf.range)
批处理非不规则数据集=非不规则数据集。应用(
tf.数据.实验.密集至不规则批次(2))
对于成批\u非\u不规则\u数据集中的元素:
打印(元素)
----输出----
每个碎布传感器表示一个序列,形状为(无,无)。我想将序列转换为length=5,即shape=(5,无),如下所示:

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


有什么办法吗?谢谢大家

您只需将必要数量的行连接到每个不规则张量:

将tensorflow导入为tf
def pad_不规则_阵列(长度):
def变换(r):
pad_size=tf.math.max(长度-r.nrows(),0)
返回tf.concat([r,tf.zeros([pad_size,1],dtype=r.dtype)],轴=0)
返回变换
长度=5
dataset=(tf.data.dataset.from_张量_切片([1,5,3,2,8]))
.map(tf.range)
.应用(tf.数据.实验.密集型至不规则型批次(2))
.map(pad_ragged_数组(长度)))
对于数据集中的元素:
打印(元素)
# 
# 
# 

我不理解您要执行的转换。第一个参差不齐的张量增加了2行,因此现在它有4行。第二个添加了3,得到5行,最后一个添加了4,得到5行。我不明白这与
length=10
有什么关系。哦,对不起,我会修复它的。我已经尝试过多次使用padded\u batch函数,但都失败了:
dataset.padded\u batch(batch\u size=2,padded\u shapes=(5,None),padding\u value=[0])
dataset.padded\u batch(batch\u size=2,padded\u shaped\u=(5,None),padding\u value=0)
数据集。填充的批次(批次大小=2,填充的形状=5,填充值=[0])
或。。。