python - Python中离散变量的逆方法

标签 python numpy

我正在尝试对离散变量执行逆方法,但我没有得到任何东西(如果我打印样本,我只得到一个数字,而不是样本)。我如何才能使其正常工作?

import numpy as np
import numpy.random as rd
import matplotlib.pyplot as plt
def inversao_discreto(p,M):
    amostra=np.zeros(M)
    acum=np.zeros(len(p))
    acum[:]=p
    for i in range(1, len(acum)):
        acum[i]+=acum[i-1]
    r=rd.random_sample(M)
    for i in range(M):
        i=0
        k=0
        while(r[k]>acum[i]):
            i+=1
            amostra=i
    return amostra
model=np.array([0.1,0.2,0.1,0.2,0.4])
sample=inversao_discreto(model,10000)    

最佳答案

据我所知,您想要实现 Inverse transform sampling对于 discrete variables ,其工作原理如下:

Given a probability distribution `p`
Given a number of samples `M`
Calculate the cumulative probability distribution function `acum` from `p`
Generate `M` uniformly distributed samples and store into `r`
For each sample `r[i]`
    Get the index where the cumulative distribution `acum` is larger or equal to the sample `r[i]`
    Store this value into `amostra[i]`

如果我的理解是正确的,那么您的代码几乎就在那里。您的错误仅出现在最后一个 for 循环中。您的变量i正在跟踪存储在r中的样本的位置。然后,k 将跟踪您在累加器 acum 中与 r 进行比较的位置。这是伪代码:

For each sample `r[i]`
    Start with `k = 0`
    While `r[i] > acum[k]`
        Increment `k`
    Now that `r[i] <= acum[k]`, store `k` into `amostra[i]`

将其翻译为 Python:

for i in range(M):
    k = 0

    while (r[i] > acum[k]):
        k += 1

    amostra[i] = k

所以这里是修复的代码:

import numpy as np
import numpy.random as rd

def inversao_discreto(p, M):
    amostra = np.zeros(M)
    acum = np.zeros(len(p))
    acum[:] = p

    for i in range(1, len(acum)):
        acum[i] += acum[i - 1]

    r = rd.random_sample(M)

    for i in range(M):
        k = 0

        while (r[i] > acum[k]):
            k += 1

        amostra[i] = k

    return amostra

model = np.array([0.1, 0.2, 0.1, 0.2, 0.4])
sample = inversao_discreto(model, 10000)

由于您对 Python 比较陌生,因此我尝试更改尽可能少的代码以使其正常工作。我实现的大部分更改都是基于此Style Guide for Python Code ,我建议您看一下,因为从视觉上讲,它会改进您的代码。

关于python - Python中离散变量的逆方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58064231/

相关文章:

python如何构造这个类

python - 在没有 pygame 的情况下检测 USB 操纵杆上的任意按钮按下

python - 如何使用 Django Admin 中的 FileField 小部件将文件上传到 BinaryField?

python - 如何在 python 中使用变量作为正则表达式?

python - numpy 中的 "Got 1 columns instead of ..."错误

Python分组和拼接: splicing the result returned from itertools. groupby

python - 查找失败的索引 numpy.assert_almost_equal

python - 数据框到 file.txt python

python - 定期对列表/数组进行切片

python - 如何在 Python 中高效地生成具有随机斜率和截距的直线?