mcy98 commited on
Commit
e7f614b
·
verified ·
1 Parent(s): ae0d8e5

Delete folder annotations/annotation_130 with huggingface_hub

Browse files
annotations/annotation_130/FairGB/Figures/FairGB-overview.jpg DELETED

Git LFS Details

  • SHA256: c083274e426c9392793b41a128930eac12650940fe4a3f3b70f877e7340ca71d
  • Pointer size: 131 Bytes
  • Size of remote file: 261 kB
annotations/annotation_130/FairGB/Figures/embedding.jpg DELETED

Git LFS Details

  • SHA256: 6b2caa6b6ca3c430ad4f88b7d494ff107e272fd3e8c14ddb684c5620daca58fb
  • Pointer size: 131 Bytes
  • Size of remote file: 300 kB
annotations/annotation_130/FairGB/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Zhixun-Li
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/FairGB/README.md DELETED
@@ -1,48 +0,0 @@
1
- # Rethinking Fair Graph Neural Networks from Re-balancing
2
-
3
- >This is the official implementation of the following paper:
4
- >
5
- >Rethinking Fair Graph Neural Networks from Re-balancing (SIGKDD'2024)
6
-
7
- <p align="left"><img src="Figures/FairGB-overview.jpg" width=70% height=75%></p>
8
-
9
- <p align="left"><img src="Figures/embedding.jpg" width=70% height=75%></p>
10
-
11
- ## Table of Contents
12
-
13
- - [Rethinking Fair Graph Neural Networks from Re-balancing](#rethinking-fair-graph-neural-networks-from-re-balancing)
14
- - [Dependencies](#dependencies)
15
- - [Datasets](#datasets)
16
- - [Running](#running)
17
-
18
- ## Dependencies
19
- * python>=3.7
20
- * torch==2.0.1
21
- * torch-geometric==2.3.1
22
- * torch-scatter==2.1.1
23
- * numpy==1.24.4
24
- * scikit-learn==1.3.0
25
-
26
- ## Datasets
27
-
28
- We conduct experiments on three widely used real-world datasets, namely German Credit, Bail, and Credit Defaulter. The detailed information of the datasets is as follows. Please unzip datasets in ```./dataset``` before running the model.
29
-
30
- |Dataset|German|Bail|Credit|
31
- |---|---|---|---|
32
- |# Nodes|1,000|18,876|30,000|
33
- |# Edges|22,242|321,308|152,377|
34
- |# Attributes|27|18|13|
35
- |Sens.|Gender|Race|Age|
36
- |Label|Credit status|Bail decision|Future default|
37
-
38
- ## Running
39
-
40
- The ```run.sh``` includes details to reproduce experimental results in the paper:
41
-
42
- ```
43
- bash run.sh
44
- ```
45
-
46
- ## Acknowledgement
47
-
48
- Our code is based on the FairVGNN (Improving fairness in graph neural networks via mitigating sensitive attribute leakage) and GraphENS (Graphens: Neighbor-aware ego network synthesis for class-imbalanced node classification).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/FairGB/data_utils.py DELETED
@@ -1,294 +0,0 @@
1
- import torch
2
- import pandas as pd
3
- import os
4
- import numpy as np
5
- import scipy.sparse as sp
6
- from scipy.spatial import distance_matrix
7
- from torch_geometric.utils import from_scipy_sparse_matrix
8
- from torch_geometric.data import Data
9
-
10
-
11
- def feature_norm(features):
12
- min_values = features.min(axis=0)[0]
13
- max_values = features.max(axis=0)[0]
14
- return 2 * (features - min_values).div(max_values - min_values) - 1
15
-
16
-
17
- def index_to_mask(node_num, index):
18
- mask = torch.zeros(node_num, dtype=torch.bool)
19
- mask[index] = 1
20
-
21
- return mask
22
-
23
-
24
- def sparse_mx_to_torch_sparse_tensor(sparse_mx):
25
- """Convert a scipy sparse matrix to a torch sparse tensor."""
26
- sparse_mx = sparse_mx.tocoo().astype(np.float32)
27
- indices = torch.from_numpy(
28
- np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
29
- values = torch.from_numpy(sparse_mx.data)
30
- shape = torch.Size(sparse_mx.shape)
31
-
32
- return torch.sparse.FloatTensor(indices, values, shape)
33
-
34
-
35
- def sys_normalized_adjacency(adj):
36
- adj = sp.coo_matrix(adj)
37
- adj = adj + sp.eye(adj.shape[0])
38
- row_sum = np.array(adj.sum(1))
39
- row_sum = (row_sum == 0) * 1 + row_sum
40
- d_inv_sqrt = np.power(row_sum, -0.5).flatten()
41
- d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
42
- d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
43
-
44
- return d_mat_inv_sqrt.dot(adj).dot(d_mat_inv_sqrt).tocoo()
45
-
46
-
47
- def build_relationship(x, thresh=0.25):
48
- df_euclid = pd.DataFrame(
49
- 1 / (1 + distance_matrix(x.T.T, x.T.T)), columns=x.T.columns, index=x.T.columns)
50
- df_euclid = df_euclid.to_numpy()
51
- idx_map = []
52
- for ind in range(df_euclid.shape[0]):
53
- max_sim = np.sort(df_euclid[ind, :])[-2]
54
- neig_id = np.where(df_euclid[ind, :] > thresh * max_sim)[0]
55
- import random
56
- random.seed(912)
57
- random.shuffle(neig_id)
58
- for neig in neig_id:
59
- if neig != ind:
60
- idx_map.append([ind, neig])
61
- # print('building edge relationship complete')
62
- idx_map = np.array(idx_map)
63
-
64
- return idx_map
65
-
66
-
67
- def load_credit(dataset, sens_attr="Age", predict_attr="NoDefaultNextMonth", path="dataset/credit/", label_number=1000, test_idx=None):
68
- # print('Loading {} dataset from {}'.format(dataset, path))
69
- idx_features_labels = pd.read_csv(
70
- os.path.join(path, "{}.csv".format(dataset)))
71
- header = list(idx_features_labels.columns)
72
- header.remove(predict_attr)
73
- header.remove('Single')
74
-
75
- # build relationship
76
- if os.path.exists(f'{path}/{dataset}_edges.txt'):
77
- edges_unordered = np.genfromtxt(
78
- f'{path}/{dataset}_edges.txt').astype('int')
79
- else:
80
- edges_unordered = build_relationship(
81
- idx_features_labels[header], thresh=0.7)
82
- np.savetxt(f'{path}/{dataset}_edges.txt', edges_unordered)
83
-
84
- features = sp.csr_matrix(idx_features_labels[header], dtype=np.float32)
85
- # print(features)
86
- labels = idx_features_labels[predict_attr].values
87
-
88
- idx = np.arange(features.shape[0])
89
- idx_map = {j: i for i, j in enumerate(idx)}
90
- edges = np.array(list(map(idx_map.get, edges_unordered.flatten())),
91
- dtype=int).reshape(edges_unordered.shape)
92
-
93
- adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),
94
- shape=(labels.shape[0], labels.shape[0]),
95
- dtype=np.float32)
96
-
97
- # build symmetric adjacency matrix
98
- adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)
99
- adj = adj + sp.eye(adj.shape[0])
100
- adj_norm = sys_normalized_adjacency(adj)
101
- adj_norm_sp = sparse_mx_to_torch_sparse_tensor(adj_norm)
102
-
103
- edge_index, _ = from_scipy_sparse_matrix(adj)
104
-
105
- features = torch.FloatTensor(np.array(features.todense()))
106
- labels = torch.LongTensor(labels)
107
-
108
- import random
109
- random.seed(20)
110
- label_idx_0 = np.where(labels == 0)[0]
111
- label_idx_1 = np.where(labels == 1)[0]
112
- random.shuffle(label_idx_0)
113
- random.shuffle(label_idx_1)
114
-
115
- idx_train = np.append(label_idx_0[:min(int(0.5 * len(label_idx_0)), label_number // 2)],
116
- label_idx_1[:min(int(0.5 * len(label_idx_1)), label_number // 2)])
117
- idx_val = np.append(label_idx_0[int(0.5 * len(label_idx_0)):int(0.75 * len(
118
- label_idx_0))], label_idx_1[int(0.5 * len(label_idx_1)):int(0.75 * len(label_idx_1))])
119
- idx_test = np.append(label_idx_0[int(
120
- 0.75 * len(label_idx_0)):], label_idx_1[int(0.75 * len(label_idx_1)):])
121
-
122
- sens = idx_features_labels[sens_attr].values.astype(int)
123
- sens = torch.LongTensor(sens)
124
- train_mask = index_to_mask(features.shape[0], torch.LongTensor(idx_train))
125
- val_mask = index_to_mask(features.shape[0], torch.LongTensor(idx_val))
126
- test_mask = index_to_mask(features.shape[0], torch.LongTensor(idx_test))
127
-
128
- return adj_norm_sp, edge_index, features, labels, train_mask, val_mask, test_mask, sens
129
-
130
-
131
- def load_bail(dataset, sens_attr="WHITE", predict_attr="RECID", path="dataset/bail/", label_number=1000, test_idx=None):
132
- # print('Loading {} dataset from {}'.format(dataset, path))
133
- idx_features_labels = pd.read_csv(
134
- os.path.join(path, "{}.csv".format(dataset)))
135
- header = list(idx_features_labels.columns)
136
- header.remove(predict_attr)
137
-
138
- # build relationship
139
- if os.path.exists(f'{path}/{dataset}_edges.txt'):
140
- edges_unordered = np.genfromtxt(
141
- f'{path}/{dataset}_edges.txt').astype('int')
142
- else:
143
- edges_unordered = build_relationship(
144
- idx_features_labels[header], thresh=0.6)
145
- np.savetxt(f'{path}/{dataset}_edges.txt', edges_unordered)
146
-
147
- features = sp.csr_matrix(idx_features_labels[header], dtype=np.float32)
148
- labels = idx_features_labels[predict_attr].values
149
-
150
- idx = np.arange(features.shape[0])
151
- idx_map = {j: i for i, j in enumerate(idx)}
152
- edges = np.array(list(map(idx_map.get, edges_unordered.flatten())),
153
- dtype=int).reshape(edges_unordered.shape)
154
- adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),
155
- shape=(labels.shape[0], labels.shape[0]),
156
- dtype=np.float32)
157
-
158
- # build symmetric adjacency matrix
159
- adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)
160
- adj = adj + sp.eye(adj.shape[0])
161
- adj_norm = sys_normalized_adjacency(adj)
162
- adj_norm_sp = sparse_mx_to_torch_sparse_tensor(adj_norm)
163
-
164
- edge_index, _ = from_scipy_sparse_matrix(adj)
165
-
166
- features = torch.FloatTensor(np.array(features.todense()))
167
- labels = torch.LongTensor(labels)
168
- sens = idx_features_labels[sens_attr].values.astype(int)
169
- sens = torch.LongTensor(sens)
170
-
171
- import random
172
- random.seed(20)
173
- label_idx_0 = np.where(labels == 0)[0]
174
- label_idx_1 = np.where(labels == 1)[0]
175
- random.shuffle(label_idx_0)
176
- random.shuffle(label_idx_1)
177
- idx_train = np.append(label_idx_0[:min(int(0.5 * len(label_idx_0)), label_number // 2)],
178
- label_idx_1[:min(int(0.5 * len(label_idx_1)), label_number // 2)])
179
- idx_val = np.append(label_idx_0[int(0.5 * len(label_idx_0)):int(0.75 * len(
180
- label_idx_0))], label_idx_1[int(0.5 * len(label_idx_1)):int(0.75 * len(label_idx_1))])
181
- idx_test = np.append(label_idx_0[int(
182
- 0.75 * len(label_idx_0)):], label_idx_1[int(0.75 * len(label_idx_1)):])
183
-
184
- train_mask = index_to_mask(features.shape[0], torch.LongTensor(idx_train))
185
- val_mask = index_to_mask(features.shape[0], torch.LongTensor(idx_val))
186
- test_mask = index_to_mask(features.shape[0], torch.LongTensor(idx_test))
187
-
188
- return adj_norm_sp, edge_index, features, labels, train_mask, val_mask, test_mask, sens
189
-
190
-
191
- def load_german(dataset, sens_attr="Gender", predict_attr="GoodCustomer", path="dataset/german/", label_number=1000, test_idx=None):
192
- # print('Loading {} dataset from {}'.format(dataset, path))
193
- idx_features_labels = pd.read_csv(
194
- os.path.join(path, "{}.csv".format(dataset)))
195
- header = list(idx_features_labels.columns)
196
- header.remove(predict_attr)
197
- header.remove('OtherLoansAtStore')
198
- header.remove('PurposeOfLoan')
199
-
200
- # Sensitive Attribute
201
- idx_features_labels['Gender'][idx_features_labels['Gender']
202
- == 'Female'] = 1
203
- idx_features_labels['Gender'][idx_features_labels['Gender'] == 'Male'] = 0
204
-
205
- # build relationship
206
- if os.path.exists(f'{path}/{dataset}_edges.txt'):
207
- edges_unordered = np.genfromtxt(
208
- f'{path}/{dataset}_edges.txt').astype('int')
209
- else:
210
- edges_unordered = build_relationship(
211
- idx_features_labels[header], thresh=0.8)
212
- np.savetxt(f'{path}/{dataset}_edges.txt', edges_unordered)
213
-
214
- features = sp.csr_matrix(idx_features_labels[header], dtype=np.float32)
215
- labels = idx_features_labels[predict_attr].values
216
- labels[labels == -1] = 0
217
-
218
- idx = np.arange(features.shape[0])
219
- idx_map = {j: i for i, j in enumerate(idx)}
220
- edges = np.array(list(map(idx_map.get, edges_unordered.flatten())),
221
- dtype=int).reshape(edges_unordered.shape)
222
- adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),
223
- shape=(labels.shape[0], labels.shape[0]),
224
- dtype=np.float32)
225
-
226
- # build symmetric adjacency matrix
227
- adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)
228
- adj = adj + sp.eye(adj.shape[0])
229
-
230
- adj_norm = sys_normalized_adjacency(adj)
231
- adj_norm_sp = sparse_mx_to_torch_sparse_tensor(adj_norm)
232
-
233
- edge_index, _ = from_scipy_sparse_matrix(adj)
234
-
235
- features = torch.FloatTensor(np.array(features.todense()))
236
- labels = torch.LongTensor(labels)
237
- sens = idx_features_labels[sens_attr].values.astype(int)
238
- sens = torch.LongTensor(sens)
239
-
240
- import random
241
- random.seed(20)
242
- label_idx_0 = np.where(labels == 0)[0]
243
- label_idx_1 = np.where(labels == 1)[0]
244
- random.shuffle(label_idx_0)
245
- random.shuffle(label_idx_1)
246
- idx_train = np.append(label_idx_0[:min(int(0.5 * len(label_idx_0)), label_number // 2)],
247
- label_idx_1[:min(int(0.5 * len(label_idx_1)), label_number // 2)])
248
- idx_val = np.append(label_idx_0[int(0.5 * len(label_idx_0)):int(0.75 * len(
249
- label_idx_0))], label_idx_1[int(0.5 * len(label_idx_1)):int(0.75 * len(label_idx_1))])
250
- idx_test = np.append(label_idx_0[int(
251
- 0.75 * len(label_idx_0)):], label_idx_1[int(0.75 * len(label_idx_1)):])
252
-
253
- train_mask = index_to_mask(features.shape[0], torch.LongTensor(idx_train))
254
- val_mask = index_to_mask(features.shape[0], torch.LongTensor(idx_val))
255
- test_mask = index_to_mask(features.shape[0], torch.LongTensor(idx_test))
256
-
257
- return adj_norm_sp, edge_index, features, labels, train_mask, val_mask, test_mask, sens
258
-
259
-
260
- def get_dataset(dataname, path="./dataset"):
261
- test_idx = False
262
- if dataname == 'credit':
263
- load, label_num = load_credit, 6000
264
- dataset = 'credit'
265
- sens_attr = 'Age'
266
- predict_attr = 'NoDefaultNextMonth'
267
- elif dataname == 'bail':
268
- load, label_num = load_bail, 100
269
- dataset = 'bail'
270
- sens_attr = 'WHITE'
271
- predict_attr = 'RECID'
272
- elif dataname == 'german':
273
- load, label_num = load_german, 100
274
- dataset = 'german'
275
- sens_attr = 'Gender'
276
- predict_attr = 'GoodCustomer'
277
-
278
- adj_norm_sp, edge_index, features, labels, train_mask, val_mask, test_mask, sens = load(
279
- dataset=dataset, label_number=label_num, path=path+'/{}/'.format(dataname), sens_attr=sens_attr, predict_attr=predict_attr, test_idx=test_idx
280
- )
281
-
282
- if dataset == 'credit':
283
- sens_idx = 1
284
- elif dataset == 'bail' or dataset == 'german':
285
- sens_idx = 0
286
-
287
- x_max, x_min = torch.max(features, dim=0)[0], torch.min(features, dim=0)[0]
288
-
289
- if dataname in ['bail', 'credit']:
290
- norm_features = feature_norm(features)
291
- norm_features[:, sens_idx] = features[:, sens_idx]
292
- features = norm_features
293
-
294
- return Data(x=features, edge_index=edge_index, adj_norm_sp=adj_norm_sp, y=labels.float(), train_mask=train_mask, val_mask=val_mask, test_mask=test_mask, sens=sens), sens_idx, x_min, x_max
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/FairGB/dataset/bail.zip DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:8b72929bbb2bcdeed16098120fcf995b66eeff6ac172c159d91f0b449265f062
3
- size 2112180
 
 
 
 
annotations/annotation_130/FairGB/dataset/credit.zip DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:1d7f523eaa98af924ccb2abcbe1f24dcad46afcdac49fa605768aa915859b728
3
- size 11004361
 
 
 
 
annotations/annotation_130/FairGB/dataset/german.zip DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:7f0707c34346539f5112f56085cff82cce98154763f124aeda05207b26789648
3
- size 103864
 
 
 
 
annotations/annotation_130/FairGB/eval.py DELETED
@@ -1,56 +0,0 @@
1
- import torch
2
- import numpy as np
3
- from sklearn.metrics import f1_score, roc_auc_score
4
-
5
-
6
- def evaluate_ged3(classifier, encoder, data, pred=None):
7
- classifier.eval()
8
- encoder.eval()
9
-
10
- if pred:
11
- data.sens = pred
12
-
13
- with torch.no_grad():
14
- h = encoder(data.x, data.edge_index)
15
- output = classifier(h)
16
-
17
- accs, auc_rocs, F1s, paritys, equalitys = {}, {}, {}, {}, {}
18
-
19
- pred_val = (output[data.val_mask].squeeze() > 0).type_as(data.y)
20
- pred_test = (output[data.test_mask].squeeze() > 0).type_as(data.y)
21
-
22
- accs['val'] = pred_val.eq(
23
- data.y[data.val_mask]).sum().item() / data.val_mask.sum().item()
24
- accs['test'] = pred_test.eq(
25
- data.y[data.test_mask]).sum().item() / data.test_mask.sum().item()
26
-
27
- F1s['val'] = f1_score(data.y[data.val_mask].cpu(
28
- ).numpy(), pred_val.cpu().numpy())
29
-
30
- F1s['test'] = f1_score(data.y[data.test_mask].cpu(
31
- ).numpy(), pred_test.cpu().numpy())
32
-
33
- auc_rocs['val'] = roc_auc_score(
34
- data.y[data.val_mask].cpu().numpy(), output[data.val_mask].detach().cpu().numpy())
35
- auc_rocs['test'] = roc_auc_score(
36
- data.y[data.test_mask].cpu().numpy(), output[data.test_mask].detach().cpu().numpy())
37
-
38
- paritys['val'], equalitys['val'] = fair_metric(pred_val.cpu().numpy(), data.y[data.val_mask].cpu(
39
- ).numpy(), data.sens[data.val_mask].cpu().numpy())
40
-
41
- paritys['test'], equalitys['test'] = fair_metric(pred_test.cpu().numpy(), data.y[data.test_mask].cpu(
42
- ).numpy(), data.sens[data.test_mask].cpu().numpy())
43
-
44
- return accs, auc_rocs, F1s, paritys, equalitys
45
-
46
-
47
- def fair_metric(pred, labels, sens):
48
- idx_s0 = sens == 0
49
- idx_s1 = sens == 1
50
- idx_s0_y1 = np.bitwise_and(idx_s0, labels == 1)
51
- idx_s1_y1 = np.bitwise_and(idx_s1, labels == 1)
52
- parity = abs(sum(pred[idx_s0]) / sum(idx_s0) -
53
- sum(pred[idx_s1]) / sum(idx_s1))
54
- equality = abs(sum(pred[idx_s0_y1]) / sum(idx_s0_y1) -
55
- sum(pred[idx_s1_y1]) / sum(idx_s1_y1))
56
- return parity.item(), equality.item()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/FairGB/main.py DELETED
@@ -1,158 +0,0 @@
1
- import argparse
2
- import torch
3
- import numpy as np
4
- import torch.nn.functional as F
5
-
6
- from models import *
7
- from data_utils import get_dataset
8
- from eval import evaluate_ged3
9
- from utils import seed_everything, get_enc_cls_opt
10
- from mixup import sampling_idx_individual_dst, neighbor_sampling, get_ins_neighbor_dist, saliency_mixup
11
-
12
- EPS = 1e-6
13
-
14
- def run(data, args):
15
- acc, f1, auc_roc, parity, equality = np.zeros(args.runs), np.zeros(
16
- args.runs), np.zeros(args.runs), np.zeros(args.runs), np.zeros(args.runs)
17
-
18
- neighbor_dist_list = get_ins_neighbor_dist(data.y.size(0), data.edge_index, args.device)
19
-
20
- data = data.to(args.device)
21
- n_cls = data.y.max().int().item() + 1
22
- n_sen = data.sens.max().int().item() + 1
23
- index_list = torch.arange(len(data.y)).to(args.device)
24
- group_num_list, idx_info = [], []
25
- for i in range(n_cls):
26
- for j in range(n_sen):
27
- mask = ((data.y == i) & (data.sens == j) & data.train_mask)
28
- data_num = mask.sum()
29
- group_num_list.append(int(data_num.item()))
30
- idx_info.append(index_list[mask])
31
-
32
- encoder, classifier, optimizer_e, optimizer_c = get_enc_cls_opt(args)
33
-
34
- for count in range(args.runs):
35
- seed_everything(count + args.seed)
36
- classifier.reset_parameters()
37
- encoder.reset_parameters()
38
-
39
- best_val_tradeoff = 0
40
- for epoch in range(0, args.epochs):
41
- encoder.train()
42
- classifier.train()
43
-
44
- optimizer_c.zero_grad()
45
- optimizer_e.zero_grad()
46
-
47
- sampling_src_idx, sampling_dst_idx = sampling_idx_individual_dst(group_num_list, idx_info, args.eta)
48
- beta = torch.distributions.beta.Beta(2, 2)
49
- lam = beta.sample((len(sampling_src_idx),) ).unsqueeze(1)
50
- lam = lam.to(args.device)
51
-
52
- if epoch >= args.warmup:
53
- new_edge_index = neighbor_sampling(data.x.size(0), data.edge_index, sampling_src_idx, neighbor_dist_list)
54
- new_x = saliency_mixup(data.x, sampling_src_idx, sampling_dst_idx, lam)
55
-
56
- h = encoder(new_x, new_edge_index)
57
- output = classifier(h)
58
-
59
- add_num = output.shape[0] - data.train_mask.shape[0]
60
- new_train_mask = torch.ones(add_num, dtype=torch.bool, device=args.device)
61
- new_train_mask = torch.cat((torch.zeros(data.train_mask.shape[0], dtype=torch.bool, device=args.device), new_train_mask), dim=0)
62
-
63
- loss_src = F.binary_cross_entropy_with_logits(
64
- output[new_train_mask], data.y[sampling_src_idx].unsqueeze(1).to(args.device), reduction='none')
65
- loss_dst = F.binary_cross_entropy_with_logits(
66
- output[new_train_mask], data.y[sampling_dst_idx].unsqueeze(1).to(args.device), reduction='none')
67
-
68
- pos_grad_src = (1. - torch.exp(-loss_src).detach()) * lam
69
- pos_grad_dst = (1. - torch.exp(-loss_dst).detach()) * (1-lam)
70
- grad_count = []
71
- for i in range(n_cls):
72
- for j in range(n_sen):
73
- mask_src = (data.y[sampling_src_idx] == i) & (data.sens[sampling_src_idx] == j)
74
- mask_dst = (data.y[sampling_dst_idx] == i) & (data.sens[sampling_dst_idx] == j)
75
- grad_count.append(pos_grad_src[mask_src].sum().item() + pos_grad_dst[mask_dst].sum().item())
76
-
77
- min_grad = np.min(grad_count)
78
- group_weight_list = [float(min_grad)/(float(num) + EPS) for num in grad_count]
79
-
80
- for i in range(n_cls):
81
- for j in range(n_sen):
82
- mask_src = (data.y[sampling_src_idx] == i) & (data.sens[sampling_dst_idx] == j)
83
- mask_dst = (data.y[sampling_dst_idx] == i) & (data.sens[sampling_dst_idx] == j)
84
- loss_src[mask_src] *= group_weight_list[i*2+j]
85
- loss_dst[mask_dst] *= group_weight_list[i*2+j]
86
-
87
- loss = lam * loss_src + (1-lam) * loss_dst
88
- loss.mean().backward()
89
- else:
90
- h = encoder(data.x, data.edge_index)
91
- output = classifier(h)
92
-
93
- loss_c = F.binary_cross_entropy_with_logits(
94
- output[data.train_mask], data.y[data.train_mask].unsqueeze(1).to(args.device))
95
- loss_c.backward()
96
-
97
- optimizer_e.step()
98
- optimizer_c.step()
99
-
100
- accs, auc_rocs, F1s, tmp_parity, tmp_equality = evaluate_ged3(classifier, encoder, data)
101
-
102
- if epoch % 10 == 0:
103
- print("RUN: {}/{}, Epoch: {:04}/{:04} | Val Acc: {:.4f}, Test Acc: {:.4f}, Test AUC: {:.4f}, Test F1: {:.4f}, Test SP: {:.4f}, Test EO: {:.4f}".format(
104
- count+1, args.runs, epoch, args.epochs, accs['val'], accs['test'], auc_rocs['test'], F1s['test'], tmp_parity['test'], tmp_equality['test']
105
- ))
106
-
107
- if (auc_rocs['val'] + F1s['val'] + accs['val'] - args.alpha * (tmp_parity['val'] + tmp_equality['val']) > best_val_tradeoff):
108
- test_acc = accs['test']
109
- test_auc_roc = auc_rocs['test']
110
- test_f1 = F1s['test']
111
- test_parity, test_equality = tmp_parity['test'], tmp_equality['test']
112
-
113
- best_val_tradeoff = auc_rocs['val'] + F1s['val'] + \
114
- accs['val'] - args.alpha * (tmp_parity['val'] + tmp_equality['val'])
115
-
116
- print("\033[0;30;41m RUN: {}/{}, Epoch: {:04}/{:04} | Val Acc: {:.4f}, Test Acc: {:.4f}, Test AUC: {:.4f}, Test F1: {:.4f}, Test SP: {:.4f}, Test EO: {:.4f}\033[0m".format(
117
- count+1, args.runs, epoch, args.epochs, accs['val'], accs['test'], auc_rocs['test'], F1s['test'], tmp_parity['test'], tmp_equality['test']
118
- ))
119
-
120
- acc[count] = test_acc
121
- f1[count] = test_f1
122
- auc_roc[count] = test_auc_roc
123
- parity[count] = test_parity
124
- equality[count] = test_equality
125
-
126
- return acc, f1, auc_roc, parity, equality
127
-
128
-
129
- if __name__ == "__main__":
130
- parser = argparse.ArgumentParser()
131
- parser.add_argument('--dataset', type=str, default='german')
132
- parser.add_argument('--runs', type=int, default=10)
133
- parser.add_argument('--epochs', type=int, default=1000)
134
- parser.add_argument('--c_lr', type=float, default=0.01)
135
- parser.add_argument('--c_wd', type=float, default=0)
136
- parser.add_argument('--e_lr', type=float, default=0.01)
137
- parser.add_argument('--e_wd', type=float, default=0)
138
- parser.add_argument('--dropout', type=float, default=0.5)
139
- parser.add_argument('--hidden', type=int, default=16)
140
- parser.add_argument('--seed', type=int, default=0)
141
- parser.add_argument('--encoder', type=str, default='SAGE')
142
- parser.add_argument('--alpha', type=float, default=1)
143
- parser.add_argument('--gpu_num', type=int, default=0)
144
- parser.add_argument('--warmup', type=int, default=5)
145
- parser.add_argument('--eta', type=float, default=0.5)
146
-
147
- args = parser.parse_args()
148
- args.device = torch.device('cuda:{}'.format(args.gpu_num) if torch.cuda.is_available() else 'cpu')
149
- data, args.sens_idx, args.x_min, args.x_max = get_dataset(args.dataset)
150
- args.num_features, args.num_classes = data.x.shape[1], 1
151
-
152
- acc, f1, auc_roc, parity, equality = run(data, args)
153
- print('======' + args.dataset + args.encoder + '======')
154
- print('auc_roc: {:.2f} +- {:.2f}'.format(np.mean(auc_roc) * 100, np.std(auc_roc) * 100))
155
- print('Acc: {:.2f} +- {:.2f}'.format(np.mean(acc) * 100, np.std(acc) * 100))
156
- print('f1: {:.2f} +- {:.2f}'.format(np.mean(f1) * 100, np.std(f1) * 100))
157
- print('parity: {:.2f} +- {:.2f}'.format(np.mean(parity) * 100, np.std(parity) * 100))
158
- print('equality: {:.2f} +- {:.2f}'.format(np.mean(equality) * 100, np.std(equality) * 100))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/FairGB/mixup.py DELETED
@@ -1,220 +0,0 @@
1
- # === Appended from canonical.py ===
2
- import torch
3
- import torch.nn.functional as F
4
- import numpy as np
5
- from torch_scatter import scatter_add
6
-
7
- @torch.no_grad()
8
- def sampling_idx_individual_dst(group_num_list, idx_info, eta=0.5):
9
- """
10
- Selects counterfactual pairs for mixup based on the specified strategy (inter-class or inter-domain).
11
-
12
- Functionality:
13
- This function generates source and destination node indices for counterfactual mixup.
14
- For all training nodes (source), it selects a corresponding destination node from a
15
- different demographic group to create a pair for interpolation. The selection strategy
16
- is chosen probabilistically for the entire batch.
17
-
18
- Paper Correspondence:
19
- This function implements the first step of "Counterfactual Node Mixup (CNM)" described in Section 3.1.
20
- It selects counterfactual pairs for each training sample. The paper states:
21
- - Inter-domain: same target label (Y), different sensitive attribute (S).
22
- - Inter-class: different target label (Y), same sensitive attribute (S).
23
- The hyperparameter `eta` corresponds to `ρ` in the paper, which controls the mixup strategy.
24
-
25
- Discrepancy between Code and Paper:
26
- 1. **Terminology Mismatch**: The variable `inter` in the code has a reversed meaning compared to the paper's text.
27
- - When `inter` is `True`, the code performs `target_group_id = 2 * (1 - i) + j`. This swaps the class `i` to `1-i` while keeping the sensitive group `j` the same. This is the **inter-class** mixup as defined in the paper.
28
- - When `inter` is `False`, the code performs `target_group_id = 2 * i + (1 - j)`. This keeps the class `i` the same while swapping the sensitive group `j` to `1-j`. This is the **inter-domain** mixup as defined in the paper.
29
- 2. **Strategy Selection**: The paper describes `ρ` as a ratio, suggesting a potential mix of both strategies. This implementation makes a single probabilistic choice (`if np.random.rand() < eta`) for the entire set of samples in a given call, rather than sampling the strategy for each node individually.
30
-
31
- Implementation Details (not in paper):
32
- - `group_num_list`: A list containing the number of nodes in each of the four demographic groups (e.g., [|D_0,0|, |D_0,1|, |D_1,0|, |D_1,1|]).
33
- - `idx_info`: A list of tensors, where each tensor contains the node indices for one demographic group.
34
- - `torch.multinomial`: Used to sample destination nodes from the target group with replacement, ensuring every source node is paired.
35
- - The final sorting operation ensures that the `k`-th node in `sampling_src_idx` is correctly paired with the `k`-th node in `sampling_dst_idx`.
36
- """
37
- n_cls, n_grp = 2, 2
38
- # Concatenate all training indices to form the source indices.
39
- sampling_src_idx = torch.cat(idx_info)
40
-
41
- # Probabilistically choose between inter-class and inter-domain mixup for the whole batch.
42
- # Note the discrepancy in terminology with the paper.
43
- if np.random.rand() < eta:
44
- inter = True # Corresponds to inter-CLASS mixup in the paper (Y changes, S is same)
45
- else:
46
- inter = False # Corresponds to inter-DOMAIN mixup in the paper (Y is same, S changes)
47
-
48
- sampling_dst_idx = []
49
- # Iterate through each demographic group (class i, sensitive attribute j).
50
- for i in range(n_cls):
51
- for j in range(n_grp):
52
- if inter:
53
- # Target group has a different class (1-i) but the same sensitive attribute (j).
54
- target_group_id = 2 * (1 - i) + j
55
- else:
56
- # Target group has the same class (i) but a different sensitive attribute (1-j).
57
- target_group_id = 2 * i + (1 - j)
58
-
59
- # Uniformly sample nodes from the selected target group.
60
- prob = torch.ones(group_num_list[target_group_id]) / group_num_list[target_group_id]
61
- # Sample with replacement to create a destination partner for each source node in the current group.
62
- sampled_idx = torch.multinomial(prob, group_num_list[i * 2 + j], replacement=True)
63
- # Get the actual node indices from the target group.
64
- sampled_idx = idx_info[target_group_id][sampled_idx]
65
- sampling_dst_idx.append(sampled_idx)
66
-
67
- # Concatenate destination indices from all groups.
68
- sampling_dst_idx = torch.cat(sampling_dst_idx)
69
-
70
- # Sort source indices and apply the same ordering to destination indices to maintain correct pairing.
71
- sampling_src_idx, sorted_idx = torch.sort(sampling_src_idx)
72
- sampling_dst_idx = sampling_dst_idx[sorted_idx]
73
-
74
- return sampling_src_idx, sampling_dst_idx
75
-
76
-
77
- def saliency_mixup(x, sampling_src_idx, sampling_dst_idx, lam):
78
- """
79
- Performs linear interpolation (mixup) on the node features of counterfactual pairs.
80
-
81
- Functionality:
82
- This function takes source and destination node features and mixes them using a lambda `lam`.
83
- The resulting new nodes are appended to the original feature matrix.
84
-
85
- Paper Correspondence:
86
- This function directly implements the feature interpolation part of Equation 11 in Section 3.1:
87
- x_new = λ * x_i + (1 - λ) * x_j
88
- The label interpolation mentioned in the same equation is handled separately, likely during the loss calculation.
89
-
90
- Discrepancy between Code and Paper:
91
- - The function name `saliency_mixup` is not used in the paper. The paper refers to this as "linear interpolation" or as part of "Counterfactual Node Mixup".
92
-
93
- Implementation Details (not in paper):
94
- - `lam`: This is the interpolation ratio `λ`, which the paper states is sampled from a Beta distribution. It is expected to be provided as an input to this function.
95
- - The mixed nodes are concatenated to the original feature matrix `x`, effectively increasing the number of nodes in the graph for the current training step.
96
- """
97
- new_src = x[sampling_src_idx.to(x.device), :].clone()
98
- new_dst = x[sampling_dst_idx.to(x.device), :].clone()
99
- lam = lam.to(x.device)
100
-
101
- # Linear interpolation of features.
102
- mixed_node = lam * new_src + (1-lam) * new_dst
103
- # Append the newly generated node features to the original feature matrix.
104
- new_x = torch.cat([x, mixed_node], dim =0)
105
- return new_x
106
-
107
-
108
- @torch.no_grad()
109
- def neighbor_sampling(total_node, edge_index, sampling_src_idx, neighbor_dist_list):
110
- """
111
- Generates new edges for the augmented nodes based on an interpolated neighborhood distribution.
112
-
113
- Functionality:
114
- This function constructs the ego-networks for the newly created mixed nodes. It first samples a
115
- degree for each new node from the graph's original degree distribution. Then, it samples that
116
- many neighbors from the provided interpolated neighborhood distribution.
117
-
118
- Paper Correspondence:
119
- This function implements the "Neighborhood Mixup" procedure described in Section 3.1.
120
- It aims to create edges for the new nodes based on the interpolated neighbor distribution from Equation 12:
121
- P_N(v_new) = λ * P_N(v_i) + (1 - λ) * P_N(v_j)
122
- It also follows the paper's guideline to "sample the neighbors according to the original degree
123
- distribution" to avoid creating out-of-distribution structures.
124
-
125
- Discrepancy between Code and Paper:
126
- - The parameter `neighbor_dist_list` is ambiguously named. Based on the paper's logic, this should be the *interpolated*
127
- neighbor distribution `P_N(v_new)`, not the list of original distributions. The calling function is
128
- responsible for computing the mixup of distributions (`λ*P_N(v_i) + (1-λ)*P_N(v_j)`) and passing it here.
129
-
130
- Implementation Details (not in paper):
131
- - **Degree Sampling**: The code first samples a *degree value* for each new node from the global degree distribution. This is a practical way to implement the paper's high-level goal.
132
- - **Degree Capping**: The line `aug_degree = torch.min(aug_degree, degree[sampling_src_idx])` is a heuristic not mentioned in the paper. It caps the new node's degree to be no larger than its source node's degree, likely to prevent instability from creating nodes with excessively high degrees.
133
- - **Neighbor Sampling**: `torch.multinomial` is used to sample the actual neighbors for each new node from its mixed neighborhood distribution.
134
- - The new edges are created as `inv_edge_index` and appended to the original `edge_index`. The new nodes are indexed starting from `total_node`.
135
- """
136
- ## Exception Handling ##
137
- device = edge_index.device
138
- sampling_src_idx = sampling_src_idx.clone().to(device)
139
-
140
- # This should be the mixed neighbor distribution, P_N(v_new), computed prior to calling this function.
141
- mixed_neighbor_dist = neighbor_dist_list[sampling_src_idx]
142
-
143
- # Compute the degree of each node in the original graph.
144
- col = edge_index[1]
145
- degree = scatter_add(torch.ones_like(col), col)
146
- # Pad with zeros if some nodes have no edges.
147
- if len(degree) < total_node:
148
- degree = torch.cat([degree, degree.new_zeros(total_node-len(degree))],dim=0)
149
- train_node_mask = torch.ones_like(degree,dtype=torch.bool)
150
- # Compute the distribution of degrees across the graph.
151
- degree_dist = scatter_add(torch.ones_like(degree[train_node_mask]), degree[train_node_mask]).to(device).type(torch.float32)
152
-
153
- # Sample a degree for each augmented node from the global degree distribution.
154
- prob = degree_dist.unsqueeze(dim=0).repeat(len(sampling_src_idx),1)
155
- aug_degree = torch.multinomial(prob, 1).to(device).squeeze(dim=1) # (m)
156
- max_degree = degree.max().item() + 1
157
- # Heuristic: Cap the sampled degree at the degree of the source node.
158
- aug_degree = torch.min(aug_degree, degree[sampling_src_idx])
159
-
160
- # Sample neighbors for each new node based on its mixed neighbor distribution.
161
- # Add a small epsilon for numerical stability.
162
- new_tgt = torch.multinomial(mixed_neighbor_dist + 1e-12, max_degree)
163
- tgt_index = torch.arange(max_degree).unsqueeze(dim=0).to(device)
164
- # Select the first 'aug_degree' sampled neighbors for each new node.
165
- new_col = new_tgt[(tgt_index - aug_degree.unsqueeze(dim=1) < 0)]
166
- # Create the row indices for the new edges (the new nodes themselves).
167
- new_row = (torch.arange(len(sampling_src_idx)).to(device)+ total_node)
168
- new_row = new_row.repeat_interleave(aug_degree)
169
- # Stack to create the new edge index and append to the original.
170
- inv_edge_index = torch.stack([new_col, new_row], dim=0)
171
- new_edge_index = torch.cat([edge_index, inv_edge_index], dim=1)
172
-
173
- return new_edge_index
174
-
175
-
176
- from tqdm import tqdm
177
-
178
- @torch.no_grad()
179
- def get_ins_neighbor_dist(num_nodes, edge_index, device):
180
- """
181
- Computes the 1-hop neighbor distribution for every node in the graph.
182
-
183
- Functionality:
184
- For each node `j`, this function creates a vector representing its 1-hop neighborhood. The vector
185
- is then normalized to form a probability distribution over its neighbors.
186
-
187
- Paper Correspondence:
188
- This function computes `P_N(v_i)` for all nodes `v_i` in the graph, as described in Section 3.1
189
- around Equation 12. The paper defines `p(v_k|v_i) = 1/|N_i|` if `v_k` is a neighbor of `v_i`.
190
- This function calculates exactly that by counting connections and then normalizing by the total count (degree).
191
-
192
- Implementation Details (not in paper):
193
- - `tqdm`: A progress bar is used for better user experience, as this can be a slow operation on large graphs.
194
- - The implementation iterates through each node individually to build its distribution, which is straightforward but can be computationally expensive.
195
- - The final list of distributions is stacked into a single tensor and normalized.
196
- """
197
- ## Utilize GPU ##
198
- # edge_index = edge_index.clone().to(device)
199
- edge_index = edge_index.clone()
200
- row, col = edge_index[0], edge_index[1]
201
-
202
- # Compute neighbor distribution for each node.
203
- neighbor_dist_list = []
204
- for j in tqdm(range(num_nodes)):
205
- # Initialize a zero vector for the current node's neighbor distribution.
206
- # neighbor_dist = torch.zeros(num_nodes, dtype=torch.float32).to(device)
207
- neighbor_dist = torch.zeros(num_nodes, dtype=torch.float32)
208
-
209
- # Find all neighbors of node j.
210
- idx = row[(col==j)]
211
- # Increment the count for each neighbor. This handles multi-edges correctly.
212
- neighbor_dist[idx] = neighbor_dist[idx] + 1
213
- neighbor_dist_list.append(neighbor_dist)
214
-
215
- # Stack all distributions into a single tensor.
216
- neighbor_dist_list = torch.stack(neighbor_dist_list,dim=0).to(device)
217
- # Normalize each row by its L1 norm to get a probability distribution.
218
- neighbor_dist_list = F.normalize(neighbor_dist_list,dim=1,p=1)
219
-
220
- return neighbor_dist_list
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/FairGB/models.py DELETED
@@ -1,125 +0,0 @@
1
- import torch
2
- from torch.nn import Linear
3
- from torch.nn import Parameter
4
- import torch.nn as nn
5
- from torch_geometric.nn import GINConv, SAGEConv, GCNConv
6
-
7
-
8
- class MLP_classifier(torch.nn.Module):
9
- def __init__(self, args):
10
- super(MLP_classifier, self).__init__()
11
- self.args = args
12
-
13
- self.lin = Linear(args.hidden, args.num_classes)
14
-
15
- def clip_parameters(self):
16
- for p in self.lin.parameters():
17
- p.data.clamp_(-self.args.clip_c, self.args.clip_c)
18
-
19
- def reset_parameters(self):
20
- self.lin.reset_parameters()
21
-
22
- def forward(self, h, edge_index=None):
23
- h = self.lin(h)
24
-
25
- return h
26
-
27
-
28
- class MLP_encoder(torch.nn.Module):
29
- def __init__(self, args):
30
- super(MLP_encoder, self).__init__()
31
- self.args = args
32
-
33
- self.lin = Linear(args.num_features, args.hidden)
34
-
35
- def reset_parameters(self):
36
- self.lin.reset_parameters()
37
-
38
- def forward(self, x, edge_index=None, mask_node=None):
39
- h = self.lin(x)
40
-
41
- return h
42
-
43
-
44
- class GCN_encoder(nn.Module):
45
- def __init__(self, args):
46
- super(GCN_encoder, self).__init__()
47
- self.conv1 = GCNConv(args.num_features, args.hidden)
48
- self.transition = nn.Sequential(
49
- nn.ReLU(),
50
- nn.BatchNorm1d(args.hidden),
51
- nn.Dropout(p=args.dropout)
52
- )
53
- self.conv2 = GCNConv(args.hidden, args.hidden)
54
-
55
- def reset_parameters(self):
56
- self.conv1.reset_parameters()
57
- self.conv2.reset_parameters()
58
-
59
- def forward(self, x, edge_index, edge_weight=None):
60
- x = self.conv1(x, edge_index, edge_weight)
61
- x = self.transition(x)
62
- h = self.conv2(x, edge_index, edge_weight)
63
- return h
64
-
65
- # class GCN_encoder(nn.Module):
66
- # def __init__(self, args):
67
- # super(GCN_encoder, self).__init__()
68
- # self.conv = GCNConv(args.num_features, args.hidden)
69
-
70
- # def reset_parameters(self):
71
- # self.conv.reset_parameters()
72
-
73
- # def forward(self, x, edge_index, edge_weight=None):
74
- # h = self.conv(x, edge_index, edge_weight)
75
- # return h
76
-
77
-
78
- class GIN_encoder(nn.Module):
79
- def __init__(self, args):
80
- super(GIN_encoder, self).__init__()
81
-
82
- self.args = args
83
-
84
- self.mlp = nn.Sequential(
85
- nn.Linear(args.num_features, args.hidden),
86
- # nn.ReLU(),
87
- # nn.BatchNorm1d(args.hidden),
88
- # nn.Linear(args.hidden, args.hidden),
89
- )
90
-
91
- self.conv = GINConv(self.mlp)
92
-
93
- def reset_parameters(self):
94
- self.conv.reset_parameters()
95
-
96
- def forward(self, x, edge_index, adj_norm_sp=None):
97
- h = self.conv(x, edge_index)
98
- return h
99
-
100
-
101
- class SAGE_encoder(nn.Module):
102
- def __init__(self, args):
103
- super(SAGE_encoder, self).__init__()
104
-
105
- self.args = args
106
-
107
- self.conv1 = SAGEConv(args.num_features, args.hidden, normalize=True)
108
- self.conv1.aggr = 'mean'
109
- self.transition = nn.Sequential(
110
- nn.ReLU(),
111
- nn.BatchNorm1d(args.hidden),
112
- nn.Dropout(p=args.dropout)
113
- )
114
- self.conv2 = SAGEConv(args.hidden, args.hidden, normalize=True)
115
- self.conv2.aggr = 'mean'
116
-
117
- def reset_parameters(self):
118
- self.conv1.reset_parameters()
119
- self.conv2.reset_parameters()
120
-
121
- def forward(self, x, edge_index, edge_weight=None):
122
- x = self.conv1(x, edge_index, edge_weight)
123
- x = self.transition(x)
124
- h = self.conv2(x, edge_index, edge_weight)
125
- return h
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/FairGB/run.sh DELETED
@@ -1,8 +0,0 @@
1
- # Bail
2
- python main.py --dataset='bail' --c_lr=0.01 --e_lr=0.01 --epochs=1500 --alpha=2 --runs=10
3
-
4
- # German
5
- python main.py --dataset='german' --c_lr=0.01 --e_lr=0.01 --epochs=1500 --alpha=4 --runs=10 --eta=0.7
6
-
7
- # Credit
8
- python main.py --dataset='credit' --c_lr=0.01 --e_lr=0.01 --c_wd=0.0001 --e_wd=0.0001 --epochs=2000 --alpha=1 --runs=10
 
 
 
 
 
 
 
 
 
annotations/annotation_130/FairGB/utils.py DELETED
@@ -1,60 +0,0 @@
1
- import torch
2
- import random
3
- import numpy as np
4
- import os
5
- from models import *
6
-
7
-
8
- def seed_everything(seed=0):
9
- random.seed(seed)
10
- torch.manual_seed(seed)
11
- torch.cuda.manual_seed(seed)
12
- np.random.seed(seed)
13
- torch.backends.cudnn.allow_tf32 = False
14
-
15
- os.environ['PYTHONHASHSEED'] = str(seed)
16
- torch.backends.cudnn.deterministic = True
17
- torch.backends.cudnn.benchmark = False
18
- torch.backends.cudnn.enabled = True
19
- # torch.use_deterministic_algorithms(True)
20
-
21
-
22
- def get_enc_cls_opt(args):
23
- classifier = MLP_classifier(args).to(args.device)
24
- optimizer_c = torch.optim.Adam([
25
- dict(params=classifier.lin.parameters(), weight_decay=args.c_wd)], lr=args.c_lr)
26
-
27
- if args.encoder == 'MLP':
28
- encoder = MLP_encoder(args).to(args.device)
29
- optimizer_e = torch.optim.Adam([
30
- dict(params=encoder.lin.parameters(), weight_decay=args.e_wd)], lr=args.e_lr)
31
- elif args.encoder == 'GCN':
32
- encoder = GCN_encoder(args).to(args.device)
33
- optimizer_e = torch.optim.Adam([
34
- dict(params=encoder.conv1.parameters(), weight_decay=args.e_wd),
35
- dict(params=encoder.conv2.parameters(), weight_decay=args.e_wd)], lr=args.e_lr)
36
- elif(args.encoder == 'GIN'):
37
- encoder = GIN_encoder(args).to(args.device)
38
- optimizer_e = torch.optim.Adam([
39
- dict(params=encoder.conv.parameters(), weight_decay=args.e_wd)], lr=args.e_lr)
40
- elif(args.encoder == 'SAGE'):
41
- encoder = SAGE_encoder(args).to(args.device)
42
- optimizer_e = torch.optim.Adam([
43
- dict(params=encoder.conv1.parameters(), weight_decay=args.e_wd),
44
- dict(params=encoder.conv2.parameters(), weight_decay=args.e_wd)], lr=args.e_lr)
45
-
46
- return encoder, classifier, optimizer_e, optimizer_c
47
-
48
-
49
- def get_data_info(data, device):
50
- group_num_list, idx_info = [], []
51
- index_list = torch.arange(len(data.train_mask)).to(device)
52
- for i in range(2):
53
- for j in range(2):
54
- group_mask = ((data.y == i) & (data.sens == j) & data.train_mask)
55
- group_num_list.append(group_mask.sum().item())
56
- group_indices = index_list[group_mask]
57
- idx_info.append(group_indices)
58
-
59
- return group_num_list, idx_info
60
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/KDD24_FairGB.pdf DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:428b96c6c73b0e0fc0dcb07c40e7e3fa8f98c223f151fbb9268592b1dd72a843
3
- size 1474859
 
 
 
 
annotations/annotation_130/_runner_stderr.txt DELETED
@@ -1,2 +0,0 @@
1
- bash: cannot set terminal process group (728353): Inappropriate ioctl for device
2
- bash: no job control in this shell
 
 
 
annotations/annotation_130/_runner_stdout.txt DELETED
@@ -1,13 +0,0 @@
1
- ============================= test session starts ==============================
2
- platform linux -- Python 3.10.18, pytest-8.4.1, pluggy-1.6.0
3
- rootdir: /home/linus/code/research_code_gen/code_agent/work_dir/dataset/annotations/annotation_130/FairGB
4
- plugins: timeout-2.4.0
5
- timeout: 10.0s
6
- timeout method: signal
7
- timeout func_only: False
8
- collected 4 items
9
-
10
- test.py .... [100%]
11
-
12
- - generated xml file: /home/linus/code/research_code_gen/code_agent/work_dir/dataset/annotations/annotation_130/pytest_report/report.xml -
13
- ============================== 4 passed in 2.24s ===============================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/canonical.py DELETED
@@ -1,219 +0,0 @@
1
- import torch
2
- import torch.nn.functional as F
3
- import numpy as np
4
- from torch_scatter import scatter_add
5
-
6
- @torch.no_grad()
7
- def sampling_idx_individual_dst(group_num_list, idx_info, eta=0.5):
8
- """
9
- Selects counterfactual pairs for mixup based on the specified strategy (inter-class or inter-domain).
10
-
11
- Functionality:
12
- This function generates source and destination node indices for counterfactual mixup.
13
- For all training nodes (source), it selects a corresponding destination node from a
14
- different demographic group to create a pair for interpolation. The selection strategy
15
- is chosen probabilistically for the entire batch.
16
-
17
- Paper Correspondence:
18
- This function implements the first step of "Counterfactual Node Mixup (CNM)" described in Section 3.1.
19
- It selects counterfactual pairs for each training sample. The paper states:
20
- - Inter-domain: same target label (Y), different sensitive attribute (S).
21
- - Inter-class: different target label (Y), same sensitive attribute (S).
22
- The hyperparameter `eta` corresponds to `ρ` in the paper, which controls the mixup strategy.
23
-
24
- Discrepancy between Code and Paper:
25
- 1. **Terminology Mismatch**: The variable `inter` in the code has a reversed meaning compared to the paper's text.
26
- - When `inter` is `True`, the code performs `target_group_id = 2 * (1 - i) + j`. This swaps the class `i` to `1-i` while keeping the sensitive group `j` the same. This is the **inter-class** mixup as defined in the paper.
27
- - When `inter` is `False`, the code performs `target_group_id = 2 * i + (1 - j)`. This keeps the class `i` the same while swapping the sensitive group `j` to `1-j`. This is the **inter-domain** mixup as defined in the paper.
28
- 2. **Strategy Selection**: The paper describes `ρ` as a ratio, suggesting a potential mix of both strategies. This implementation makes a single probabilistic choice (`if np.random.rand() < eta`) for the entire set of samples in a given call, rather than sampling the strategy for each node individually.
29
-
30
- Implementation Details (not in paper):
31
- - `group_num_list`: A list containing the number of nodes in each of the four demographic groups (e.g., [|D_0,0|, |D_0,1|, |D_1,0|, |D_1,1|]).
32
- - `idx_info`: A list of tensors, where each tensor contains the node indices for one demographic group.
33
- - `torch.multinomial`: Used to sample destination nodes from the target group with replacement, ensuring every source node is paired.
34
- - The final sorting operation ensures that the `k`-th node in `sampling_src_idx` is correctly paired with the `k`-th node in `sampling_dst_idx`.
35
- """
36
- n_cls, n_grp = 2, 2
37
- # Concatenate all training indices to form the source indices.
38
- sampling_src_idx = torch.cat(idx_info)
39
-
40
- # Probabilistically choose between inter-class and inter-domain mixup for the whole batch.
41
- # Note the discrepancy in terminology with the paper.
42
- if np.random.rand() < eta:
43
- inter = True # Corresponds to inter-CLASS mixup in the paper (Y changes, S is same)
44
- else:
45
- inter = False # Corresponds to inter-DOMAIN mixup in the paper (Y is same, S changes)
46
-
47
- sampling_dst_idx = []
48
- # Iterate through each demographic group (class i, sensitive attribute j).
49
- for i in range(n_cls):
50
- for j in range(n_grp):
51
- if inter:
52
- # Target group has a different class (1-i) but the same sensitive attribute (j).
53
- target_group_id = 2 * (1 - i) + j
54
- else:
55
- # Target group has the same class (i) but a different sensitive attribute (1-j).
56
- target_group_id = 2 * i + (1 - j)
57
-
58
- # Uniformly sample nodes from the selected target group.
59
- prob = torch.ones(group_num_list[target_group_id]) / group_num_list[target_group_id]
60
- # Sample with replacement to create a destination partner for each source node in the current group.
61
- sampled_idx = torch.multinomial(prob, group_num_list[i * 2 + j], replacement=True)
62
- # Get the actual node indices from the target group.
63
- sampled_idx = idx_info[target_group_id][sampled_idx]
64
- sampling_dst_idx.append(sampled_idx)
65
-
66
- # Concatenate destination indices from all groups.
67
- sampling_dst_idx = torch.cat(sampling_dst_idx)
68
-
69
- # Sort source indices and apply the same ordering to destination indices to maintain correct pairing.
70
- sampling_src_idx, sorted_idx = torch.sort(sampling_src_idx)
71
- sampling_dst_idx = sampling_dst_idx[sorted_idx]
72
-
73
- return sampling_src_idx, sampling_dst_idx
74
-
75
-
76
- def saliency_mixup(x, sampling_src_idx, sampling_dst_idx, lam):
77
- """
78
- Performs linear interpolation (mixup) on the node features of counterfactual pairs.
79
-
80
- Functionality:
81
- This function takes source and destination node features and mixes them using a lambda `lam`.
82
- The resulting new nodes are appended to the original feature matrix.
83
-
84
- Paper Correspondence:
85
- This function directly implements the feature interpolation part of Equation 11 in Section 3.1:
86
- x_new = λ * x_i + (1 - λ) * x_j
87
- The label interpolation mentioned in the same equation is handled separately, likely during the loss calculation.
88
-
89
- Discrepancy between Code and Paper:
90
- - The function name `saliency_mixup` is not used in the paper. The paper refers to this as "linear interpolation" or as part of "Counterfactual Node Mixup".
91
-
92
- Implementation Details (not in paper):
93
- - `lam`: This is the interpolation ratio `λ`, which the paper states is sampled from a Beta distribution. It is expected to be provided as an input to this function.
94
- - The mixed nodes are concatenated to the original feature matrix `x`, effectively increasing the number of nodes in the graph for the current training step.
95
- """
96
- new_src = x[sampling_src_idx.to(x.device), :].clone()
97
- new_dst = x[sampling_dst_idx.to(x.device), :].clone()
98
- lam = lam.to(x.device)
99
-
100
- # Linear interpolation of features.
101
- mixed_node = lam * new_src + (1-lam) * new_dst
102
- # Append the newly generated node features to the original feature matrix.
103
- new_x = torch.cat([x, mixed_node], dim =0)
104
- return new_x
105
-
106
-
107
- @torch.no_grad()
108
- def neighbor_sampling(total_node, edge_index, sampling_src_idx, neighbor_dist_list):
109
- """
110
- Generates new edges for the augmented nodes based on an interpolated neighborhood distribution.
111
-
112
- Functionality:
113
- This function constructs the ego-networks for the newly created mixed nodes. It first samples a
114
- degree for each new node from the graph's original degree distribution. Then, it samples that
115
- many neighbors from the provided interpolated neighborhood distribution.
116
-
117
- Paper Correspondence:
118
- This function implements the "Neighborhood Mixup" procedure described in Section 3.1.
119
- It aims to create edges for the new nodes based on the interpolated neighbor distribution from Equation 12:
120
- P_N(v_new) = λ * P_N(v_i) + (1 - λ) * P_N(v_j)
121
- It also follows the paper's guideline to "sample the neighbors according to the original degree
122
- distribution" to avoid creating out-of-distribution structures.
123
-
124
- Discrepancy between Code and Paper:
125
- - The parameter `neighbor_dist_list` is ambiguously named. Based on the paper's logic, this should be the *interpolated*
126
- neighbor distribution `P_N(v_new)`, not the list of original distributions. The calling function is
127
- responsible for computing the mixup of distributions (`λ*P_N(v_i) + (1-λ)*P_N(v_j)`) and passing it here.
128
-
129
- Implementation Details (not in paper):
130
- - **Degree Sampling**: The code first samples a *degree value* for each new node from the global degree distribution. This is a practical way to implement the paper's high-level goal.
131
- - **Degree Capping**: The line `aug_degree = torch.min(aug_degree, degree[sampling_src_idx])` is a heuristic not mentioned in the paper. It caps the new node's degree to be no larger than its source node's degree, likely to prevent instability from creating nodes with excessively high degrees.
132
- - **Neighbor Sampling**: `torch.multinomial` is used to sample the actual neighbors for each new node from its mixed neighborhood distribution.
133
- - The new edges are created as `inv_edge_index` and appended to the original `edge_index`. The new nodes are indexed starting from `total_node`.
134
- """
135
- ## Exception Handling ##
136
- device = edge_index.device
137
- sampling_src_idx = sampling_src_idx.clone().to(device)
138
-
139
- # This should be the mixed neighbor distribution, P_N(v_new), computed prior to calling this function.
140
- mixed_neighbor_dist = neighbor_dist_list[sampling_src_idx]
141
-
142
- # Compute the degree of each node in the original graph.
143
- col = edge_index[1]
144
- degree = scatter_add(torch.ones_like(col), col)
145
- # Pad with zeros if some nodes have no edges.
146
- if len(degree) < total_node:
147
- degree = torch.cat([degree, degree.new_zeros(total_node-len(degree))],dim=0)
148
- train_node_mask = torch.ones_like(degree,dtype=torch.bool)
149
- # Compute the distribution of degrees across the graph.
150
- degree_dist = scatter_add(torch.ones_like(degree[train_node_mask]), degree[train_node_mask]).to(device).type(torch.float32)
151
-
152
- # Sample a degree for each augmented node from the global degree distribution.
153
- prob = degree_dist.unsqueeze(dim=0).repeat(len(sampling_src_idx),1)
154
- aug_degree = torch.multinomial(prob, 1).to(device).squeeze(dim=1) # (m)
155
- max_degree = degree.max().item() + 1
156
- # Heuristic: Cap the sampled degree at the degree of the source node.
157
- aug_degree = torch.min(aug_degree, degree[sampling_src_idx])
158
-
159
- # Sample neighbors for each new node based on its mixed neighbor distribution.
160
- # Add a small epsilon for numerical stability.
161
- new_tgt = torch.multinomial(mixed_neighbor_dist + 1e-12, max_degree)
162
- tgt_index = torch.arange(max_degree).unsqueeze(dim=0).to(device)
163
- # Select the first 'aug_degree' sampled neighbors for each new node.
164
- new_col = new_tgt[(tgt_index - aug_degree.unsqueeze(dim=1) < 0)]
165
- # Create the row indices for the new edges (the new nodes themselves).
166
- new_row = (torch.arange(len(sampling_src_idx)).to(device)+ total_node)
167
- new_row = new_row.repeat_interleave(aug_degree)
168
- # Stack to create the new edge index and append to the original.
169
- inv_edge_index = torch.stack([new_col, new_row], dim=0)
170
- new_edge_index = torch.cat([edge_index, inv_edge_index], dim=1)
171
-
172
- return new_edge_index
173
-
174
-
175
- from tqdm import tqdm
176
-
177
- @torch.no_grad()
178
- def get_ins_neighbor_dist(num_nodes, edge_index, device):
179
- """
180
- Computes the 1-hop neighbor distribution for every node in the graph.
181
-
182
- Functionality:
183
- For each node `j`, this function creates a vector representing its 1-hop neighborhood. The vector
184
- is then normalized to form a probability distribution over its neighbors.
185
-
186
- Paper Correspondence:
187
- This function computes `P_N(v_i)` for all nodes `v_i` in the graph, as described in Section 3.1
188
- around Equation 12. The paper defines `p(v_k|v_i) = 1/|N_i|` if `v_k` is a neighbor of `v_i`.
189
- This function calculates exactly that by counting connections and then normalizing by the total count (degree).
190
-
191
- Implementation Details (not in paper):
192
- - `tqdm`: A progress bar is used for better user experience, as this can be a slow operation on large graphs.
193
- - The implementation iterates through each node individually to build its distribution, which is straightforward but can be computationally expensive.
194
- - The final list of distributions is stacked into a single tensor and normalized.
195
- """
196
- ## Utilize GPU ##
197
- # edge_index = edge_index.clone().to(device)
198
- edge_index = edge_index.clone()
199
- row, col = edge_index[0], edge_index[1]
200
-
201
- # Compute neighbor distribution for each node.
202
- neighbor_dist_list = []
203
- for j in tqdm(range(num_nodes)):
204
- # Initialize a zero vector for the current node's neighbor distribution.
205
- # neighbor_dist = torch.zeros(num_nodes, dtype=torch.float32).to(device)
206
- neighbor_dist = torch.zeros(num_nodes, dtype=torch.float32)
207
-
208
- # Find all neighbors of node j.
209
- idx = row[(col==j)]
210
- # Increment the count for each neighbor. This handles multi-edges correctly.
211
- neighbor_dist[idx] = neighbor_dist[idx] + 1
212
- neighbor_dist_list.append(neighbor_dist)
213
-
214
- # Stack all distributions into a single tensor.
215
- neighbor_dist_list = torch.stack(neighbor_dist_list,dim=0).to(device)
216
- # Normalize each row by its L1 norm to get a probability distribution.
217
- neighbor_dist_list = F.normalize(neighbor_dist_list,dim=1,p=1)
218
-
219
- return neighbor_dist_list
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/function_info.json DELETED
@@ -1,278 +0,0 @@
1
- [
2
- {
3
- "function_name": "sampling_idx_individual_dst",
4
- "file_path": "main.py",
5
- "function_calls": [
6
- {
7
- "function_call_name": "torch.cat",
8
- "functionality": "Concatenates a sequence of tensors along a given dimension.",
9
- "input": "(tensors, dim=0)",
10
- "output": "torch.Tensor",
11
- "location_or_namespace": "torch"
12
- },
13
- {
14
- "function_call_name": "np.random.rand",
15
- "functionality": "Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).",
16
- "input": "()",
17
- "output": "float or ndarray of floats",
18
- "location_or_namespace": "numpy.random"
19
- },
20
- {
21
- "function_call_name": "range",
22
- "functionality": "Returns an immutable sequence of numbers.",
23
- "input": "(stop)",
24
- "output": "range object",
25
- "location_or_namespace": "built-in"
26
- },
27
- {
28
- "function_call_name": "torch.ones",
29
- "functionality": "Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.",
30
- "input": "(*size, **kwargs)",
31
- "output": "torch.Tensor",
32
- "location_or_namespace": "torch"
33
- },
34
- {
35
- "function_call_name": "torch.multinomial",
36
- "functionality": "Returns a tensor where each row contains num_samples indices sampled from the multinomial probability distribution located in the corresponding row of tensor input.",
37
- "input": "(input, num_samples, replacement=False, **kwargs)",
38
- "output": "torch.Tensor",
39
- "location_or_namespace": "torch"
40
- },
41
- {
42
- "function_call_name": "list.append",
43
- "functionality": "Add an item to the end of the list.",
44
- "input": "(object)",
45
- "output": "None",
46
- "location_or_namespace": "built-in"
47
- },
48
- {
49
- "function_call_name": "torch.sort",
50
- "functionality": "Sorts the elements of the input tensor along a given dimension in ascending order by value.",
51
- "input": "(input, dim=-1, descending=False, **kwargs)",
52
- "output": "A tuple of (values, indices) Tensors.",
53
- "location_or_namespace": "torch"
54
- }
55
- ]
56
- },
57
- {
58
- "function_name": "saliency_mixup",
59
- "file_path": "main.py",
60
- "function_calls": [
61
- {
62
- "function_call_name": "Tensor.to",
63
- "functionality": "Performs Tensor dtype and/or device conversion.",
64
- "input": "(*args, **kwargs)",
65
- "output": "torch.Tensor",
66
- "location_or_namespace": "torch.Tensor"
67
- },
68
- {
69
- "function_call_name": "Tensor.clone",
70
- "functionality": "Returns a copy of the tensor with the same size, data type, and device as the original.",
71
- "input": "(*, memory_format=torch.preserve_format)",
72
- "output": "torch.Tensor",
73
- "location_or_namespace": "torch.Tensor"
74
- },
75
- {
76
- "function_call_name": "torch.cat",
77
- "functionality": "Concatenates a sequence of tensors along a given dimension.",
78
- "input": "(tensors, dim=0)",
79
- "output": "torch.Tensor",
80
- "location_or_namespace": "torch"
81
- }
82
- ]
83
- },
84
- {
85
- "function_name": "neighbor_sampling",
86
- "file_path": "main.py",
87
- "function_calls": [
88
- {
89
- "function_call_name": "Tensor.clone",
90
- "functionality": "Returns a copy of the tensor with the same size, data type, and device as the original.",
91
- "input": "(*, memory_format=torch.preserve_format)",
92
- "output": "torch.Tensor",
93
- "location_or_namespace": "torch.Tensor"
94
- },
95
- {
96
- "function_call_name": "Tensor.to",
97
- "functionality": "Performs Tensor dtype and/or device conversion.",
98
- "input": "(*args, **kwargs)",
99
- "output": "torch.Tensor",
100
- "location_or_namespace": "torch.Tensor"
101
- },
102
- {
103
- "function_call_name": "scatter_add",
104
- "functionality": "Adds all values from the src tensor into out at the indices specified in the index tensor.",
105
- "input": "(src, index, dim=-1, out=None, dim_size=None)",
106
- "output": "torch.Tensor",
107
- "location_or_namespace": "torch_scatter"
108
- },
109
- {
110
- "function_call_name": "torch.ones_like",
111
- "functionality": "Returns a tensor filled with the scalar value 1, with the same size as input.",
112
- "input": "(input, **kwargs)",
113
- "output": "torch.Tensor",
114
- "location_or_namespace": "torch"
115
- },
116
- {
117
- "function_call_name": "len",
118
- "functionality": "Return the length (the number of items) of an object.",
119
- "input": "(object)",
120
- "output": "int",
121
- "location_or_namespace": "built-in"
122
- },
123
- {
124
- "function_call_name": "torch.cat",
125
- "functionality": "Concatenates a sequence of tensors along a given dimension.",
126
- "input": "(tensors, dim=0)",
127
- "output": "torch.Tensor",
128
- "location_or_namespace": "torch"
129
- },
130
- {
131
- "function_call_name": "Tensor.new_zeros",
132
- "functionality": "Returns a Tensor of specified size filled with 0, with the same dtype and device as the original tensor.",
133
- "input": "(size, **kwargs)",
134
- "output": "torch.Tensor",
135
- "location_or_namespace": "torch.Tensor"
136
- },
137
- {
138
- "function_call_name": "Tensor.type",
139
- "functionality": "Casts this tensor to a new type.",
140
- "input": "(dtype=None, non_blocking=False, **kwargs)",
141
- "output": "torch.Tensor",
142
- "location_or_namespace": "torch.Tensor"
143
- },
144
- {
145
- "function_call_name": "Tensor.unsqueeze",
146
- "functionality": "Returns a new tensor with a dimension of size one inserted at the specified position.",
147
- "input": "(dim)",
148
- "output": "torch.Tensor",
149
- "location_or_namespace": "torch.Tensor"
150
- },
151
- {
152
- "function_call_name": "Tensor.repeat",
153
- "functionality": "Repeats this tensor along the specified dimensions.",
154
- "input": "(*sizes)",
155
- "output": "torch.Tensor",
156
- "location_or_namespace": "torch.Tensor"
157
- },
158
- {
159
- "function_call_name": "torch.multinomial",
160
- "functionality": "Returns a tensor where each row contains num_samples indices sampled from the multinomial probability distribution located in the corresponding row of tensor input.",
161
- "input": "(input, num_samples, replacement=False, **kwargs)",
162
- "output": "torch.Tensor",
163
- "location_or_namespace": "torch"
164
- },
165
- {
166
- "function_call_name": "Tensor.squeeze",
167
- "functionality": "Returns a tensor with all specified dimensions of input of size 1 removed.",
168
- "input": "(dim=None)",
169
- "output": "torch.Tensor",
170
- "location_or_namespace": "torch.Tensor"
171
- },
172
- {
173
- "function_call_name": "Tensor.max",
174
- "functionality": "Returns the maximum value of all elements in the input tensor.",
175
- "input": "(dim=None, keepdim=False)",
176
- "output": "torch.Tensor",
177
- "location_or_namespace": "torch.Tensor"
178
- },
179
- {
180
- "function_call_name": "Tensor.item",
181
- "functionality": "Returns the value of this tensor as a standard Python number. This only works for tensors with one element.",
182
- "input": "()",
183
- "output": "number",
184
- "location_or_namespace": "torch.Tensor"
185
- },
186
- {
187
- "function_call_name": "torch.min",
188
- "functionality": "Returns the minimum value of all elements in the input tensor or performs element-wise min.",
189
- "input": "(input) or (input, other)",
190
- "output": "torch.Tensor",
191
- "location_or_namespace": "torch"
192
- },
193
- {
194
- "function_call_name": "torch.arange",
195
- "functionality": "Returns a 1-D tensor of size ceil((end - start) / step) with values from the interval [start, end).",
196
- "input": "(start=0, end, step=1, **kwargs)",
197
- "output": "torch.Tensor",
198
- "location_or_namespace": "torch"
199
- },
200
- {
201
- "function_call_name": "Tensor.repeat_interleave",
202
- "functionality": "Repeat elements of a tensor.",
203
- "input": "(repeats, dim=None, *, output_size=None)",
204
- "output": "torch.Tensor",
205
- "location_or_namespace": "torch.Tensor"
206
- },
207
- {
208
- "function_call_name": "torch.stack",
209
- "functionality": "Concatenates a sequence of tensors along a new dimension.",
210
- "input": "(tensors, dim=0, *, out=None)",
211
- "output": "torch.Tensor",
212
- "location_or_namespace": "torch"
213
- }
214
- ]
215
- },
216
- {
217
- "function_name": "get_ins_neighbor_dist",
218
- "file_path": "main.py",
219
- "function_calls": [
220
- {
221
- "function_call_name": "Tensor.clone",
222
- "functionality": "Returns a copy of the tensor with the same size, data type, and device as the original.",
223
- "input": "(*, memory_format=torch.preserve_format)",
224
- "output": "torch.Tensor",
225
- "location_or_namespace": "torch.Tensor"
226
- },
227
- {
228
- "function_call_name": "tqdm",
229
- "functionality": "Creates a smart progress bar for loops.",
230
- "input": "(iterable=None, ...)",
231
- "output": "iterator",
232
- "location_or_namespace": "tqdm"
233
- },
234
- {
235
- "function_call_name": "range",
236
- "functionality": "Returns an immutable sequence of numbers.",
237
- "input": "(stop)",
238
- "output": "range object",
239
- "location_or_namespace": "built-in"
240
- },
241
- {
242
- "function_call_name": "torch.zeros",
243
- "functionality": "Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.",
244
- "input": "(*size, **kwargs)",
245
- "output": "torch.Tensor",
246
- "location_or_namespace": "torch"
247
- },
248
- {
249
- "function_call_name": "list.append",
250
- "functionality": "Add an item to the end of the list.",
251
- "input": "(object)",
252
- "output": "None",
253
- "location_or_namespace": "built-in"
254
- },
255
- {
256
- "function_call_name": "torch.stack",
257
- "functionality": "Concatenates a sequence of tensors along a new dimension.",
258
- "input": "(tensors, dim=0, *, out=None)",
259
- "output": "torch.Tensor",
260
- "location_or_namespace": "torch"
261
- },
262
- {
263
- "function_call_name": "Tensor.to",
264
- "functionality": "Performs Tensor dtype and/or device conversion.",
265
- "input": "(*args, **kwargs)",
266
- "output": "torch.Tensor",
267
- "location_or_namespace": "torch.Tensor"
268
- },
269
- {
270
- "function_call_name": "F.normalize",
271
- "functionality": "Performs L_p normalization of a tensor.",
272
- "input": "(input, p=2.0, dim=1, eps=1e-12, out=None)",
273
- "output": "torch.Tensor",
274
- "location_or_namespace": "torch.nn.functional"
275
- }
276
- ]
277
- }
278
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/instruction.txt DELETED
@@ -1,59 +0,0 @@
1
- # Code Generation Instruction: FairGB Counterfactual Augmentation
2
-
3
- ## Goal:
4
- To implement the core components of the data augmentation strategy from the paper "Rethinking Fair Graph Neural Networks from Re-balancing". This involves generating counterfactual nodes through mixup of features and neighborhood structures to create a more balanced graph for training fair GNNs. The implementation should follow the algorithmic details described in Section 3.1, "Counterfactual Node Mixup".
5
-
6
- ---
7
-
8
- ### **Instruction 1: Counterfactual Pair Sampling**
9
-
10
- * **Functionality Description:** Implement a function that selects counterfactual pairs for data augmentation. For a given set of training nodes, this function probabilistically chooses one of two strategies for the entire batch: 1) **inter-class mixup**, where each source node is paired with a destination node of a different class but the same sensitive attribute, or 2) **inter-domain mixup**, where the destination node has the same class but a different sensitive attribute. This corresponds to the counterfactual pair selection step in Section 3.1 of the paper.
11
- * **Expected Function Name:** `sampling_idx_individual_dst`
12
- * **Input:**
13
- * `group_num_list` (list[int]): A list containing the number of nodes in each demographic group.
14
- * `idx_info` (list[torch.Tensor]): A list where each element is a `torch.Tensor` containing the node indices belonging to a specific demographic group.
15
- * `eta` (float): A probability threshold (corresponding to `ρ` in the paper) to decide between the inter-class and inter-domain sampling strategy.
16
- * **Output:**
17
- * A tuple containing two `torch.Tensor`s:
18
- * `source_indices` (torch.Tensor): A 1D tensor of shape `[N]` containing all source node indices, sorted.
19
- * `destination_indices` (torch.Tensor): A 1D tensor of shape `[N]` containing destination node indices, where each index corresponds to the source index at the same position.
20
-
21
- ---
22
-
23
- ### **Instruction 2: Node Feature Mixup**
24
-
25
- * **Functionality Description:** Implement a function to perform linear interpolation (mixup) on the features of the counterfactual node pairs generated in the previous step. The function should take the original node feature tensor, the source and destination indices, and interpolation ratios, and produce a new feature tensor with the mixed-up node features appended. This directly implements the feature interpolation part of Equation 11 from Section 3.1 of the paper.
26
- * **Expected Function Name:** `saliency_mixup`
27
- * **Input:**
28
- * `node_features` (torch.Tensor): The original node feature tensor of shape `[num_nodes, feature_dim]`.
29
- * `source_indices` (torch.Tensor): A 1D tensor of shape `[M]` containing source node indices for the mixup.
30
- * `destination_indices` (torch.Tensor): A 1D tensor of shape `[M]` containing destination node indices, paired with the source indices.
31
- * `interpolation_ratios` (torch.Tensor): A tensor of shape `[M, 1]` or `[M]` containing the interpolation weights (λ) for combining features.
32
- * **Output:**
33
- * `augmented_node_features` (torch.Tensor): The new feature tensor of shape `[num_nodes + M, feature_dim]`, containing the original features with the newly created mixed features appended.
34
-
35
- ---
36
-
37
- ### **Instruction 3: Neighborhood Structure Mixup and Sampling**
38
-
39
- * **Functionality Description:** Implement a function to generate new edges for the augmented nodes created via feature mixup. This function should first determine the degree for each new node by sampling from the original graph's degree distribution. Then, for each new node, it should sample that many neighbors from its corresponding interpolated neighborhood distribution. This process, described as "Neighborhood Mixup" in Section 3.1 and related to Equation 12, constructs the local graph structure (ego-network) for the new nodes.
40
- * **Expected Function Name:** `neighbor_sampling`
41
- * **Input:**
42
- * `num_original_nodes` (int): The total number of nodes in the graph before augmentation.
43
- * `edge_index` (torch.Tensor): The edge list of the original graph, with a shape of `[2, num_edges]`.
44
- * `source_node_indices` (torch.Tensor): A 1D tensor of shape `[M]` representing the source nodes used to create the augmented nodes.
45
- * `interpolated_neighbor_distributions` (torch.Tensor): A tensor of shape `[M, num_original_nodes]`, where each row is the interpolated probability distribution over all original nodes for a corresponding new node.
46
- * **Output:**
47
- * `augmented_edge_index` (torch.Tensor): The new edge index tensor of shape `[2, num_edges + new_edges]`, containing the original edges plus the newly generated edges for the augmented nodes.
48
-
49
- ---
50
-
51
- ### **Instruction 4: Node-wise Neighbor Distribution Calculation**
52
-
53
- * **Functionality Description:** Implement a utility function that computes the 1-hop neighbor distribution for every node in a given graph. For each node, the function should produce a probability distribution over all other nodes, where the probability of a node is proportional to the number of edges connecting to it. This corresponds to calculating `P_N(v_i)` for all nodes `v_i`, as mentioned in Section 3.1 of the paper, which is a prerequisite for neighborhood mixup.
54
- * **Expected Function Name:** `get_ins_neighbor_dist`
55
- * **Input:**
56
- * `num_nodes` (int): The total number of nodes in the graph.
57
- * `edge_index` (torch.Tensor): The edge list of the graph, with a shape of `[2, num_edges]`.
58
- * **Output:**
59
- * `neighbor_distributions` (torch.Tensor): A tensor of shape `[num_nodes, num_nodes]`, where row `i` is a probability distribution representing the 1-hop neighborhood of node `i`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/latex.txt DELETED
@@ -1,74 +0,0 @@
1
- \subsection{Counterfactual Node Mixup}
2
-
3
- Recently, the incorporation of causal learning techniques into GNNs has ignited a plethora of groundbreaking studies \cite{jiang2023survey, guo2023towards, fan2022debiasing, sui2022causal}. This is attributed to the fact that addressing trustworthiness concerns is more effectively achieved by capturing the inherent causality in the underlying data, as opposed to merely relying on superficial correlations. In this work, we present a causal view of the union of the graph data generation and the GNNs' prediction process as a Structure Causal Model \cite{peters2017elements} (as shown in \figref{fig:analysis}(a)). We illustrate the causal relationships among six variables in the node classification problem: unobservable causal variable $C$, unobservable sensitive (bias) variable $S$, observable node attributes $\mathbf{X}$, observable topology $\mathbf{A}$, node embedding $\mathbf{Z}$, and ground-truth label $\mathbf{Y}$. In the graph data generation process, $C\rightarrow\mathbf{X}\leftarrow S$ and $C\rightarrow\mathbf{A}\leftarrow S$ demonstrate that two variables (causal variable $C$ and sensitive variable $S$) construct two components of observable contextual subgraphs (node attributes $\mathbf{X}$ and topology $\mathbf{A}$), which is different from \emph{i.i.d.} data only consider attributes. $\mathbf{X}\rightarrow\mathbf{Z}\leftarrow\mathbf{A}$ and $\mathbf{Z}\rightarrow\mathbf{Y}$ indicate existing GNNs produce representations and predictions based on observable contextual subgraphs. $C\dashleftrightarrow S$ denotes the spurious correlation between $C$ and $S$.
4
-
5
- Inspired by \citet{fan2022debiasing}, we analyze the SCM according to $d$-connection theory \cite{pearl2009causality} (\emph{two variables are dependent if they are connected by at least one unblocked path}). Thus we can find three paths between sensitive variable $S$ and group-truth label $\mathbf{Y}$:
6
- \begin{itemize}[leftmargin=*]
7
- \item $S\rightarrow\mathbf{X}\rightarrow\mathbf{Z}\rightarrow\mathbf{Y}$ and $S\rightarrow\mathbf{A}\rightarrow\mathbf{Z}\rightarrow\mathbf{Y}$: Because the existing graph neural networks make prediction for a node based on its contextual subgraph, sensitive variable $S$ will influence the final prediction not only through node attributes $\mathbf{X}$ but also topology $\mathbf{A}$ \cite{li2024gslb}. This makes fairness in graph machine learning more complex compared to other modalities (\emph{e.g.}, images and languages). As a result, if we want to sever all unblocked paths between $S$ and $\mathbf{Y}$, we need to debias both $\mathbf{X}$ and $\mathbf{A}$.
8
-
9
- \item $S\dashleftrightarrow C\rightarrow\mathbf{Y}$: we want to sever the connection between $S$ and $C$, so we utilize inter-domain and inter-class mixup. Intuitively, we interpolate samples with the same target label but different sensitive attributes in inter-domain mixup, and then the model can focus on class-specific information and learn domain invariant features. Besides, we also interpolate samples with the same sensitive attribute and different target labels in inter-class mixup, which can smooth the decision surface and alleviate the dependency on bias information.
10
- \end{itemize}
11
-
12
- Furthermore, we can also explain counterfactual mixup is equivalent to re-sampling methods. As shown in \figref{fig:analysis}(b), we observe that the original group distribution is imbalanced, which could lead to unfairness during training. However, in the inter-domain mixup, counterfactual samples can balance the bias distribution within each class (\emph{i.e.}, $P(Y=y|S=i)=P(Y=y|S=j), \forall i,j\in S$). In the inter-class mixup, counterfactual samples can make the bias distribution consistent within each class (\emph{i.e.}, $P(S=s|Y=i)=P(S=s|Y=j), \forall i,j\in Y$). The following theorem builds a theoretical analysis of the debiasing capability of counterfactual mixup.
13
-
14
- \begin{figure}
15
- \centering
16
- \begin{minipage}{0.32\linewidth}
17
- \centering
18
- \includegraphics[width=0.96\linewidth]{pic/casual.pdf}
19
- \caption*{(a) Causal View.}
20
- \end{minipage}
21
- \begin{minipage}{0.66\linewidth}
22
- \centering
23
- \includegraphics[width=0.93\linewidth]{pic/distribution.pdf}
24
- \caption*{(b) Group Distribution.}
25
- \end{minipage}
26
- \caption{Analysis of the proposed FairGB. (a) SCM of the union of the graph data generation and the existing GNNs' prediction process. (b) Statistics of the occurrences of samples in each group per epoch in the German dataset. "IC" denotes inter-class mixup, "ID" denotes inter-domain mixup.}
27
- \label{fig:analysis}
28
- \end{figure}
29
-
30
- \begin{theorem}
31
- Let $Y$ and $S$ be target labels and sensitive attributes. Balanced and consistent bias distribution within each class can make $S$ statistically independent from $Y$, i.e., $P(Y=y|S=s)=P(Y=y)$.
32
- \label{the:1}
33
- \end{theorem}
34
- \begin{proof}
35
- \ding{182}\textbf{Inter-domain mixup}: If $P(Y=y|S=i)=P(Y=y|S=j), \forall i,j\in S$, given $s\in S$ then:
36
- \begin{equation}
37
- P(Y=y)=\sum_{s\in S}P(Y=y|S=s)P(S=s),
38
- \label{equ:1}
39
- \end{equation}
40
- Based on the premise condition, we can rewrite \equref{equ:1} as:
41
- \begin{equation}
42
- P(Y=y)=P(Y=y|S=s)\sum_{s'\in S}P(S=s')=P(Y=y|S=s)
43
- \end{equation}
44
- \ding{183}\textbf{Inter-class mixup}: If $P(S=s|Y=i)=P(S=s|Y=j), \forall i,j\in Y$, given $y\in Y$ then:
45
- \begin{equation}
46
- P(S=s)=\sum_{y\in Y}P(S=s|Y=y)P(Y=y)
47
- \label{equ:2}
48
- \end{equation}
49
- Based on the premise condition, we can rewrite \equref{equ:2} as:
50
- \begin{equation}
51
- P(S=s)=P(S=s|Y=y)\sum_{y'\in Y}P(Y=y')=P(S=s|Y=y)
52
- \end{equation}
53
- Subsequently, using Bayesian probability we can get:
54
- \begin{align}
55
- P(Y=y|S=s)&=\frac{P(S=s|Y=y)P(Y=y)}{P(S=s)}\\
56
- &=\frac{P(S=s)P(Y=y)}{P(S=s)}\\
57
- &=P(Y=y)
58
- \end{align}
59
- Thus, we have completed the proof of \theref{the:1}.
60
- \end{proof}
61
-
62
- Although some literature provided similar theoretical analysis based on the statistical view \cite{qraitem2023bias, teney2023selective}, they did not conduct a detailed analysis of the debiasing mechanism of balanced and consistent bias distribution within each class.
63
-
64
- Next, we are going to introduce the detailed process of counterfactual node mixup. Specifically, for each training node $v_i$, we randomly select a node $v_j$ that has the same target label and a different sensitive attribute with $v_i$ ($y_i=y_j, s_i\neq s_j$) as an inter-domain counterexample. In the same way, we randomly select a node $v_j$ that has a different target label and the same sensitive attribute with $v_i$ ($y_i\neq y_j, s_i=s_j$) as an inter-class counterexample. Here, we introduce a hyper-parameter $\eta$, which is responsible for controlling the ratio between two kinds of counterexamples. Then we perform linear interpolation on the node attributes:
65
- \begin{equation}
66
- \mathbf{x}_{mix}=\lambda \mathbf{x}_i + (1-\lambda)\mathbf{x}_j,\ y_{mix}=\lambda y_i + (1-\lambda)y_j,
67
- \label{equ:node}
68
- \end{equation}
69
- where $\lambda\in [0,1]$ is the interpolation ratio that is sampled from a Beta distribution. After generating new node attributes, we need to insert these nodes into the original graph. According to the analysis above, we also perform mixup on the contextual subgraph structure. We define the neighbor distribution of node $v_i$ as $p_\mathcal{N}(v_i)$ where $p(v_k|v_i)=\frac{1}{|\mathcal{N}_i|}$, if $\mathbf{A}_{ik}=1$, and $p(v_k|v_i)=0$ otherwise. Then we directly interpolate the neighbor distribution of counterfactual pairs using the same $\lambda$:
70
- \begin{equation}
71
- p_\mathcal{N}(v_{mix})=\lambda p_\mathcal{N}(v_i) + (1-\lambda)p_\mathcal{N}(v_j),
72
- \label{equ:neighbor}
73
- \end{equation}
74
- Thus we can obtain newly generated unbiased ego-networks. However, these ego-networks have very dense structures, which could violate the original degree distribution and result in the phenomenon of out-of-distribution \cite{tang2020investigating, liu2021tail}. Therefore, we sample the neighbors according to the original degree distribution and inject newly generated unbiased ego-networks into the original graph to construct an augmented graph $\mathcal{G}_{aug}$.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/pytest_report/report.xml DELETED
@@ -1 +0,0 @@
1
- <?xml version="1.0" encoding="utf-8"?><testsuites name="pytest tests"><testsuite name="pytest" errors="0" failures="0" skipped="0" tests="4" time="2.242" timestamp="2025-08-31T13:40:23.455153-05:00" hostname="linus-ms7e59"><testcase classname="test.TestFairGBAugmentation" name="test_get_ins_neighbor_dist" time="0.013" /><testcase classname="test.TestFairGBAugmentation" name="test_neighbor_sampling" time="1.278" /><testcase classname="test.TestFairGBAugmentation" name="test_saliency_mixup" time="0.001" /><testcase classname="test.TestFairGBAugmentation" name="test_sampling_idx_individual_dst" time="0.002" /></testsuite></testsuites>
 
 
annotations/annotation_130/requirements.txt DELETED
@@ -1,59 +0,0 @@
1
- aiohappyeyeballs==2.6.1
2
- aiohttp==3.12.15
3
- aiosignal==1.4.0
4
- async-timeout==5.0.1
5
- attrs==25.3.0
6
- certifi==2025.8.3
7
- charset-normalizer==3.4.3
8
- filelock==3.13.1
9
- frozenlist==1.7.0
10
- fsspec==2024.6.1
11
- idna==3.10
12
- Jinja2==3.1.4
13
- joblib==1.5.1
14
- MarkupSafe==2.1.5
15
- mpmath==1.3.0
16
- multidict==6.6.4
17
- networkx==3.3
18
- numpy==2.1.2
19
- nvidia-cublas-cu12==12.9.1.4
20
- nvidia-cuda-cupti-cu12==12.9.79
21
- nvidia-cuda-nvrtc-cu12==12.9.86
22
- nvidia-cuda-runtime-cu12==12.9.79
23
- nvidia-cudnn-cu12==9.10.2.21
24
- nvidia-cufft-cu12==11.4.1.4
25
- nvidia-cufile-cu12==1.14.1.1
26
- nvidia-curand-cu12==10.3.10.19
27
- nvidia-cusolver-cu12==11.7.5.82
28
- nvidia-cusparse-cu12==12.5.10.65
29
- nvidia-cusparselt-cu12==0.7.1
30
- nvidia-nccl-cu12==2.27.3
31
- nvidia-nvjitlink-cu12==12.9.86
32
- nvidia-nvtx-cu12==12.9.79
33
- pandas==2.3.2
34
- pillow==11.0.0
35
- propcache==0.3.2
36
- psutil==7.0.0
37
- pyg-lib==0.4.0+pt28cu129
38
- pyparsing==3.2.3
39
- python-dateutil==2.9.0.post0
40
- pytz==2025.2
41
- requests==2.32.5
42
- scikit-learn==1.7.1
43
- scipy==1.15.3
44
- six==1.17.0
45
- sympy==1.13.3
46
- threadpoolctl==3.6.0
47
- torch==2.8.0+cu129
48
- torch-geometric==2.6.1
49
- torch_cluster==1.6.3+pt28cu129
50
- torch_scatter==2.1.2+pt28cu129
51
- torch_sparse==0.6.18+pt28cu129
52
- torch_spline_conv==1.2.2+pt28cu129
53
- torchvision==0.23.0+cu129
54
- tqdm==4.67.1
55
- triton==3.4.0
56
- typing_extensions==4.12.2
57
- tzdata==2025.2
58
- urllib3==2.5.0
59
- yarl==1.20.1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/test.py DELETED
@@ -1,154 +0,0 @@
1
- import unittest
2
- import torch
3
- import numpy as np
4
- import os
5
- import random
6
-
7
- # Assume the canonical code is in a file named `canonical.py`
8
- # and the generated code is in a file named `generated.py`
9
- from canonical import get_ins_neighbor_dist as canonical_get_ins_neighbor_dist
10
- from canonical import sampling_idx_individual_dst as canonical_sampling_idx_individual_dst
11
- from canonical import saliency_mixup as canonical_saliency_mixup
12
- from canonical import neighbor_sampling as canonical_neighbor_sampling
13
-
14
- from mixup import get_ins_neighbor_dist as generated_get_ins_neighbor_dist
15
- from mixup import sampling_idx_individual_dst as generated_sampling_idx_individual_dst
16
- from mixup import saliency_mixup as generated_saliency_mixup
17
- from mixup import neighbor_sampling as generated_neighbor_sampling
18
-
19
-
20
- def set_seed(seed=42):
21
- """Sets the seed for reproducibility for random, os, numpy, and torch."""
22
- random.seed(seed)
23
- os.environ['PYTHONHASHSEED'] = str(seed)
24
- np.random.seed(seed)
25
- torch.manual_seed(seed)
26
- if torch.cuda.is_available():
27
- torch.cuda.manual_seed(seed)
28
- torch.cuda.manual_seed_all(seed)
29
- # The following two lines are crucial for deterministic results on CUDA.
30
- torch.backends.cudnn.deterministic = True
31
- torch.backends.cudnn.benchmark = False
32
-
33
- class TestFairGBAugmentation(unittest.TestCase):
34
-
35
- def setUp(self):
36
- """Set up common variables and representative data for tests."""
37
- self.device = torch.device('cpu')
38
- self.num_nodes = 10
39
- self.feature_dim = 8
40
- self.num_edges = 15
41
-
42
- # Create sample node features and edge index
43
- self.node_features = torch.randn(self.num_nodes, self.feature_dim, device=self.device)
44
- self.edge_index = torch.randint(0, self.num_nodes, (2, self.num_edges), device=self.device)
45
-
46
- # Create sample demographic group information
47
- # Groups: (cls=0, sen=0), (cls=0, sen=1), (cls=1, sen=0), (cls=1, sen=1)
48
- self.idx_info = [
49
- torch.tensor([0, 1], device=self.device),
50
- torch.tensor([2, 3, 4], device=self.device),
51
- torch.tensor([5], device=self.device),
52
- torch.tensor([6, 7, 8, 9], device=self.device)
53
- ]
54
- self.group_num_list = [len(group) for group in self.idx_info]
55
-
56
- # Ensure total nodes match the setup
57
- self.assertEqual(sum(self.group_num_list), self.num_nodes)
58
-
59
- def test_get_ins_neighbor_dist(self):
60
- """
61
- Tests the functional equivalence of get_ins_neighbor_dist.
62
- This function is deterministic.
63
- """
64
- # Execute canonical function
65
- canonical_output = canonical_get_ins_neighbor_dist(self.num_nodes, self.edge_index, self.device)
66
-
67
- # Execute generated function
68
- generated_output = generated_get_ins_neighbor_dist(self.num_nodes, self.edge_index, self.device)
69
-
70
- # Assertions
71
- self.assertIsInstance(generated_output, torch.Tensor)
72
- self.assertEqual(canonical_output.shape, generated_output.shape)
73
- torch.testing.assert_close(canonical_output, generated_output,
74
- msg="get_ins_neighbor_dist outputs do not match.")
75
-
76
- def test_sampling_idx_individual_dst(self):
77
- """
78
- Tests the functional equivalence of sampling_idx_individual_dst.
79
- This function involves randomness, so seeding is critical.
80
- Two cases are tested for the two sampling strategies.
81
- """
82
- # Case 1: Force inter-class sampling (eta > 1.0)
83
- set_seed(42)
84
- canonical_src_1, canonical_dst_1 = canonical_sampling_idx_individual_dst(self.group_num_list, self.idx_info, eta=1.1)
85
-
86
- set_seed(42)
87
- generated_src_1, generated_dst_1 = generated_sampling_idx_individual_dst(self.group_num_list, self.idx_info, eta=1.1)
88
-
89
- self.assertTrue(torch.equal(canonical_src_1, generated_src_1), "Source indices do not match for inter-class sampling.")
90
- self.assertTrue(torch.equal(canonical_dst_1, generated_dst_1), "Destination indices do not match for inter-class sampling.")
91
-
92
- # Case 2: Force inter-domain sampling (eta < 0.0)
93
- set_seed(43)
94
- canonical_src_2, canonical_dst_2 = canonical_sampling_idx_individual_dst(self.group_num_list, self.idx_info, eta=-0.1)
95
-
96
- set_seed(43)
97
- generated_src_2, generated_dst_2 = generated_sampling_idx_individual_dst(self.group_num_list, self.idx_info, eta=-0.1)
98
-
99
- self.assertTrue(torch.equal(canonical_src_2, generated_src_2), "Source indices do not match for inter-domain sampling.")
100
- self.assertTrue(torch.equal(canonical_dst_2, generated_dst_2), "Destination indices do not match for inter-domain sampling.")
101
-
102
- def test_saliency_mixup(self):
103
- """
104
- Tests the functional equivalence of saliency_mixup.
105
- This function is deterministic.
106
- """
107
- # Prepare inputs for the function
108
- src_idx = torch.tensor([0, 2, 5], device=self.device)
109
- dst_idx = torch.tensor([1, 4, 8], device=self.device)
110
- lam = torch.rand(len(src_idx), 1, device=self.device)
111
-
112
- # Execute canonical function
113
- canonical_output = canonical_saliency_mixup(self.node_features.clone(), src_idx, dst_idx, lam)
114
-
115
- # Execute generated function
116
- generated_output = generated_saliency_mixup(self.node_features.clone(), src_idx, dst_idx, lam)
117
-
118
- # Assertions
119
- self.assertIsInstance(generated_output, torch.Tensor)
120
- self.assertEqual(canonical_output.shape, generated_output.shape)
121
- torch.testing.assert_close(canonical_output, generated_output,
122
- msg="saliency_mixup outputs do not match.")
123
-
124
- def test_neighbor_sampling(self):
125
- """
126
- Tests the functional equivalence of neighbor_sampling.
127
- This function involves randomness, so seeding is critical.
128
- """
129
- # Prepare inputs for the function
130
- source_indices = torch.tensor([0, 1, 2, 3], device=self.device)
131
-
132
- # Simulate an interpolated neighbor distribution
133
- set_seed(42)
134
- dist1 = torch.rand(self.num_nodes, self.num_nodes, device=self.device)
135
- dist1 = torch.nn.functional.normalize(dist1, p=1, dim=1)
136
-
137
- # Execute canonical function
138
- set_seed(42)
139
- canonical_output = canonical_neighbor_sampling(self.num_nodes, self.edge_index.clone(), source_indices, dist1)
140
-
141
- # Execute generated function
142
- set_seed(42)
143
- generated_output = generated_neighbor_sampling(self.num_nodes, self.edge_index.clone(), source_indices, dist1)
144
-
145
- # Assertions
146
- self.assertIsInstance(generated_output, torch.Tensor)
147
- self.assertEqual(canonical_output.shape, generated_output.shape)
148
- # Sorting edges to ensure comparison is robust to potential ordering differences, though seeding should prevent this.
149
- canonical_sorted, _ = torch.sort(canonical_output, dim=1)
150
- generated_sorted, _ = torch.sort(generated_output, dim=1)
151
- self.assertTrue(torch.equal(canonical_sorted, generated_sorted), "neighbor_sampling outputs do not match.")
152
-
153
- if __name__ == '__main__':
154
- unittest.main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
annotations/annotation_130/test.sh DELETED
@@ -1,28 +0,0 @@
1
- #!/bin/bash
2
- eval "$(conda shell.bash hook)"
3
- conda activate test_common1
4
-
5
- # Get the directory where this script is located
6
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
7
-
8
- # Define the target directory (adjust if needed)
9
- TARGET_DIR="${SCRIPT_DIR}/FairGB/"
10
-
11
- # Ensure the target directory exists
12
- mkdir -p "${TARGET_DIR}"
13
-
14
- # Copy required files to target directory
15
- cp "${SCRIPT_DIR}/canonical.py" "${TARGET_DIR}/."
16
- cp "${SCRIPT_DIR}/test.py" "${TARGET_DIR}/."
17
-
18
- # Change to target directory
19
- cd "${TARGET_DIR}" || exit 1
20
-
21
- # Run tests with pytest
22
- PYTHONPATH="${TARGET_DIR}" pytest --timeout=10 test.py \
23
- --junitxml="${SCRIPT_DIR}/pytest_report/report.xml"
24
-
25
- # Clean up copied files
26
- rm -f "${TARGET_DIR}/canonical.py"
27
- rm -f "${TARGET_DIR}/test.py"
28
-