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

如何将10×3矩阵随机删除元素转换为10×2有效矩阵?

如何将10×3矩阵随机删除元素转换为10×2矩阵?

原始10×3矩阵生成代码

random_values = np.round(np.random.normal(mean, std_deviation, (num_rows, num_columns)), 
2)
b_values = np.sort(random_values, axis=1)[:, ::-1]
weights = np.array([0.2, 0.5, 0.3])
y_values = np.round(np.dot(b_values, weights), 2)

当前实现的问题

现有代码仅将元素标记为NaN,并未真正移除元素并将每行压缩为2列,导致输出仍为10×3矩阵:

删除元素的函数

def drop_random_value(matrix):
    for i in range(matrix.shape[0]):
        # 获取行内随机索引
        random_index = np.random.randint(matrix.shape[1])
        
        # 将该索引位置设为NaN
        matrix[i, random_index] = np.nan

调用结果对比

drop_random_value(b_values)

print("Modified b_values:")
print(b_values)

实际输出:

[[0.93    nan 0.12 ]
 [  nan 0.4   0.4  ]
 [0.64    nan 0.23 ]
 [0.56  0.56    nan]
 [0.44  0.41    nan]
 [0.55  0.55    nan]
 [  nan 0.52  0.23 ]
 [0.69  0.69    nan]
 [0.62  0.405   nan]
 [  nan 0.71  0.53 ]]

预期输出:

[[0.93  0.12 ]
 [0.4   0.4  ]
 [0.64  0.23 ]
 [0.56  0.56 ]
 [0.44  0.41 ]
 [0.55  0.55 ]
 [0.52  0.23 ]
 [0.69  0.69 ]
 [0.62  0.405]
 [0.71  0.53 ]]

解决方案

需要直接移除每行的一个随机元素,生成新的10×2矩阵,以下是两种可行实现:

方式1:循环处理每行(直观易懂)

def drop_random_value(matrix):
    result = []
    for row in matrix:
        # 随机选择要保留的2个索引(排除1个随机位置)
        keep_indices = np.delete(np.arange(3), np.random.randint(3))
        result.append(row[keep_indices])
    return np.array(result)

# 调用函数得到10×2矩阵
b_values_10x2 = drop_random_value(b_values)
print(b_values_10x2)

方式2:向量化操作(高效适配大矩阵)

# 生成每行要删除的随机索引
drop_indices = np.random.randint(0, 3, size=b_values.shape[0])
# 创建掩码:标记每行需保留的元素位置
mask = np.ones(b_values.shape, dtype=bool)
mask[np.arange(b_values.shape[0]), drop_indices] = False
# 应用掩码并重塑为10×2矩阵
b_values_10x2 = b_values[mask].reshape(-1, 2)
print(b_values_10x2)

两种方式均会生成符合预期的10×2矩阵,且不会修改原始b_values矩阵。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:05:10