这是一种基于拒绝抽样的方法。根据示例中的数字,随机选择的索引可能为零,因此这是一种相对有效的方法。
from scipy import sparse
dims = (281903, 281903)
mat = sparse.lil_matrix(dims, dtype=np.int)
for _ in range(1000):
x, y = np.random.randint(0, dims[0], 2)
mat[x, y] = 1
def sample_zero_forever(mat):
nonzero_or_sampled = set(zip(*mat.nonzero()))
while True:
t = tuple(np.random.randint(0, mat.shape[0], 2))
if t not in nonzero_or_sampled:
yield t
nonzero_or_sampled.add(t)
def sample_zero_n(mat, n=100):
itr = sample_zero_forever(mat)
return [next(itr) for _ in range(n)]