You need to enable JavaScript to run this app. TensorFlow原生实现全零行前向填充的方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow原生实现全零行前向填充的方法咨询

用TensorFlow原生方法填充张量全零行为上一个非全零行的值

可以通过TensorFlow原生操作实现这个需求,无需使用tf.tensor_scatter_nd_update,具体步骤如下:

1. 定义输入张量

import tensorflow as tf

input_tensor = tf.constant([
    [1., 0., 3.],
    [7., 5., 6.],
    [0., 0., 0.],
    [0., 11., 1.],
    [0., 0., 0.],
    [0., 0., 0.],
    [13., 14., 16.5]
])

2. 生成非全零行掩码

先判断每行是否为全零行,生成布尔类型的掩码张量(True表示该行非全零):

non_zero_mask = tf.reduce_any(input_tensor != 0., axis=1)

3. 构建索引并填充

通过tf.cumsum为连续的全零行分配上一个非零行的索引,再用tf.gather提取对应行的值完成填充:

# 生成索引:非零行对应自身行号,全零行继承上一个非零行的行号
indices = tf.cumsum(tf.cast(non_zero_mask, tf.int32)) - 1
# 按索引收集行,得到填充后的张量
filled_tensor = tf.gather(input_tensor, indices)

验证结果

执行上述代码后,打印filled_tensor.numpy()会得到目标结果:

[[ 1.   0.   3. ]
 [ 7.   5.   6. ]
 [ 7.   5.   6. ]
 [ 0.  11.   1. ]
 [ 0.  11.   1. ]
 [ 0.  11.   1. ]
 [13.  14.  16.5]]

这个方案完全基于TensorFlow原生操作,避免了手动循环,计算效率更高,也更符合TensorFlow的张量运算逻辑。

内容的提问来源于stack exchange,提问作者Thomas Ghorbanian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:15:38