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

环境

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}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值