You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在TensorFlow 1.10中如何将(m,50)张量按值裁剪为(m,25)张量

TensorFlow 1.10 实现删除张量最后一维全0半段

实现思路

根据题目给出的场景,张量最后一维固定长度为50,且恰好前25位或后25位全为0,因此可以直接拆分最后一维为两段,判断全0段后保留有效段即可,全程使用TF1.10原生支持的API,无需额外依赖。

完整实现代码

import tensorflow as tf

def remove_zero_half(input_tensor):
    # 拆分最后一维为前后两个长度为25的片段
    first_half = input_tensor[:, :25]
    second_half = input_tensor[:, 25:]
    # 计算前半段所有元素的绝对值和,和为0即代表前半段全为0
    sum_first_half = tf.reduce_sum(tf.abs(first_half), axis=1)
    # 生成选择掩码:前半段全0则选后半段,否则选前半段
    select_second_mask = tf.equal(sum_first_half, 0)
    # 按掩码选择对应片段,输出形状为(m, 25)
    output_tensor = tf.where(select_second_mask, second_half, first_half)
    return output_tensor

测试验证代码

# 构造题目示例中的张量a和b
a = tf.constant([
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 15, 32, 1, 1, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [1, 1, 1, 1, 1, 11, 1, 1, 1, 11, 1, 1, 1, 1, 1, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [1, 1, 1, 1, 1, 421, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
], dtype=tf.int32)
b = tf.constant([
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 11, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 142, 1]
], dtype=tf.int32)

processed_a = remove_zero_half(a)
processed_b = remove_zero_half(b)

# TF1.x 会话运行验证
with tf.Session() as sess:
    res_a, res_b = sess.run([processed_a, processed_b])
    print("处理后a的形状:", res_a.shape)
    print("处理后b的形状:", res_b.shape)

运行后输出为:

处理后a的形状: (3, 25)
处理后b的形状: (3, 25)

注意事项

  • 该实现仅适配题目给定的场景:每个样本的最后一维恰好有一段长度为25的全0区域,且全0区域严格为前25位或后25位
  • 所有用到的API均为TensorFlow 1.10 原生支持,无需升级版本或引入其他依赖

内容的提问来源于stack exchange,提问作者Bowen Peng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:18:00