csv 파일에 데이터가 있고 아래와 같이 팬더를 통해 읽습니다.
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
sub_data = pd.read_csv('sample.csv')
산출:
user_id item_id rating
0 772 36 3
1 471 228 5
2 641 401 4
3 312 98 4
4 58 504 5
이 데이터를 사용하여 네트워크 그래프 만들기 :
edges = [tuple(x) for x in sub_data[['user_id','item_id']].values.tolist()]
B = nx.Graph()
B.add_nodes_from(sub_data['user_id'].unique(), bipartite=0, label='user')
B.add_nodes_from(sub_data['item_id'].unique(), bipartite=1, label='item')
B.add_edges_from(edges, label='rating')
아래 코드를 사용하여 그래프 그리기 :
pos=nx.spring_layout(B)
nx.draw(B,pos,node_color='#A0CBE2',edge_color='#00bb5e',width=1,
edge_cmap=plt.cm.Blues,with_labels=True)
노드 만 얻고 있습니다. 여기서 노드를 연결하고 해당 연결에 대한 레이블로 등급을 지정해야합니다.
당신이 작성한 코드를 실행하려고했는데, 이분 그래프를 얻을 수있었습니다. 귀하의 경우 NetworkX가 내 것과 유사한 이분 그래프를 렌더링 할 수 있다고 가정하고 있지만 그래프에 더 많은 노드가 있으므로 가장자리가 제대로 표시되지 않습니다. 이 같은
가장자리가 거의 보이지 않음을 알 수 있습니다. 또한 노드 수를 10 개로 제한하면 가장자리도 볼 수 있습니다. 예제를 복제하는 데 관심이 있다면 다음은 샘플 csv 데이터입니다 (질문에 제공된 데이터에 몇 가지 포인트를 더 추가했습니다).
,user_id,item_id,rating
0,772,36,3
1,471,228,5
2,641,401,4
3,312,98,4
4,58,504,5
5,67,98,4
6,471,229,3
이제 양측에 두 세트의 노드가있는 Bipartite 레이아웃에서 그래프를보고 싶다는 것을 이해합니다. 이를 달성하기 위해 대신 bipartite_layout 을 사용해야 spring_layout
합니다.
다음은 전체 코드입니다.
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
sub_data = pd.read_csv('sample.csv')
edges = [tuple(x) for x in sub_data[['user_id','item_id']].values.tolist()]
B = nx.Graph()
B.add_nodes_from(sub_data['user_id'].unique(), bipartite=0, label='user')
B.add_nodes_from(sub_data['item_id'].unique(), bipartite=1, label='item')
B.add_edges_from(edges, label='rating')
# Now instead of spring_layout, use bipartite_layout
# First specify the nodes you want on left or top
left_or_top = sub_data['user_id'].unique()
# Then create a bipartite layout
pos = nx.bipartite_layout(B, left_or_top)
# Pass that layout to nx.draw
nx.draw(B,pos,node_color='#A0CBE2',edge_color='#00bb5e',width=1,
edge_cmap=plt.cm.Blues,with_labels=True)
또한 여기 에 언급 된대로 bipartite_sets 를 bipartite_layout
사용 하는 대신 에 한 노드 집합을 명시 적으로 전달했습니다. 그래프가 연결 해제되어 AmbiguousSolution Error로 이어질 수 있기 때문 입니다. 자세한 내용은 여기 와 여기 에서 설명서를 참조 하십시오 .
이 Google Colab 노트북 에서 전체 코드를 볼 수도 있습니다 .
업데이트 : 엣지를 보여주고 싶을 경우 아래와 같이 할당해야합니다. (등급 추가 코드가 잘못되었습니다)
# Extract the ratings while extracting the edges from DF
edges = [tuple(x) for x in sub_data[['user_id','item_id', 'rating']].values.tolist()]
B = nx.Graph()
B.add_nodes_from(sub_data['user_id'].unique(), bipartite=0, label='user')
B.add_nodes_from(sub_data['item_id'].unique(), bipartite=1, label='item')
# Now assign the ratings correctly to edges
for row in edges:
B.add_edge(row[0], row[1], rating=row[2])
이제 draw_netwokrx_edge_labels를 사용하여 가장자리 레이블을 그 립니다 .
left_or_top = sub_data['user_id'].unique()
pos = nx.bipartite_layout(B, left_or_top)
# Draw the graph
nx.draw(B,pos,node_color='#A0CBE2',edge_color='#00bb5e',width=1,
edge_cmap=plt.cm.Blues,with_labels=True)
# Get the edge labels for ratings
edge_labels = nx.get_edge_attributes(B,'rating')
# Draw the edge labels
nx.draw_networkx_edge_labels(B, pos, edge_labels=edge_labels)
참조 :
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다