【问题标题】:Create two set of mutually exclusive random samples in python在python中创建两组互斥的随机样本
【发布时间】:2013-12-19 09:29:55
【问题描述】:

我有两个不同的 numpy.array A[m,n] 和 B[m,p]。我想分别从 A 和 B 创建两个随机样本,即 A1[m1,n]、A2[m2,n] 和 B1[m1,p]、B2[m2,p]。

或者具体来说,如果我随机抽取两个与行相对应的索引样本,即

rnd1 = [random.randint(1,m) for r in xrange(m1)]
rnd2 = [random.randint(1,m) for r in xrange(m2)]

并尝试将子数组创建为

A1=[A[i,:] for i in rnd1]
A2=[A[i,:] for i in rnd2]   

B1=[B[i,:] for i in rnd1]
B2=[B[i,:] for i in rnd2]

A1 和 B1 中的行顺序相同,A2 和 B2 中的行顺序也相同。但 rand1 和 rnd2 并不相互排斥。

如何创建互斥集合?

【问题讨论】:

  • 你忘了问问题。您在执行此操作时遇到任何问题吗?具体在哪里?你试过什么?这不是一个为我编写代码的网站。
  • "使得 A1 和 B1 中的行顺序相同,同样 A2 和 B2 也相同。" - 这意味着什么?我想出的解释——A1 的每一行等于 B1 的相应行,A2 的每一行等于 B2 的相应行——简化为 A1 和 A2 与 B1 和 B2 具有相同的内容。这通常是不可能的。
  • 我已经编辑了问题并添加了更多描述和一些代码 sn-ps 以帮助理解问题

标签: python random numpy


【解决方案1】:

一种方法是将[0, m - 1] 范围内的每个索引分配给idx1 系列或idx2 系列以相等的概率,然后从idx1idx2 中采样:

m, m1, m2 = 10, 5, 7

# tag each index with equal probabilities to True & False
# note: p = m1 / ( m1 + m2 ) can make more sense depending
# on desired distribution
tag = np.random.binomial(n=1, p=.5, size=m) == 1

# assign True indices to idx1 and False indices to index 2
idx = np.array( range( m ) )
idx1, idx2 = idx[ tag ], idx[ np.logical_not( tag ) ]

# sample from idx1 and idx2
i1, i2 = np.random.choice( idx1, size=m1 ), np.random.choice( idx2, size=m2 )

唯一需要注意的是,您需要重做标记,直到 sum( tag ) != 0sum( tag ) != ml;即idx1idx2 非空。

您也可以在上面设置p=m1/(m1+m2),具体取决于您要查找的发行版。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-13
    • 2013-03-09
    • 1970-01-01
    • 2012-01-31
    • 2021-12-20
    • 2013-10-29
    • 2015-02-13
    相关资源
    最近更新 更多