我有一个联合概率质量函数数组,其形状例如 (1,2,3,4,5,6),我想计算概率表,以某些维度的值为条件(导出cpts),用于决策目的。
我现在想出的代码如下(输入是形式为 {'variable_1': value_1, 'variable_2': value_2 ... } 的字典“vdict”)
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)
...
所以,我目前所做的是:
- 我将变量转换为 cpt 中相应的维度。
- 我将第零轴与之前找到的轴交换。
- 我将整个 0 轴替换为所需的值。
我将尺寸放回原来的轴。
现在的问题是,为了执行步骤 2,我必须 (a.) 计算一个子数组 (b.) 将其放入列表中并再次将其转换为数组,这样我就会得到新的数组。
事实是,粗体的内容意味着我创建新对象,而不是仅使用对旧对象的引用,如果 d 非常大(这发生在我身上)并且使用 d 的方法被调用很多次(这又发生在我身上)整个结果非常慢。
那么,有没有人想出一个想法来改进这一小段代码并且运行得更快?也许可以让我计算适当的条件。
注意:我必须保持原始的轴顺序(或者至少确定在删除轴时如何将变量更新为尺寸字典)。我不想诉诸自定义数据类型。
最佳答案
好吧,在玩了一下 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 秒。收获巨大。
希望这对遇到同样问题的人有所帮助。
关于python - 在 numpy 中计算联合 pmf 的条件概率,太慢了。有想法吗? (python-numpy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2199940/