NetworkX基本教程

NetworkX官方文档

# Upgrade packages
!pip install --upgrade scipy networkx

# Import the NetworkX package
import networkx as nx

1.图级别操作

# 建立无向图
G = nx.Graph()
print(G.is_directed())

# 建立有向图
H = nx.DiGraph()
print(H.is_directed())
# 添加图级别属性
G.graph["Name"] = "Bar"
print(G.graph)

2.点级别操作

# 添加点,附带属性
G.add_node(0, feature=5, label=0)

# 获取节点0的属性
node_0_attr = G.nodes[0]
print("Node 0 has the atrribute {}".format(node_0_attr))
# 图中所有节点信息
G.nodes(data=True)
# 添加多个节点
G.add_nodes_from([
    (1, {"feature": 1, "label": 1}),
    (2, {"feature": 2, "label": 2})
])
# 遍历所有节点
for node in G.nodes(data=True):
    print(node)
# 获取点的数量
num_nodes = G.number_of_nodes()
print("G has {} nodes".format(num_nodes))

3.边级别操作

# 添加权重为0.5的边(0,1)
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))
# 添加多条边
G.add_edges_from([
    (1, 2, {"weight": 0.3}),
    (2, 0, {"weight": 0.1}),
])
# 遍历所有的边
for edge in G.edges():
    print(edge)
# 获得边的数量
num_edges = G.number_of_edges()
print("G has {} edges".format(num_edges))

4.图的可视化

nx.draw(G, with_labels = True)

5.节点度数和邻居节点

# 获取节点度数
node_id = 1
print("Node {} has degree {}".format(node_id, G.degree[node_id]))
# 获取节点邻居
node_id = 1
for neighbor in G.neighbors(node_id):
    print("Node {} has neighbor {}".format(node_id, neighbor))

6.计算节点的PageRank

num_nodes = 4
# 创建一个有向图(path_graph相当于生成的图是一条线)
G = nx.DiGraph(nx.path_graph(num_nodes))
nx.draw(G, with_labels = True)
# 计算pagerank
pr = nx.pagerank(G, alpha=0.8)
pr

你可能感兴趣的:(Graph,Learning,python,数据挖掘,图神经网络,NetworkX)