查找列表中标签关系的频率(成对相关?)

我有一些图像标签列表。我想找出哪些标签似乎相关:


l1 = ["cat", "toe", "man"]

l2 = ["cat", "toe", "ice"]

l3 = ["cat", "hat", "bed"]

在这个(简单的)例子中,“cat”和“toe”显然是相关的,因为它们出现了两次(l1,l2)。


如何计算?结果如下: cat & toe: 2. 我有一个线索,我要求“成对相关”,但这种分析的资源对我来说太复杂了。


哈士奇WWW
浏览 188回答 2
2回答

月关宝盒

您可以使用collections.defaultdictwithfrozenset和itertools.combinations来形成成对计数的字典。变化是可能的。例如,您可以使用collections.Counterwith sortedtuple来代替,但基本上是相同的想法。from collections import defaultdictfrom itertools import combinationsdd = defaultdict(int)L1 = ["cat", "toe", "man"]L2 = ["cat", "toe", "ice"]L3 = ["cat", "hat", "bed"]for L in [L1, L2, L3]:    for pair in map(frozenset, (combinations(L, 2))):        dd[pair] += 1结果:defaultdict(int,            {frozenset({'cat', 'toe'}): 2,             frozenset({'cat', 'man'}): 1,             frozenset({'man', 'toe'}): 1,             frozenset({'cat', 'ice'}): 1,             frozenset({'ice', 'toe'}): 1,             frozenset({'cat', 'hat'}): 1,             frozenset({'bed', 'cat'}): 1,             frozenset({'bed', 'hat'}): 1})

拉莫斯之舞

另一种选择是创建一个 DataFrame,其中每个唯一单词的指标变量作为列:from itertools import chainall_tags = set(chain.from_iterable([l1, l2, l3]))d = pd.DataFrame([{k: 1 if k in l else 0 for k in all_tags} for l in [l1, l2, l3]])print(d)#   bed  cat  hat  ice  man  toe#0    0    1    0    0    1    1#1    0    1    0    1    0    1#2    1    1    1    0    0    0现在您可以转置这个矩阵并将其与自身点在一起以获得成对计数:pairwise_counts = d.T.dot(d)print(pairwise_counts)#     bed  cat  hat  ice  man  toe#bed    1    1    1    0    0    0#cat    1    3    1    1    1    2#hat    1    1    1    0    0    0#ice    0    1    0    1    0    1#man    0    1    0    0    1    1#toe    0    2    0    1    1    2该矩阵的对角线是每个单词在您的数据中出现的次数。如果您想要任何两个字符串的成对计数,例如"cat"和“ toe”,您可以执行以下操作:print(pairwise_counts.loc["cat", "toe"])#2由于这个矩阵是对称的,你会得到相同的答案:print(pairwise_counts.loc["toe", "cat"])#2
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python