You need to enable JavaScript to run this app. NumPy或优先TensorFlow实现:一维数组转行内按规则置零的N×N矩阵
优惠活动
大模型
产品
解决方案
定价
更多

NumPy或优先TensorFlow实现:一维数组转行内按规则置零的N×N矩阵

数组转N×N矩阵的高效实现方案

核心转换逻辑

根据给出的样例规则,核心逻辑可拆解为无循环的向量化实现:

  • 对行号为i的行,先查找原数组中位置不超过i的所有元素里、最后一个0的索引值z_i
  • 该行的所有列j,仅当j > z_i时保留原数组的对应元素值,j <= z_i的位置全部置0
  • 整个实现无需逐行遍历,全程使用广播向量化操作,TensorFlow版本可直接在GPU上加速

优先 TensorFlow 版本实现

完全向量化、支持硬件加速,适配任意长度的一维数组输入:

import tensorflow as tf

def to_square_matrix_tf(input_array):
    # 强制转换为浮点类型兼容多场景计算
    a = tf.cast(input_array, tf.float32)
    N = tf.shape(a)[0]
    # 1. 提取原数组中所有0的位置(按自然升序排列)
    zero_pos = tf.reshape(tf.where(a == 0), [-1])
    # 2. 为每个行号计算对应的最后一个0的位置z_i
    row_indices = tf.range(N)
    # 二分查找计算插入位置,减1即为符合<=i的最后一个0的索引
    insert_point = tf.searchsorted(zero_pos, row_indices, side="right")
    # 边界处理:若i位置之前没有0,设置z_i=-1,即整行保留原数组值
    if tf.shape(zero_pos)[0] == 0:
        z_i = -tf.ones_like(row_indices)
    else:
        z_i = tf.gather(zero_pos, insert_point - 1)
        z_i = tf.where(insert_point == 0, -1, z_i)
    # 3. 构造广播掩码生成最终矩阵
    col_indices = tf.range(N)
    mask = tf.cast(col_indices[None, :] > z_i[:, None], a.dtype)
    output_matrix = a[None, :] * mask
    return output_matrix

效果验证

输入A = np.array([0,1,1,0,1]),输出完全匹配示例矩阵B
输入D = np.array([0,1,1,1,0,0,1,1,0,0]),输出完全匹配示例矩阵E
兼容边界场景:数组全1、数组全0、数组开头无0等输入均能正确计算


NumPy 兼容版本实现

逻辑与TensorFlow版本完全一致,适合CPU端离线计算场景:

import numpy as np

def to_square_matrix_np(input_array):
    a = input_array
    N = a.shape[0]
    # 1. 提取所有0的位置
    zero_pos = np.where(a == 0)[0]
    # 2. 二分查找计算每个行对应的最后一个0的位置
    row_indices = np.arange(N)
    insert_point = np.searchsorted(zero_pos, row_indices, side="right")
    # 边界处理
    z_i = np.where(insert_point == 0, -1, zero_pos[insert_point - 1])
    # 3. 构造掩码生成矩阵
    col_indices = np.arange(N)
    mask = (col_indices[None, :] > z_i[:, None]).astype(a.dtype)
    output_matrix = a[None, :] * mask
    return output_matrix

效率说明

  • 整体时间复杂度为O(N),远低于逐行遍历的O(N²)循环开销
  • 支持N为万级以上规模的矩阵生成,TensorFlow版本可充分利用GPU并行能力
  • 无动态循环操作,可直接嵌入计算图完成端到端的模型部署

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.15 16:45:08