如何将字典转换成矩阵?

2024-09-29 02:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算日志文件中出现的多个项目之间的相关性百分比。通过这样做,我得到它们出现的次数除以它们出现的次数,而另一个项目存在。 我不想谈太多细节,但这种相关性是不对称的 (A和B之间的相关性与B和A之间的相关性不同)

作为输出,我有一个格式如下的字典:

{
    itemA:  {
        itemB: 0.85,
        itemC: 0.12
    },
    itemB:  {
        itemC: 0.68,
        itemA: 0.24
    },
    itemC:  {
        itemA: 0.28
    }
}

我试过使用DictVectorizer来自sklearnDictVectorizer,但它不起作用,因为它需要一个字典列表。你知道吗

我希望输出是一个矩阵,用matplotlib可视化

像这样:

[[1,0.85,0.12]
[0.68,1,0.24]
[0.28,0,1]]

如果可能的话,我也希望有一个matplotlib可视化与图例为每一行和每一列,因为我的dict有方式超过3项。你知道吗

我希望一切都清楚。 谢谢你的帮助。你知道吗


Tags: 文件项目列表字典matplotlib可视化格式sklearn
2条回答

下面是一个使用数组的代码,但是您可以很容易地将它调整为您想要使用的序列。你知道吗

dictionary = {
    'itemA':  {
        'itemB': 0.85,
        'itemC': 0.12
    },
    'itemB':  {
        'itemA': 0.68,
        'itemC': 0.24
    },
    'itemC':  {
        'itemA': 0.28
    }
}

matrix = []
i = 0
for v in dictionary.values():
    tmp_mat = []
    for h in v.values():
        if len(tmp_mat) == i:
            tmp_mat.append(1)
        tmp_mat.append(h)
    i += 1
    if len(tmp_mat) == len(v):
        tmp_mat.append(1)
    matrix.append(tmp_mat)

print(matrix)

输出:

[[1, 0.85, 0.12], [0.68, 1, 0.24], [0.28, 1]]

unpacking keys and values of a dictionary

你可以用熊猫和numpy有效地做到这一点:

import pandas as pd

d = {
    'itemA':  {
        'itemB': 0.85,
        'itemC': 0.12
    },
    'itemB':  {
        'itemA': 0.68,
        'itemC': 0.24
    },
    'itemC':  {
        'itemA': 0.28
    }
}

df = pd.DataFrame(d)

# since this is a matrix of co-occurrences of a set of objects,
# sort columns and rows alphabetically
df = df.sort_index(axis=0)
df = df.sort_index(axis=1)

# the matrix is now the values of the dataframe
a = df.values.T

# if needed, fill the diagonal with 1 and replace NaN with 0
import numpy as np

np.fill_diagonal(a, 1)
a[np.isnan(a)] = 0

矩阵现在是:

array([[1.  , 0.85, 0.12],
       [0.68, 1.  , 0.24],
       [0.28, 0.  , 1.  ]])

要可视化此矩阵:

import matplotlib.pyplot as plt
plt.matshow(a)
plt.show()

行和列ID将显示为标签。你知道吗

相关问题 更多 >