求网络的拉普拉斯矩阵(python)

1. 导包

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

2. 求图的拉普拉斯矩阵

# 求图的拉普拉斯矩阵 L = D - A
def laplacian_matrix(graph):
  # 求邻接矩阵
  A = np.array(nx.adjacency_matrix(graph).todense())
  A = -A
  for i in range(len(A)):
  	# 求顶点的度
    degree_i = graph.degree(i+1) # 节点编号从1开始,若从0开始,将i+1改为i
    A[i][i] = A[i][i] + degree_i  
  return A

3. 完整程序

import math
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# 构造图
def generate_graph(): 
  graph = nx.Graph()
  graph.add_edge(1,2)
  graph.add_edge(2,3)
  graph.add_edge(1,4)
  graph.add_edge(1,5)
  graph.add_edge(2,5)
  graph.add_edge(4,5)
  return graph

# 打印图 输入一个图
def print_graph(graph):
  nx.draw(graph, with_labels=True)
  plt.show()

# 求图的拉普拉斯矩阵 L = D - A
def laplacian_matrix(graph):
  # 求邻接矩阵
  A = np.array(nx.adjacency_matrix(graph).todense())
  A = -A
  for i in range(len(A)):
  	# 求顶点的度
    degree_i = graph.degree(i+1) # 节点编号从1开始,若从0开始,将i+1改为i
    A[i][i] = A[i][i] + degree_i  
  return A

# 主方法
if __name__ == "__main__":
  graph = generate_graph()
  print_graph(graph)
  print("拉普拉斯矩阵如下所示;")
  L_M = laplacian_matrix(graph)
  print(L_M)

4. 程序运行结果

在这里插入图片描述

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值