英文:
Bipartite graph to a projection graph
问题
抱歉,我只会翻译文本内容,不会回答关于翻译的问题。以下是您提供的内容的翻译:
"嗨,我正在尝试使用Networkx的projected_graph来投影一个二部图(B),但由于内存限制(B有超过140K个节点),这一直崩溃。我尝试过使用稀疏矩阵进行矩阵乘法来计算邻接矩阵,但由于我的矩阵不够稀疏,这也不起作用。有人能帮助我吗?
import networkx as nx
from networkx.algorithms import bipartite
B.add_nodes_from(inmates_list, bipartite=0)
B.add_nodes_from(cells_list, bipartite=1)
inmates = set(n for n,d in B.nodes(data=True) if d['bipartite']==0)
cells = set(B) - inmates
G = bipartite.projected_graph(B, inmates)
英文:
Hi I'm trying to project a bipartite graph (B) using Networkx's projected_graph but due to memory constraints (B has more than 140K nodes), this keeps crashing. I tried a matrix multiplication using a sparse matrix for computing the adjacency matrix but due to my matrix not being sparse enough, that didn't work either. Can anyone please help with this?
import networkx as nx
from networkx.algorithms import bipartite
B.add_nodes_from(inmates_list, bipartite=0)
B.add_nodes_from(cells_list, bipartite=1)
inmates = set(n for n,d in B.nodes(data=True) if d['bipartite']==0)
cells = = set(B) - inmates
G = bipartite.projected_graph(B, inmates)
答案1
得分: 1
import pandas as pd
import networkx as nx
假设你的DataFrame命名为'df',包含n行和k列的标签
创建一个空图
graph = nx.Graph()
向图中添加节点
graph.add_nodes_from(df.index)
创建一个字典来存储每对节点的权重
weights = {}
遍历标签并根据共同标签的计数更新权重
for label in df.columns:
label_nodes = df.index[df[label] == 1].tolist()
edges = [(u, v) for u, v in nx.utils.pairwise(label_nodes)]
# 更新每个边的权重
for u, v in edges:
if (u, v) in weights:
weights[(u, v)] += (df.loc[u, label].astype(bool) & df.loc[v, label].astype(bool)).sum()
else:
weights[(u, v)] = (df.loc[u, label].astype(bool) & df.loc[v, label].astype(bool)).sum()
将带有更新权重的边添加到图中
graph.add_weighted_edges_from((u, v, weight) for (u, v), weight in weights.items())
现在你有了基于共同标签计数的带权边的图。
英文:
import pandas as pd
import networkx as nx
# Assuming your DataFrame is named 'df' with n rows and k columns for labels
# Create an empty graph
graph = nx.Graph()
# Add nodes to the graph
graph.add_nodes_from(df.index)
# Create a dictionary to store the weights for each pair of nodes
weights = {}
# Iterate over the labels and update the weights based on the count of common labels
for label in df.columns:
label_nodes = df.index[df[label] == 1].tolist()
edges = [(u, v) for u, v in nx.utils.pairwise(label_nodes)]
# Update the weights for each edge
for u, v in edges:
if (u, v) in weights:
weights[(u, v)] += (df.loc[u, label].astype(bool) & df.loc[v, label].astype(bool)).sum()
else:
weights[(u, v)] = (df.loc[u, label].astype(bool) & df.loc[v, label].astype(bool)).sum()
# Add the edges with updated weights to the graph
graph.add_weighted_edges_from((u, v, weight) for (u, v), weight in weights.items())
# Now you have the graph with weighted edges based on the count of common labels
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论