STGCN复现第三弹:解读math_graph.py

import numpy as np
import pandas as pd
from scipy.sparse.linalg import eigs

在这里插入图片描述
在这里插入图片描述

scaled_laplacian函数:

def scaled_laplacian(W):
    '''
    Normalized graph Laplacian function. 标准化拉普拉斯矩阵
    :param W: np.ndarray, [n_route, n_route], weighted adjacency matrix of G.
    :return: np.matrix, [n_route, n_route].
    '''
    # d ->  diagonal degree matrix 度矩阵
    n, d = np.shape(W)[0], np.sum(W, axis=1)      #1.取出矩阵W的维度 2.将矩阵W的列向量相加
    ’‘’
    举例:
    c = np.array([[0, 2, 1], [3, 5, 6], [0, 1, 1]])
	print c.sum()
	print c.sum(axis=0)
	print c.sum(axis=1)
	结果分别是:19, [3 8 8], [ 3 14  2]
    ‘’‘
    # L -> graph Laplacian
    L = -W
    L[np.diag_indices_from(L)] = d  #返回索引以访问n维数组L的主对角线
    for i in range(n):
        for j in range(n):
            if (d[i] > 0) and (d[j] > 0):
                L[i, j] = L[i, j] / np.sqrt(d[i] * d[j])
    # lambda_max \approx(大约) 2.0, the largest eigenvalues(特征值) of L.
    lambda_max = eigs(L, k=1, which='LR')[0][0].real  # 1. k:int, 可选参数所需的特征值和特征向量的数量。 2.‘LR’:largest real part 3. x.real取得xd的实部
     #eigs()全称为scipy.sparse.linalg.eigs()用于求平方矩阵A的k个特征值和特征向量。
    return np.mat(2 * L / lambda_max - np.identity(n)) 	#np.identity(n)生成一个n行n列的单位矩阵

np.identity()函数详解
scipy.sparse.linalg.eigs()函数详解~

在这里插入图片描述

cheb_poly_approx函数:

def cheb_poly_approx(L, Ks, n):
    '''
    Chebyshev(切比雪夫) polynomials(多项式) approximation(逼近、近似) function.
    :param L: np.matrix, [n_route, n_route], graph Laplacian(拉普拉斯算子).
    :param Ks: int, kernel size of spatial convolution(空间卷积核大小).
    :param n: int, number of routes / size of graph.(图的大小)
    :return: np.ndarray, [n_route, Ks*n_route]. 返回一个np.ndarray的多维数组
    '''
    L0, L1 = np.mat(np.identity(n)), np.mat(np.copy(L))  	#np.copy():返回给定对象的数组副本

    if Ks > 1:
        L_list = [np.copy(L0), np.copy(L1)]
        for i in range(Ks - 2):
            Ln = np.mat(2 * L * L1 - L0)
            L_list.append(np.copy(Ln))
            L0, L1 = np.matrix(np.copy(L1)), np.matrix(np.copy(Ln))
        # L_lsit [Ks, n*n], Lk [n, Ks*n]
        return np.concatenate(L_list, axis=-1)
    elif Ks == 1:
        return np.asarray(L0) 	#将输入转换为数组
    else:
        raise ValueError(f'ERROR: the size of spatial kernel must be greater than 1, but received "{Ks}".')

np.copy()函数详解
np.concatenate()函数详解
numpy.asarray()函数详解

first_approx()函数:

def first_approx(W, n):
    '''
    1st-order approximation function.
    :param W: np.ndarray, [n_route, n_route], weighted adjacency matrix of G.
    :param n: int, number of routes / size of graph.
    :return: np.ndarray, [n_route, n_route].
    '''
    A = W + np.identity(n)
    d = np.sum(A, axis=1)
    sinvD = np.sqrt(np.mat(np.diag(d)).I)
    # refer to Eq.5
    return np.mat(np.identity(n) + sinvD * A * sinvD)

weight_matrix()函数:

def weight_matrix(file_path, sigma2=0.1, epsilon=0.5, scaling=True):
    '''
    Load weight matrix function.
    :param file_path: str, the path of saved weight matrix file.
    :param sigma2: float, scalar of matrix W.
    :param epsilon: float, thresholds to control the sparsity of matrix W.
    :param scaling: bool, whether applies numerical scaling on W.
    :return: np.ndarray, [n_route, n_route].
    '''
    try:
        W = pd.read_csv(file_path, header=None).values
    except FileNotFoundError:
        print(f'ERROR: input file was not found in {file_path}.')

    # check whether W is a 0/1 matrix.
    if set(np.unique(W)) == {0, 1}:
        print('The input graph is a 0/1 matrix; set "scaling" to False.')
        scaling = False

    if scaling:
        n = W.shape[0]
        W = W / 10000.
        W2, W_mask = W * W, np.ones([n, n]) - np.identity(n)
        # refer to Eq.10
        return np.exp(-W2 / sigma2) * (np.exp(-W2 / sigma2) >= epsilon) * W_mask
    else:
        return W

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,假设我们有两个有向图,分别是图G1和图G2。我们想要将这两个图合并成一个大的二分图,以便将它们作为一个整体输入到某些机器学习模型中。 首先,我们需要将这两个图转换为稀疏的邻接矩阵。假设 `graph_1` 和 `graph_2` 分别是这两个图的邻接矩阵,我们可以使用scipy库来实现: ```python import numpy as np from scipy.sparse import lil_matrix # 生成图G1的邻接矩阵 graph_1 = lil_matrix((3, 3)) graph_1[0, 1] = 1 graph_1[1, 2] = 1 # 生成图G2的邻接矩阵 graph_2 = lil_matrix((2, 2)) graph_2[0, 1] = 1 # 将两个邻接矩阵合并成一个大的二分图 x_1 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) # 图G1的节点特征 x_2 = np.array([[2, 2], [3, 3]]) # 图G2的节点特征 x_cat = np.concatenate((x_1, x_2), axis=0) # 将节点特征合并 bi_graph = torch.zeros(x_cat.shape[0], x_cat.shape[0]) bi_graph[:x_1.shape[0], x_1.shape[0]:] = graph_1.toarray() # 将图G1的邻接矩阵赋值给左下角的子矩阵 bi_graph[x_1.shape[0]:, x_1.shape[0]:] = graph_2.toarray() # 将图G2的邻接矩阵赋值给右下角的子矩阵 ``` 在这个例子中,我们首先使用 `lil_matrix()` 函数创建了两个有向图G1和G2的邻接矩阵。然后,我们将这两个邻接矩阵合并成一个大的二分图,以便将它们作为一个整体输入到某些机器学习模型中。具体来说,我们将G1的节点特征和G2的节点特征合并,形成一个新的特征矩阵 `x_cat`。然后,我们创建了一个大小为 `x_cat.shape[0]` x `x_cat.shape[0]` 的零矩阵,并将G1的邻接矩阵赋值给这个零矩阵的左下角子矩阵,将G2的邻接矩阵赋值给右下角子矩阵。这样,我们就得到了一个大的二分图,其中左半部分对应于G1,右半部分对应于G2。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值