gpt4 book ai didi

python - 列表中元素的识别 - 机器学习

转载 作者:行者123 更新时间:2023-11-30 09:38:14 26 4
gpt4 key购买 nike

所以我有多个列表:

['disney','england','france']
['disney','japan']
['england', 'london']
['disney', 'france']

现在我需要确定这些列表中的内容往往会同时出现。

例如,如果我们查看这个小示例,我们会发现“迪士尼”、“法国”经常一起出现在列表中。随着文档/列表数量的增加,我们可能会发现“england”始终与“london”一起出现在列表中

我研究过诸如元组之类的东西,但是这种情况更多地发生在语言和大型文本文档中。这里的问题是如何识别这些一起出现的配对/三元组/n 个属性。

编辑:这不仅仅是看对。如果你让三个字符串重复出现在一起会怎样!

最佳答案

也许这样的事情可以作为一个起点:

import numpy as np

# I'll use numbers instead of words,
# but same exact concept
points_list = [[0,1,2],
[0,3],
[1,4],
[0,2]]

scores = np.zeros((5,5))

for points in points_list:
temp = np.array(points)[:, np.newaxis]
scores[temp, points] += 1

结果:

>>> scores
array([[ 3., 1., 2., 1., 0.],
[ 1., 2., 1., 0., 1.],
[ 2., 1., 2., 0., 0.],
[ 1., 0., 0., 1., 0.],
[ 0., 1., 0., 0., 1.]])

对角线元素告诉您一个变量总共出现了多少次,对角线元素告诉您两个变量一起出现了多少次。这个矩阵显然是对称的,因此可能可以对其进行优化。

此外,如果您的子列表很长(有很多变量),但没有太多,您可以考虑使用稀疏矩阵。

编辑:

这里有一个关于如何获得三胞胎等的想法。

import numpy as np

# I'll use numbers instead of words,
# but same exact concept
points_list = [[0,1,2],
[0,3],
[1,4],
[0,2],
[0,1,2,3],
[0,1,2,4]]

scores = np.zeros((5,5))

for points in points_list:
temp = np.array(points)[:, np.newaxis]
scores[temp, points] += 1


diag = scores.diagonal()

key_col = (scores/diag)[:, 0]
key_col[0] = 0

points_2 = np.where(key_col > 0.5)[0] # suppose 0.5 is the threshold
temp_2 = np.array(points_2)[:, np.newaxis] # step 1: we identified the points that are
# close to 0
inner_scores = scores[temp_2, points_2] # step 1: we are checking if those points are
# are close to each other

打印输出

>>> scores
array([[ 5., 3., 4., 2., 1.], # We identified that 1 and 2 are close to 0
[ 3., 4., 3., 1., 2.],
[ 4., 3., 4., 1., 1.],
[ 2., 1., 1., 2., 0.],
[ 1., 2., 1., 0., 2.]])
>>> inner_scores
array([[ 4., 3.], # Testing to see whether 1 and 2 are close together
[ 3., 4.]]) # Since they are, we can conclude that (0,1,2) occur
# together

正如我现在所看到的,为了使这个想法正常工作,我们需要仔细的递归实现,但我希望这会有所帮助。

关于python - 列表中元素的识别 - 机器学习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21769042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com