首页 > 解决方案 > 在视觉上显示列表之间相似性的最理想方式是什么?

问题描述

我有以下形式的数据:

每一秒,N秒,我将M个字符串写入一个列表 [ M(i), i = {1,..,N}不一定等于M(j), j = {1,..,N | j != i} ]。我在 3 个实例中执行此操作。也就是说,我每秒创建 3 个任意数量的字符串列表,总共N秒。

现在,我想直观地显示每个列表(每秒)中共有多少个字符串作为(可能)相关性或相似性矩阵。我想在所有N秒内重复此操作。我不确定我该怎么做。

假设N = 3

# instance 1
I1 = [['cat', 'dog', 'bob'], # 1st second
      ['eel', 'pug', 'emu'], # 2nd second
      ['owl', 'yak', 'elk']] # 3rd second
# instance 2
I2 = [['dog', 'fox', 'rat'], # 1st second
      ['emu', 'pug', 'ram'], # 2nd second
      ['bug', 'bee', 'bob']] # 3rd second
# instance 3
I3 = [['cat', 'bob', 'fox'], # 1st second
      ['emu', 'pug', 'eel'], # 2nd second
      ['bob', 'bee', 'yak']] # 3rd second

在 Python 中的实例中每秒可视化公共元素数量的最佳方法是什么?PS,我已经可以将其绘制为图表,但我对创建相关性或相似性矩阵感兴趣。

标签: pythondata-visualization

解决方案


您可以遍历并创建自己的相似度矩阵,并使用 matplotlib 的 imshow 函数绘制矩阵。对于这种方法,它将是几秒钟内的完全相似度,否则您将需要一个 3 维相似度矩阵。使用下面的代码是可行的,但是您需要找到除 imshow 之外的另一种可视化方式

import numpy as np
import matplotlib.pyplot as plt

# instance 1
I1 = [['cat', 'dog', 'bob'], # 1st second
      ['eel', 'pug', 'emu'], # 2nd second
      ['owl', 'yak', 'elk']] # 3rd second
# instance 2
I2 = [['dog', 'fox', 'rat'], # 1st second
      ['emu', 'pug', 'ram'], # 2nd second
      ['bug', 'bee', 'bob']] # 3rd second
# instance 3
I3 = [['cat', 'bob', 'fox'], # 1st second
      ['emu', 'pug', 'eel'], # 2nd second
      ['bob', 'bee', 'yak']] # 3rd second

total = [I1, I2, I3]

# initialize similarity matrix by number of instances you have
sim_matrix = np.zeros(shape=(len(total), len(total)))

# constant per your explanation
N = 3

# for each row in sim matrix
for i in range(len(total)):

    # for each column in sim matrix
    for j in range(len(total)):

        # if comparing itself
        if i == j:

            # similarity is total # of strings across all seconds (may not be constant)
            sim_matrix[i, j] = sum([len(t) for t in total[i]])

        else:

            # sum up each set intersection of each list of strings at each second
            sim_matrix[i, j] = sum([len(list(set(total[i][s]) & set(total[j][s]))) for s in range(N)])

sim_matrix应该

array([[9., 3., 6.],
       [3., 9., 5.],
       [6., 5., 9.]])

您可以使用imshow

plt.imshow(sim_matrix)
plt.colorbar()
plt.show()

在此处输入图像描述

几乎可以肯定有更好和更有效的方法来做到这一点,但如果你的列表数量很少,这可能没问题。

编辑

如果您需要每秒相似度矩阵,您可以使用以下修改后的代码

sim_matrix = np.zeros(shape=(len(total), len(total), len(total)))

for i in range(len(total)):

    for j in range(len(total)):

        if i == j:

            sim_matrix[:, i, j] = [len(t) for t in total[i]]

        else:

            sim_matrix[:, i, j] = [len(list(set(total[i][s]) & set(total[j][s]))) for s in range(N)]

您可以使用imshowstill 来可视化 3-d 相似度矩阵,但它会将每个切片解释为 RBG 颜色通道。


推荐阅读