2

我有一个 numpy 数组(实际上是从 GIS 栅格地图导入的),其中包含一个物种出现的概率值,如下例所示:

a = random.randint(1.0,20.0,1200).reshape(40,30)
b = (a*1.0)/sum(a)

现在我想再次获得该数组的离散版本。例如,如果我有 100 个位于该阵列区域(1200 个单元)的个体,它们是如何分布的?当然,它们应该根据它们的概率分布,这意味着较低的值表示较低的发生概率。但是,由于一切都是统计数据,因此个人仍有可能位于低概率单元格中。应该有可能多个人可以占据一个单元...

这就像将连续分布曲线再次转换为直方图。就像许多不同的直方图可能会导致某个分布曲线一样,它也应该反过来。因此,应用我正在寻找的算法每次都会产生不同的离散值。

...python中有没有可以做到这一点的算法?由于我对离散化不太熟悉,也许有人可以提供帮助。

4

3 回答 3

3

random.choice与 一起使用bincount

np.bincount(np.random.choice(b.size, 100, p=b.flat),
            minlength=b.size).reshape(b.shape)

如果您没有 NumPy 1.7,您可以替换random.choice为:

np.searchsorted(np.cumsum(b), np.random.random(100))

给予:

np.bincount(np.searchsorted(np.cumsum(b), np.random.random(100)),
            minlength=b.size).reshape(b.shape)
于 2012-07-25T13:18:31.443 回答
2

到目前为止,我认为 ecatmur 的回答似乎非常合理和简单。

我只想添加一个更“应用”的示例。考虑一个有 6 个面(6 个数字)的骰子。每个数字/结果的概率为 1/6。以数组的形式显示骰子可能如下所示:

b = np.array([[1,1,1],[1,1,1]])/6.0

因此,掷骰子 100 次(n=100)会产生以下模拟:

np.bincount(np.searchsorted(np.cumsum(b), np.random.random(n)),minlength=b.size).reshape(b.shape)

我认为这可能是此类应用程序的合适方法。因此,感谢 ecatmur 的帮助!

/约翰内斯

于 2012-08-06T11:39:28.643 回答
1

这类似于我本月早些时候提出的问题。

import random
def RandFloats(Size):
    Scalar = 1.0
    VectorSize = Size
    RandomVector = [random.random() for i in range(VectorSize)]
    RandomVectorSum = sum(RandomVector)
    RandomVector = [Scalar*i/RandomVectorSum for i in RandomVector]
    return RandomVector

from numpy.random import multinomial
import math
def RandIntVec(ListSize, ListSumValue, Distribution='Normal'):
    """
    Inputs:
    ListSize = the size of the list to return
    ListSumValue = The sum of list values
    Distribution = can be 'uniform' for uniform distribution, 'normal' for a normal distribution ~ N(0,1) with +/- 5 sigma  (default), or a list of size 'ListSize' or 'ListSize - 1' for an empirical (arbitrary) distribution. Probabilities of each of the p different outcomes. These should sum to 1 (however, the last element is always assumed to account for the remaining probability, as long as sum(pvals[:-1]) <= 1).  
    Output:
    A list of random integers of length 'ListSize' whose sum is 'ListSumValue'.
    """
    if type(Distribution) == list:
        DistributionSize = len(Distribution)
        if ListSize == DistributionSize or (ListSize-1) == DistributionSize:
            Values = multinomial(ListSumValue,Distribution,size=1)
            OutputValue = Values[0]
    elif Distribution.lower() == 'uniform': #I do not recommend this!!!! I see that it is not as random (at least on my computer) as I had hoped
        UniformDistro = [1/ListSize for i in range(ListSize)]
        Values = multinomial(ListSumValue,UniformDistro,size=1)
        OutputValue = Values[0]
    elif Distribution.lower() == 'normal':
        """
            Normal Distribution Construction....It's very flexible and hideous
            Assume a +-3 sigma range.  Warning, this may or may not be a suitable range for your implementation!
            If one wishes to explore a different range, then changes the LowSigma and HighSigma values
            """
            LowSigma    = -3#-3 sigma
            HighSigma   = 3#+3 sigma
            StepSize    = 1/(float(ListSize) - 1)
            ZValues     = [(LowSigma * (1-i*StepSize) +(i*StepSize)*HighSigma) for i in range(int(ListSize))]
            #Construction parameters for N(Mean,Variance) - Default is N(0,1)
            Mean        = 0
            Var         = 1
            #NormalDistro= [self.NormalDistributionFunction(Mean, Var, x) for x in ZValues]
            NormalDistro= list()
            for i in range(len(ZValues)):
                if i==0:
                    ERFCVAL = 0.5 * math.erfc(-ZValues[i]/math.sqrt(2))
                    NormalDistro.append(ERFCVAL)
                elif i ==  len(ZValues) - 1:
                    ERFCVAL = NormalDistro[0]
                    NormalDistro.append(ERFCVAL)
                else:
                    ERFCVAL1 = 0.5 * math.erfc(-ZValues[i]/math.sqrt(2))
                    ERFCVAL2 = 0.5 * math.erfc(-ZValues[i-1]/math.sqrt(2))
                    ERFCVAL = ERFCVAL1 - ERFCVAL2
                    NormalDistro.append(ERFCVAL)  
            #print "Normal Distribution sum = %f"%sum(NormalDistro)
            Values = multinomial(ListSumValue,NormalDistro,size=1)
            OutputValue = Values[0]
        else:
            raise ValueError ('Cannot create desired vector')
        return OutputValue
    else:
        raise ValueError ('Cannot create desired vector')
    return OutputValue

ProbabilityDistibution = RandFloats(1200)#This is your probability distribution for your 1200 cell array
SizeDistribution = RandIntVec(1200,100,Distribution=ProbabilityDistribution)#for a 1200 cell array, whose sum is 100 with given probability distribution 

重要的两行主要是上面代码中的最后两行

于 2012-07-25T13:29:54.517 回答