【问题标题】:Alternatives for numpy.random generation with choice values and specific frequency of values具有选择值和特定值频率的 numpy.random 生成的替代方案
【发布时间】:2021-01-07 21:30:20
【问题描述】:

我正在生成一个 (1109, 8) 数组,该数组具有从一组固定数字 [18, 24, 36, 0] 生成的随机值,我需要确保每行始终包含 5 个零,但它即使在调整了概率的权重之后也没有发生。

我的解决方法代码如下,但想知道是否有其他功能更简单的方法?或者也许通过调整生成器的一些参数? https://numpy.org/doc/stable/reference/random/generator.html

#Random output using new method
from numpy.random import default_rng
rng = default_rng(1)

#generate an array with random values of test duration,
test_duration = rng.choice([18, 24, 36, 0], size = arr.shape, p=[0.075, 0.1, 0.2, 0.625])
# ensure number of tests equals n_tests
n_tests = 3
non_tested = arr.shape[1] - n_tests


for row in range(len(test_duration)):
    while np.count_nonzero(test_duration[row, :]) != n_tests:
        new_test = rng.choice([18, 24, 36, 0], size = arr.shape[1], p=[0.075, 0.1, 0.2, 0.625])
        test_duration[row, :] = np.array(new_test)
    else:
        pass
print('There are no days exceeding n_tests')
#print(test_durations)
print(test_duration[:10, :])

【问题讨论】:

    标签: python numpy random


    【解决方案1】:

    如果每行需要 5 个零,您可以从 [18, 24, 36] 中随机选择 3 个值,用零填充其余的值,然后进行每行随机洗牌。 numpy shuffle 发生在原地,所以你不需要重新分配。

    import numpy as np
    
    c = [18,24,26]
    
    p = np.array([0.075, 0.1, 0.2])
    p = p / p.sum()  # normalize the probs
    
    a = np.random.choice(c, size=(1109, 3), replace=True, p=(p/p.sum()))
    a = np.hstack([a, np.zeros((1109, 5), dtype=np.int32)])
    
    list(map(np.random.shuffle, a))
    
    a
    # returns:
    array([[ 0,  0,  0,  0, 36,  0, 36, 36],
           [ 0, 36,  0, 24, 24,  0,  0,  0],
           [ 0,  0,  0,  0, 36, 36, 36,  0]])
           ...
           [ 0,  0,  0, 24, 24, 36,  0,  0],
           [ 0, 24,  0,  0,  0, 36,  0, 18],
           [ 0,  0,  0, 36, 36, 24,  0,  0]])
    

    【讨论】:

    • 好主意。您的代码只是缺少 c=[18,24,26] ;并且可能会提到list(map(...)for row in a: np.random.shuffle(row) 相同。
    【解决方案2】:

    您可以简单地为数组中零的 5 个位置创建一个随机选择,这样您就可以强制确定确实存在 5 个零,并且在您对 [18, 24, 36] 及其归一化概率。

    但是这样做你没有尊重你一开始指定的概率密度,我不知道你在哪个应用程序中使用它,但这是需要考虑的一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2018-10-04
      • 2018-02-17
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多