-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
75 lines (59 loc) · 2.52 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from torch_geometric.utils import add_remaining_self_loops, degree
from torch_scatter import scatter
import random
import torch
import os
import numpy as np
import torch.nn.functional as F
from torch_sparse import SparseTensor, matmul, fill_diag, sum as sparsesum, mul
import pandas as pd
def propagate(x, edge_index, edge_weight=None):
edge_index, _ = add_remaining_self_loops(edge_index, num_nodes=x.size(0))
# calculate the degree normalize term
row, col = edge_index
deg = degree(col, x.size(0), dtype=x.dtype)
deg_inv_sqrt = deg.pow(-0.5)
# for the first order appro of laplacian matrix in GCN, we use deg_inv_sqrt[row]*deg_inv_sqrt[col]
if(edge_weight == None):
edge_weight = deg_inv_sqrt[row] * deg_inv_sqrt[col]
# normalize the features on the starting point of the edge
out = edge_weight.view(-1, 1) * x[row]
return scatter(out, edge_index[-1], dim=0, dim_size=x.size(0), reduce='add')
def propagate2(x, edge_index):
edge_index, _ = add_remaining_self_loops(
edge_index, num_nodes=x.size(0))
# calculate the degree normalize term
row, col = edge_index
deg = degree(col, x.size(0), dtype=x.dtype)
deg_inv_sqrt = deg.pow(-0.5)
# for the first order appro of laplacian matrix in GCN, we use deg_inv_sqrt[row]*deg_inv_sqrt[col]
edge_weight = deg_inv_sqrt[row] * deg_inv_sqrt[col]
# normalize the features on the starting point of the edge
out = edge_weight.view(-1, 1) * x[row]
return scatter(out, edge_index[-1], dim=0, dim_size=x.size(0), reduce='add')
def seed_everything(seed=0):
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
torch.backends.cudnn.allow_tf32 = False
os.environ['PYTHONHASHSEED'] = str(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.enabled = True
# torch.use_deterministic_algorithms(True)
def fair_metric(pred, labels, sens):
idx_s0 = sens == 0
idx_s1 = sens == 1
idx_s0_y1 = np.bitwise_and(idx_s0, labels == 1)
idx_s1_y1 = np.bitwise_and(idx_s1, labels == 1)
parity = abs(sum(pred[idx_s0]) / sum(idx_s0) -
sum(pred[idx_s1]) / sum(idx_s1))
equality = abs(sum(pred[idx_s0_y1]) / sum(idx_s0_y1) -
sum(pred[idx_s1_y1]) / sum(idx_s1_y1))
return parity.item(), equality.item()
def random_drop_edges(adj, drop_prob):
mask = torch.rand(adj.size()) > drop_prob
adj = adj * mask
adj = adj + adj.t() - adj * adj.t()
return adj