使用 NetworkX 从邻接矩阵构建具有相似值的边?
我已经从如下节点构建了一个图表:
data = pd.DataFrame({
'id': [1, 2, 3, 4, 5],
'a': [55, 2123, -19.3, 9, -8],
'b': [21, -0.1, 0.003, 4, 2.1]
})
import networkx as nx
G = nx.Graph()
for i, attr in data.set_index('id').iterrows():
G.add_node(i, **attr.to_dict())
我已经计算了相似度矩阵(通过排除 id 列)。
from sklearn.metrics.pairwise import cosine_similarity
# Calculate the pairwise cosine similarities
S = cosine_similarity(data.drop('id', axis=1))
T = S.tolist()
df = pd.DataFrame.from_records(T)
这是我的 adj 矩阵:
adj_mat = pd.DataFrame(df.to_numpy(), index=data['id'], columns=data['id'])
现在,我如何使用此 adj_mat“附加”并连接节点?例如,我希望 id = 1 的节点连接到 id = 2 的节点,其边的相似度参数等于 adj 矩阵中计算的相似度。
请告知如何做。
I have build a graph from nodes like:
data = pd.DataFrame({
'id': [1, 2, 3, 4, 5],
'a': [55, 2123, -19.3, 9, -8],
'b': [21, -0.1, 0.003, 4, 2.1]
})
import networkx as nx
G = nx.Graph()
for i, attr in data.set_index('id').iterrows():
G.add_node(i, **attr.to_dict())
I have calculated similarity matrix (by excluding the id
column).
from sklearn.metrics.pairwise import cosine_similarity
# Calculate the pairwise cosine similarities
S = cosine_similarity(data.drop('id', axis=1))
T = S.tolist()
df = pd.DataFrame.from_records(T)
Here is my adj matrix:
adj_mat = pd.DataFrame(df.to_numpy(), index=data['id'], columns=data['id'])
Now, how can I "attach" and connect the nodes using this adj_mat? For example I want node with id = 1 to connect to node with id = 2 with an edge with a similarity parameter equals to the similarity calculated in adj matrix.
Please advise how to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过首先从 adj 矩阵构建图表来解决:
然后循环我的节点数据,用节点的属性更新节点(并删除自循环):
希望它能帮助其他人:)
Solved by firstly building the graph from adj matrix:
Then looping on my nodes data, update the nodes with their attributes (and remove the self loops):
Hope it will help others :)