从一个热编码矩阵中按行快速随机采样不同数量的矩阵

2024-09-28 13:18:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个热编码的M x N矩阵A,具有以下属性:

  • 每行中的一列或多列可以等于1
  • 矩阵中的每一列都有一个值为1的单元格(所有其他单元格都为零)
  • M<<N

我还需要一个M x 1数组B,它包含整数(即我要选择的随机样本数)。B的每个单元格都具有以下属性:

  • B[i]<;=np.sum(M[i])

我正在寻找最有效的方法来随机抽取A的每一行中的一个子集。为每行返回的样本数由B的相应单元格中的整数值给出。输出将是一个M x N矩阵,我们称之为C,其中B == np.sum(C, axis=1)

实例
A = np.array([[0, 0, 1, 0, 0, 1, 0, 0], 
              [0, 1, 0, 0, 0, 0, 1, 1], 
              [1, 0, 0, 1, 1, 0, 0, 0]])
B = np.array([1, 3, 2])

运行此算法的有效输出为

array([[0, 0, 1, 0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0, 0, 1, 1],
       [1, 0, 0, 0, 1, 0, 0, 0]])

另一个可能的结果是

array([[0, 0, 0, 0, 0, 1, 0, 0], 
       [0, 1, 0, 0, 0, 0, 1, 1], 
       [0, 0, 0, 1, 1, 0, 0, 0]])

寻找尽可能快地生成X随机样本的能力


Tags: 实例方法lt编码属性np矩阵整数
1条回答
网友
1楼 · 发布于 2024-09-28 13:18:41

这个怎么样

import numpy as np
np.random.seed(42)

A = np.array([[0, 0, 1, 0, 0, 1, 0, 0],
              [0, 1, 0, 0, 0, 0, 1, 1],
              [1, 0, 0, 1, 1, 0, 0, 0]])
B = np.array([1, 3, 2])

C = np.c_[B, A]

def sample_ones(x):
    indices = np.where(x[1:] == 1)[0]  # indices of 1s
    subset_indices = np.random.choice(a=indices, size=indices.size - x[0], replace=False)  # indices of NON-sampled 1s
    x[subset_indices + 1] = 0  # replace non-sampled 1s with 0s
    return x[1:]

print(np.apply_along_axis(sample_ones, 1, C))

输出:

[[0 0 1 0 0 0 0 0]
 [0 1 0 0 0 0 1 1]
 [0 0 0 1 1 0 0 0]]

相关问题 更多 >

    热门问题