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

如何对6×1000数组的指定行(6i行)执行归一化操作?

问题:按指定行索引对数组执行归一化处理

需求说明

  • 数组尺寸为6×1000(示例使用12×3数组演示)
  • 仅对索引为0、6、12、18……(即6i,i∈range(1000))的行执行归一化
  • 其余行数值保持不变
  • 归一化公式:(行元素 - 行最小值) / (行最大值 - 行最小值 + 0.00001)

现有代码问题

当前的normalize函数会对所有行执行归一化,不符合仅处理指定行的需求,导致调用示例输入时无法得到预期结果。

现有函数代码

def normalize(array):
    minimum = np.expand_dims(np.min(array, axis=1), axis=1)
    maximum = np.expand_dims(np.max(array, axis=1), axis=1)
    return (array - minimum) / (maximum - minimum + 0.00001)

示例输入

import numpy as np
A = np.array([[15, 14,  3],
   [11,  9,  9],
   [16,  6,  1],
   [14,  6,  9],
   [ 1, 12,  2],
   [ 5,  1,  2],
   [13, 11,  2],
   [11,  4,  1],
   [11,  7, 10],
   [10, 11, 16],
   [ 2, 13,  4],
   [12, 14, 14]])

normalize(A)

预期输出

array([[0.99999917, 0.9166659 , 0.        ],
   [11,  9,  9],
   [16,  6,  1],
   [14,  6,  9],
   [ 1, 12,  2],
   [ 5,  1,  2],
   [0.99999909, 0.81818107, 0.        ],
   [11,  4,  1],
   [11,  7, 10],
   [10, 11, 16],
   [ 2, 13,  4],
   [12, 14, 14]])

修改后的解决方案

修改函数,仅对指定索引的行执行归一化,其余行保持原样:

import numpy as np

def normalize(array):
    # 创建输入数组的副本,避免修改原数组
    result = array.copy().astype(np.float64)
    # 生成需要归一化的行索引:0,6,12,...
    target_indices = np.arange(0, array.shape[0], 6)
    # 提取目标行
    target_rows = array[target_indices]
    # 计算每行的最小值和最大值
    min_rows = np.expand_dims(np.min(target_rows, axis=1), axis=1)
    max_rows = np.expand_dims(np.max(target_rows, axis=1), axis=1)
    # 对目标行执行归一化
    normalized_rows = (target_rows - min_rows) / (max_rows - min_rows + 1e-5)
    # 将归一化后的行放回结果数组
    result[target_indices] = normalized_rows
    return result

调用验证

output = normalize(A)
print(output)

运行后即可得到预期输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:35:29