【斯坦福CS224W图机器学习】作业 Colab0-Networkx库的使用

  • Post author:
  • Post category:其他




环境


networkx 2.2



matplotlib 2.2.3

NetworkX is one of the most frequently used Python packages to create, manipulate, and mine graphs.

import networkx as nx



Graph图

# 建立一个无向图G
G = nx.Graph()
print(G.is_directed())
False
# 建立一个有向图 H
H = nx.DiGraph()
print(H.is_directed())
True
# 给图增加一个图级别(Graph-level)的属性
G.graph["Name"] = "Bar"
print(G.graph)
{'Name': 'Bar'}



Node 节点

Nodes (with attributes) can be easily added to NetworkX graphs.

# 给节点添加节点级别的属性
G.add_node(0,feature=0,lable=0)

# 取出节点0的属性
node_0_attr = G.node[0]
print("节点0有属性{}".format(node_0_attr))
节点0有属性{'feature': 0, 'lable': 0}
# 给图添加多个具有属性的节点
G.add_nodes_from([
    (1,{"feature":1,"label":1}),
    (2,{"feature":2,"label":2})
])
# 遍历所有节点
# Set data=True will return node attributes
for node in G.nodes(data=True):
    print(node)

# 查看节点数量
num_nodes = G.number_of_nodes()
print("图G有{}个节点".format(num_nodes))
(0, {'feature': 0, 'lable': 0})
(1, {'feature': 1, 'label': 1})
(2, {'feature': 2, 'label': 2})
图G有3个节点



Edge边

Similar to nodes, edges (with attributes) can also be easily added to NetworkX graphs.

# 添加一个权重为0.5的边
G.add_edge(0,1,weight=0.5)

# 查看边(0,1)的属性
edge_0_1_attr = G.edges[(0,1)]
print("Edge (0, 1) has the attributes {}".format(edge_0_1_attr))
Edge (0, 1) has the attributes {'weight': 0.5}
# 给图添加多个具有属性的边
G.add_edges_from([
    (1,2,{"weight":0.3}),
    (2,0,{"weight":0.1})
])
# 遍历所有边
# Set data=True will return node attributes
for edge in G.edges(data=True):
    print(edge)
    
# 查看edge数量
num_edges = G.number_of_edges()
print("图G有{}条边".format(num_edges))
(0, 1, {'weight': 0.5})
(0, 2, {'weight': 0.1})
(1, 2, {'weight': 0.3})
图G有3条边



可视化

nx.draw(G,with_labels=True)



在这里插入图片描述



Node Degree and Neighbor 节点的度和邻居

node_id = 1
# 节点1的度
print("Node{} has degree {}".format(node_id,G.degree(node_id)))

# 节点1的邻居节点
for neigbhor in G.neighbors(node_id):
    print("Node {} has neighbor {}".format(node_id,neigbhor))
Node1 has degree 2
Node 1 has neighbor 0
Node 1 has neighbor 2



networkx库的其他函数

NetworkX also provides plenty of useful methods to study graphs.

Here is an example to get

PageRank

of nodes (we will talk about PageRank in one of the future lectures).

nodes = 4
# Create a new path like graph and change it to a directed graph
M = nx.DiGraph(nx.path_graph(nodes))
nx.draw(M,withlabel=True)

在这里插入图片描述

# Get the pagerank
pr = nx.pagerank(M, alpha=0.8)
pr
{0: 0.17857162031103999,
 1: 0.32142837968896,
 2: 0.32142837968896,
 3: 0.17857162031103999}



版权声明:本文为qq_42447107原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。