当我使用这个随机发生器时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) 假设 x_1, x_2, ..., x_n 是 n 个对象,并且想要选择其中一个,以便选择 x_i 的概率与某个数字 u_i 成正比。Numpy 为此提供了一个函数:
x, u = np.array([x_1, x_2, ..., x_n]), np.array([u_1, ..., u_n])
np.random.choice(x, p = u/np.sum(u))
Run Code Online (Sandbox Code Playgroud)
然而,我观察到这段代码有时会抛出一个 ValueError ,指出“概率之和不等于 1”。这可能是由于有限精度算术的舍入误差造成的。应该怎么做才能让这个功能正常工作呢?