【问题标题】:Find frequency of relationships of tags in lists (pairwise correlation?)查找列表中标签关系的频率(成对相关?)
【发布时间】:2018-09-26 15:00:42
【问题描述】:

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

l1 = ["cat", "toe", "man"]
l2 = ["cat", "toe", "ice"]
l3 = ["cat", "hat", "bed"]

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

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

【问题讨论】:

    标签: python list combinations counter data-analysis


    【解决方案1】:

    您可以将collections.defaultdictfrozensetitertools.combinations 一起使用来形成成对计数的字典。

    变化是可能的。例如,您可以使用 collections.Counter 和 sorted tuple,但基本相同。

    from collections import defaultdict
    from itertools import combinations
    
    dd = 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})
    

    【讨论】:

    • 谢谢!我可以通过组合(L,3)将其升级为三倍!酷。
    • 没有冻结集可以做吗?我们从l = [list(combinations(i, 2)) for i in l4] 到哪里去,l4 是 3 个列表的列表
    • 您需要可散列的键,列表不起作用。正如我所提到的,您可以使用 tuple 而不是 frozenset [如果它已排序]。
    • 还有一件事gggg,是否可以直接计数而不是增量计数
    • @vash_the_stampede,所以不是论坛。如果你有的话,我建议你ask a new question
    【解决方案2】:

    另一种选择是创建一个 DataFrame,其中每个唯一单词的指示变量作为列:

    from itertools import chain
    all_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
    

    【讨论】:

    • 谢谢,看起来也不错!它也适用于三元组等吗? (我知道,我没有要求。)
    • @j____r___ 不,这仅适用于成对。您可能想研究一种称为频繁项集或关联规则学习的东西
    猜你喜欢
    • 2020-12-28
    • 2022-01-28
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多