在深度学习或者机器学习中,关系转换为矩阵是常用的操作。这里提供两种方法
思路:固定定义了一个字典用于查询索引,先生成一个全零矩阵,然后遍历关系列表将矩阵对应索引处的值改为 1
relation_list = [('赵四', '王五'), ('赵四', '理论'), ('赵四', '王琦'), ('王五', '王琦'),
('王五', '赵四'), ('王琦', '王五'), ('王琦', '赵四'), ('理论', '赵四')]
member_dict = {}
member_index = 0
for name_tuple in relation_list:
for name in name_tuple:
if name in member_dict:
continue
member_dict[name] = member_index
member_index += 1
relation_matrix = [[0 for i in range(len(member_dict))]
for i in range(len(member_dict))]
for (x, y) in relation_list:
x_index = member_dict[x]
y_index = member_dict[y]
relation_matrix[x_index][y_index] = 1
print(relation_matrix)
import scipy as sp
import networkx as nx
relation_list = [('赵四', '王五'), ('赵四', '理论'), ('赵四', '王琦'), ('王五', '王琦'),
('王五', '赵四'), ('王琦', '王五'), ('王琦', '赵四'), ('理论', '赵四')]
g = nx.Graph(relation_list)
A = nx.to_numpy_matrix(g)
print(A)
这个方法需要注意的是矩阵的索引问题。
[1]怎么用Python将关系对转为邻接矩阵?