【发布时间】:2017-12-17 15:58:54
【问题描述】:
想知道是否有更好的方法来获取 2D numpy 数组的概率。也许使用一些 numpy 的内置函数。
为简单起见,假设我们有一个示例数组:
[['apple','pie'],
['apple','juice'],
['orange','pie'],
['strawberry','cream'],
['strawberry','candy']]
想得到如下概率:
['apple' 'juice'] --> 0.4 * 0.5 = 0.2
['apple' 'pie'] --> 0.4 * 0.5 = 0.2
['orange' 'pie'] --> 0.2 * 1.0 = 0.2
['strawberry' 'candy'] --> 0.4 * 0.5 = 0.2
['strawberry' 'cream'] --> 0.4 * 0.5 = 0.2
其中“果汁”作为第二个单词的概率为 0.2。因为苹果的概率是 2/5 * 1/2(果汁)。
另一方面,“pie”作为第二个词的概率为 0.4。 “apple”和“orange”的概率组合。
我解决问题的方法是在数组中添加 3 个新列,分别是第 1 列、第 2 列的概率和最终概率。将数组按第一列分组,然后按第二列分组,并相应地更新概率。
下面是我的代码:
a = np.array([['apple','pie'],['apple','juice'],['orange','pie'],['strawberry','cream'],['strawberry','candy']])
ans = []
unique, counts = np.unique(a.T[0], return_counts=True) ## TRANSPOSE a, AND GET unique
myCounter = zip(unique,counts)
num_rows = sum(counts)
a = np.c_[a,np.zeros(num_rows),np.zeros(num_rows),np.zeros(num_rows)] ## ADD 3 COLUMNS to a
groups = []
## GATHER GROUPS BASE ON COLUMN 0
for _unique, _count in myCounter:
index = a[:,0] == _unique ## WHERE COLUMN 0 MATCH _unique
curr_a = a[index]
for j in range(len(curr_a)):
curr_a[j][2] = _count/num_rows
groups.append(curr_a)
## GATHER UNIQUENESS FROM COLUMN 1, PER GROUP
for g in groups:
unique, counts = np.unique(g.T[1], return_counts=True)
myCounter = zip(unique, counts)
num_rows = sum(counts)
for _unique, _count in myCounter:
index = g[:, 1] == _unique
curr_g = g[index]
for j in range(len(curr_g)):
curr_g[j][3] = _count / num_rows
curr_g[j][4] = float(curr_g[j][2]) * float(curr_g[j][3]) ## COMPUTE FINAL PROBABILITY
ans.append(curr_g[j])
for an in ans:
print(an)
输出:
['apple' 'juice' '0.4' '0.5' '0.2']
['apple' 'pie' '0.4' '0.5' '0.2']
['orange' 'pie' '0.2' '1.0' '0.2']
['strawberry' 'candy' '0.4' '0.5' '0.2']
['strawberry' 'cream' '0.4' '0.5' '0.2']
想知道使用 numpy 或其他方式是否有更好的更短/更快的方法。添加列不是必需的,这只是我的做法。其他方法也可以接受。
【问题讨论】:
-
从问题标题来看,问题涉及计算联合概率,但似乎有一个隐含的假设,即所有组合都具有相同的概率,因此都具有相同的联合概率(例如,它们都以在上述情况下为 0.2)。似乎这个问题更多是关于将这种联合概率分解为连续的条件概率。
标签: python arrays numpy probability