园春编程

from future import division from future import print_function

做一个标记

import argparse import numpy as np import scipy.sparse as sp import torch import torch.nn.functional as F

parser = argparse.ArgumentParser() parser.add_argument('--seed', type=int, default=42, help='Random seed.') parser.add_argument('--dataset', type=str, default='cora', help='type of dataset.') #parser.add_argument('--hops', type=int, default=20, help='number of hops') hops =20 r_list = [0, 0.1, 0.2, 0.3, 0.4, 0.5] args = parser.parse_args()

def sparse_mx_to_torch_sparse_tensor(sparse_mx): '''Convert a scipy sparse matrix to a torch sparse tensor.''' sparse_mx = sparse_mx.tocoo().astype(np.float32) indices = torch.from_numpy( np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64)) values = torch.from_numpy(sparse_mx.data) shape = torch.Size(sparse_mx.shape) return torch.sparse.FloatTensor(indices, values, shape)

def normalize_adj(mx, r): '''Row-normalize sparse matrix''' mx = sp.coo_matrix(mx) + sp.eye(mx.shape[0]) # 将邻接矩阵转换为coo格式,然后加上对角线元素 rowsum = np.array(mx.sum(1)) # 按行求和 r_inv_sqrt_left = np.power(rowsum, r-1).flatten() # 求行向量的r-1次方,并将结果展平 r_inv_sqrt_left[np.isinf(r_inv_sqrt_left)] = 0. # 如果结果中有inf则赋值为0 r_mat_inv_sqrt_left = sp.diags(r_inv_sqrt_left)

r_inv_sqrt_right = np.power(rowsum, -r).flatten() # 求行向量的-r次方,并将结果展平
r_inv_sqrt_right[np.isinf(r_inv_sqrt_right)] = 0. # 如果结果中有inf则赋值为0
r_mat_inv_sqrt_right = sp.diags(r_inv_sqrt_right)
adj_normalized = mx.dot(r_mat_inv_sqrt_left).transpose().dot(r_mat_inv_sqrt_right).tocoo() # 计算D^ r_t-1 A^ ~  D^ -r_t,DAD
return sparse_mx_to_torch_sparse_tensor(adj_normalized)

def run(args): # 1. 加载数据,处理邻接矩阵 adj = torch.tensor([ [1., 1., 0., 0., 0., 0., 0., 1., 0., 0.], [1., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 1., 1., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 1., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [0., 0., 0., 0., 0., 1., 0., 0., 0., 1.], ]) features=torch.tensor([ [1., 1.2, 0., 0., 0., 0., 0., 1., 0.2, 0.], [1., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 1., 0., 0.5, 0., 0., 0., 0., 0.], [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 1., 1., 0., 0., 0., 0., 0.], [0., 0., 2., 0., 0., 1., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0., 1., 0., 0., 0.], [0., 0., 0., 0.4, 0., 0., 0., 1., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [0., 0., 0., 0., 0., 1., 0., 0., 0., 1.], ]) n_nodes, feat_dim = features.shape

for hop in range(hops, hops+1): # hop为迭代次数n
    # shezhi
    input_features = 0.
    for r in r_list:
        adj_norm = normalize_adj(adj, r)  # A^= D^ r_t-1 A^ ~  D^ -r_t,DAD
        features_list = []
        features_list.append(features) #
        features_list.append(torch.spmm(adj_norm, features_list[-1]))  # X,矩阵相乘A*X
        # 计算权重
        weight_list = []
        norm_fea = torch.norm(features, 2, 1).add(1e-10)  # 正则化
        for fea in features_list:
            norm_cur = torch.norm(fea, 2, 1).add(1e-10)
            temp = torch.div((features*fea).sum(1), norm_fea) # 计算相似度
            temp = torch.div(temp, norm_cur)
            weight_list.append(temp.unsqueeze(-1))
        weight = F.softmax(torch.cat(weight_list, dim=1), dim=1) # 权重归一化

        input_feas = []
        #  smooth the node features X
        for i in range(n_nodes):
            fea = 0.
            for j in range(hop+1):# J:0-20
                fea += (weight[i][j]*features_list[j][i]).unsqueeze(0)
            input_feas.append(fea)
        input_feas = torch.cat(input_feas, dim=0)

        if r == r_list[0]:
            input_features = input_feas
        else:
            ## (input_features,input_feas)
            temp = []
            temp.append(input_features.unsqueeze(0))
            temp.append(input_feas.unsqueeze(0))

            input_features = torch.cat(temp, dim=0).max(0)[0]# (input_features,input_feas)(input_features,input_feas)

    sim = torch.sigmoid(torch.mm(input_features, input_features.T))

if name == 'main': run(args)

园春编程:基于图神经网络的节点相似度计算

原文地址: http://www.cveoy.top/t/topic/nsJG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录