-
Notifications
You must be signed in to change notification settings - Fork 11
/
utils.py
51 lines (35 loc) · 1.59 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import torch
import networkx as nx
import numpy as np
import pandas as pd
# In[ ]:
def create_Graphs_with_attributes(edgelist_filepath,attributes_filepath):
graph=nx.read_edgelist(edgelist_filepath,nodetype=int)
attributes=pd.read_csv(attributes_filepath,index_col=['node'])
att_values = {a:{'role':b[0],'community':b[1]} for a,b in enumerate(attributes.values)}
nx.set_node_attributes(graph,att_values)
return graph
# In[ ]:
def create_train_test(graph):
X_train,Y_train,X_test,Y_test=[],[],[],[],[]
for node, data in graph.nodes(data=True):
if data['role'] in ['Administrator','Instructor']:
X_train.append(node)
Y_train.append(data['role']=='Administrator')
elif data['role'] =='Member':
X_test.append(node)
Y_test.append(data['community']=='Administrator')
return np.asarray(X_train),np.asarray(Y_train),np.asarray(X_test),np.asarray(Y_test)
def create_features(graph): # create input features, concatenation of identity matrix and shortest paths to targets
A = nx.to_numpy_matrix(graph)
X_1 = torch.eye(A.shape[0]) # identity matrix
X_2 = torch.zeros((A.shape[0], 2)) # shortest path to the targets as 2nd input feature
node_distance_instructor = nx.shortest_path_length(graph, target=33)
node_distance_administrator = nx.shortest_path_length(graph, target=0)
for node in graph.nodes():
X_2[node][0] = node_distance_administrator[node]
X_2[node][1] = node_distance_instructor[node]
return torch.cat((X_1,X_2),dim=1)