You need to enable JavaScript to run this app. 如何将随机2D数据重分布为最大值居中且呈类高斯衰减的矩阵
优惠活动
大模型
产品
解决方案
定价
更多

如何将随机2D数据重分布为最大值居中且呈类高斯衰减的矩阵

实现思路
  • 第一步:将原2D数组的所有元素拉平为一维数组,按从大到小降序排序
  • 第二步:计算目标矩阵每个坐标点到中心的距离,你给出的示例符合曼哈顿距离的分层规则,如需更接近真实高斯的平滑衰减效果可替换为欧氏距离
  • 第三步:将所有坐标点按距离从小到大排序,相同距离的点排序顺序不影响整体衰减效果
  • 第四步:把排序好的一维元素按顺序填充到对应排序后的坐标位置,得到最终矩阵
完整实现代码
import numpy as np

def rearrange_to_gaussian_like(mat):
    # 获取矩阵尺寸
    rows, cols = mat.shape
    # 1. 拉平原数组并按从大到小降序排序
    sorted_vals = np.sort(mat.flatten())[::-1]
    # 2. 计算每个坐标到矩阵中心的距离
    center_row, center_col = (rows - 1) / 2, (cols - 1) / 2
    y_coords, x_coords = np.ogrid[:rows, :cols]
    # 曼哈顿距离(和你给出的示例分层规则完全匹配)
    dist = np.abs(x_coords - center_col) + np.abs(y_coords - center_row)
    # 如需更平滑的类高斯效果,可替换为欧氏距离:
    # dist = np.sqrt((x_coords - center_col)**2 + (y_coords - center_row)**2)
    # 3. 按距离从小到大获取坐标的一维索引
    sorted_indices = np.argsort(dist.flatten())
    # 4. 按顺序填充元素生成结果矩阵
    result = np.zeros_like(mat)
    result.flat[sorted_indices] = sorted_vals
    return result

# 测试用例:匹配你提到的100x120随机矩阵场景
x = 100
y = 120
random_mat = np.random.random((x, y))
output_mat = rearrange_to_gaussian_like(random_mat)

如果需要同一距离层内的元素分布更随机,可对相同距离的坐标做随机打乱后再填充,不会影响整体从中心向外衰减的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 10:33:02