相关疑难解决方法(0)

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

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
查看次数

使用numpy.random.multinomial时如何避免值错误?

当我使用这个随机发生器时numpy.random.multinomial,我不断得到:

ValueError: sum(pvals[:-1]) > 1.0
Run Code Online (Sandbox Code Playgroud)

我总是传递这个softmax函数的输出:

def softmax(w, t = 1.0):
    e = numpy.exp(numpy.array(w) / t)
    dist = e / np.sum(e)
    return dist
Run Code Online (Sandbox Code Playgroud)

除了我现在收到这个错误,我还为参数(pvals)添加了这个:

while numpy.sum(pvals) > 1:
    pvals /= (1+1e-5)
Run Code Online (Sandbox Code Playgroud)

但这并没有解决它.确保我避免此错误的正确方法是什么?

编辑:这是包含此代码的函数

def get_MDN_prediction(vec):
    coeffs = vec[::3]
    means = vec[1::3]
    stds = np.log(1+np.exp(vec[2::3]))
    stds = np.maximum(stds, min_std)
    coe = softmax(coeffs)
    while np.sum(coe) > 1-1e-9:
        coe /= (1+1e-5)
    coeff = unhot(np.random.multinomial(1, coe))
    return np.random.normal(means[coeff], stds[coeff])
Run Code Online (Sandbox Code Playgroud)

python random numpy numerical-stability

5
推荐指数
2
解决办法
3288
查看次数