【问题标题】:Calculating conditional probabilities from joint pmfs in numpy, too slow. Ideas? (python-numpy)从 numpy 中的联合 pmfs 计算条件概率,太慢了。想法? (python-numpy)
【发布时间】:2011-01-13 02:01:42
【问题描述】:

我有一个联合概率质量函数数组,其形状例如 (1,2,3,4,5,6),我想计算概率表,条件是某些维度的值(导出cpts),用于决策目的。

我现在想出的代码如下(输入是字典“vdict”,格式为 {'variable_1': value_1, 'variable_2': value_2 ... } )

for i in vdict:
   dim = self.invardict.index(i) # The index of the dimension that our Variable resides in
   val = self.valdict[i][vdict[i]] # The value we want it to be
   d = d.swapaxes(0, dim)
   **d = array([d[val]])**
   d = d.swapaxes(0, dim)

...

所以,我现在做的是:

  1. 我将变量转换为cpt中的相应维度。
  2. 我将第零轴与之前找到的轴交换。
  3. 我将整个 0 轴替换为所需的值。

我把维度放回到原来的轴上。

现在,问题是,为了执行第 2 步,我必须 (a.) 计算一个子数组 和 (b.) 将其放入列表中并再次将其转换为数组,这样我将拥有我的新数组。

问题是,粗体表示我创建新对象,而不是仅使用对旧对象的引用,如果 d 非常大(这发生在我身上)并且使用 d 的方法被调用多次(这又发生在我身上)整个结果非常缓慢。

那么,有没有人想出一个想法,可以对这小段代码进行隐蔽并且运行得更快?也许可以让我计算适当的条件。

注意:我必须保持原始轴顺序(或者至少要确定在移除轴时如何将变量更新为维度字典)。我不想使用自定义 dtypes。

【问题讨论】:

    标签: python numpy probability arrays recarray


    【解决方案1】:

    好的,在玩了一点 numpy 的就地数组操作后,我自己找到了答案。

    将循环中的最后 3 行更改为:

        d = conditionalize(d, dim, val)
    

    条件化定义为:

        def conditionalize(arr, dim, val):
            arr = arr.swapaxes(dim, 0)
            shape = arr.shape[1:]       # shape of the sub-array when we omit the desired dimension.
            count = array(shape).prod() # count of elements omitted the desired dimension.
            arr = arr.reshape(array(arr.shape).prod()) # flatten the array in-place.
            arr = arr[val*count:(val+1)*count] # take the needed elements
            arr = arr.reshape((1,)+shape) # the desired sub-array shape.
            arr = arr. swapaxes(0, dim)   # fix dimensions
    
            return arr
    

    这使我的程序的执行时间从 15 分钟减少到 6 秒。收获巨大。

    我希望这对遇到同样问题的人有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2017-12-17
      • 1970-01-01
      • 2016-04-12
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      相关资源
      最近更新 更多