从 2D numpy 获得联合概率的最佳方法

use*_*317 5 python arrays numpy probability

想知道是否有更好的方法来获得 2D numpy 数组的概率。也许使用一些 numpy 的内置函数。

为简单起见,假设我们有一个示例数组:

[['apple','pie'],
['apple','juice'],
['orange','pie'],
['strawberry','cream'],
['strawberry','candy']]
Run Code Online (Sandbox Code Playgroud)

想得到这样的概率:

['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
Run Code Online (Sandbox Code Playgroud)

其中“果汁”作为第二个词的概率为 0.2。由于苹果的概率为 2/5 * 1/2(果汁)。

另一方面,'pie' 作为第二个词的概率为 0.4。'apple' 和 'orange' 的概率组合。

我处理这个问题的方法是向数组添加 3 个新列,分别是第一列、第二列和最终概率的概率。将数组按第一列分组,然后按第二列分组并相应地更新概率。

下面是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

输出:

['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']
Run Code Online (Sandbox Code Playgroud)

想知道是否有更好的短/更快的方式使用 numpy 或其他方式来做到这一点。添加列不是必需的,这只是我的做法。其他方法将是可以接受的。

Flo*_*oor 2

根据您给出的概率分布的定义,您可以用来pandas执行相同的操作,即

import pandas as pd
a = np.array([['apple','pie'],['apple','juice'],['orange','pie'],['strawberry','cream'],['strawberry','candy']])

df = pd.DataFrame(a)
# Find the frequency of first word and divide by the total number of rows
df[2]=df[0].map(df[0].value_counts())/df.shape[0]
# Divide 1 by the total repetion 
df[3]=1/(df[0].map(df[0].value_counts()))
# Multiply the probabilities 
df[4]= df[2]*df[3]
Run Code Online (Sandbox Code Playgroud)

输出:

            0 1 2 3 4
0 苹果派 0.4 0.5 0.2
1 苹果汁 0.4 0.5 0.2
2 橙子派 0.2 1.0 0.2
3 草莓奶油 0.4 0.5 0.2
4颗草莓糖 0.4 0.5 0.2

如果您想要列表的形式,您可以使用df.values.tolist()

如果您不想要这些列,那么

df = pd.DataFrame(a)
df[2]=((df[0].map(df[0].value_counts())/df.shape[0]) * (1/(df[0].map(df[0].value_counts()))))
Run Code Online (Sandbox Code Playgroud)

输出:

           0 1 2
0 苹果派 0.2
1 苹果汁 0.2
2 橙子派 0.2
3 草莓奶油 0.2
4颗草莓糖0.2

对于组合概率print(df.groupby(1)[2].sum())

糖果0.2
奶油0.2
果汁 0.2
饼 0.4