相关疑难解决方法(0)

加权选择简短

如果我在列表中有一组项目.我想根据另一个权重列表从该列表中进行选择.

例如我的收藏是['one', 'two', 'three']和权重[0.2, 0.3, 0.5],我希望这个方法在所有抽奖的大约一半中给我'三'.

最简单的方法是什么?

python numpy

46
推荐指数
4
解决办法
4万
查看次数

给定每个变量概率的列表变量

我一直在尝试编写一个在中间使用softmax激活功能的程序.

现在,我有一个这样的概率列表:

P[0.10,0.25,0.60,0.05]
Run Code Online (Sandbox Code Playgroud)

P中所有变量的总和始终为1.

考虑到附加概率,我想要一种方法来选择列表的索引.或者,换句话说,返回的函数

0 - 10% of the time
1 - 25% of the time
2 - 60% of the time
3 - 5% of the time
Run Code Online (Sandbox Code Playgroud)

我完全不知道从哪里开始.任何帮助,将不胜感激.:)

python probability

29
推荐指数
4
解决办法
3万
查看次数

随机矩阵的所有行的快速随机加权选择

numpy.random.choice 允许从矢量加权选择,即

arr = numpy.array([1, 2, 3])
weights = numpy.array([0.2, 0.5, 0.3])
choice = numpy.random.choice(arr, p=weights) 
Run Code Online (Sandbox Code Playgroud)

选择1概率为0.2,2选择概率为0.5,3选择概率为0.3.

如果我们想以矢量化的方式快速完成2D阵列(矩阵),每个行都是概率矢量,该怎么办?也就是说,我们想要一个随机矩阵的选择向量?这是超级慢的方式:

import numpy as np

m = 10
n = 100 # Or some very large number

items = np.arange(m)
prob_weights = np.random.rand(m, n)
prob_matrix = prob_weights / prob_weights.sum(axis=0, keepdims=True)

choices = np.zeros((n,))
# This is slow, because of the loop in Python
for i in range(n):
    choices[i] = np.random.choice(items, p=prob_matrix[:,i])
Run Code Online (Sandbox Code Playgroud)

print(choices):

array([ 4.,  7.,  8.,  1.,  0.,  4.,  3.,  7.,  1., …
Run Code Online (Sandbox Code Playgroud)

python numpy matrix vectorization random-sample

12
推荐指数
1
解决办法
1528
查看次数

python中的加权随机样本

我正在寻找一个合理的函数定义weighted_sample,它不会为给定权重列表返回一个随机索引(这类似于

def weighted_choice(weights, random=random):
    """ Given a list of weights [w_0, w_1, ..., w_n-1],
        return an index i in range(n) with probability proportional to w_i. """
    rnd = random.random() * sum(weights)
    for i, w in enumerate(weights):
        if w<0:
            raise ValueError("Negative weight encountered.")
        rnd -= w
        if rnd < 0:
            return i
    raise ValueError("Sum of weights is not positive")
Run Code Online (Sandbox Code Playgroud)

给出一个具有恒定权重的分类分布)但随机抽样k的那些,没有替换,就像random.sample行为相比random.choice.

就像weighted_choice可以写成一样

lambda weights: random.choice([val for val, cnt in enumerate(weights) …
Run Code Online (Sandbox Code Playgroud)

python random algorithm

7
推荐指数
1
解决办法
9630
查看次数

从 Numpy 数组的索引中采样的有效方法?

我想从 2D Numpy 数组的索引中采样,考虑到每个索引都由该数组内的数字加权。numpy.random.choice然而,我知道它的方式不返回索引,而是返回数字本身。有什么有效的方法吗?

这是我的代码:

import numpy as np
A=np.arange(1,10).reshape(3,3)
A_flat=A.flatten()
d=np.random.choice(A_flat,size=10,p=A_flat/float(np.sum(A_flat)))
print d
Run Code Online (Sandbox Code Playgroud)

python random numpy sampling

5
推荐指数
1
解决办法
1336
查看次数