-
Notifications
You must be signed in to change notification settings - Fork 1
/
MakeGraph.py
72 lines (47 loc) · 1.57 KB
/
MakeGraph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import networkx as nx
import numpy as np
import torch
from torch_geometric.data import Data
from sklearn.preprocessing import LabelEncoder
import dgl
import torch.nn as nn
import torch
from torch_geometric.nn import knn_graph
from torch_geometric.utils import add_self_loops
from sklearn.neighbors import NearestNeighbors
import numpy as np
def Makegraph(matrix):
num_patients, num_features = matrix.shape
# print( num_patients, num_features)
src_nodes, dst_nodes = [], []
for i in range(0,num_patients):
for j in range(0, num_features):
src_nodes.append(i)
dst_nodes.append(j)
g = dgl.heterograph({
('patient', 'feature', 'patient'): (src_nodes, dst_nodes)
})
edge_features = torch.tensor([matrix[i, j] for i, j in zip(src_nodes, dst_nodes)], dtype=torch.float)
g.edges[('patient', 'feature', 'patient')].data['weight'] = edge_features
# print(g)
# g = dgl.to_homogeneous(g)
# g = dgl.add_self_loop(g)
return g
def MakegraphH(matrix):
g = dgl.DGLGraph()
g.add_nodes(matrix.shape[0])
# g.ndata['feat'] = features
# Find K nearest neighbors for each row
knn = NearestNeighbors(n_neighbors=1)
knn.fit(matrix.numpy())
_, indices = knn.kneighbors(matrix.numpy())
# Add edges to the graph based on KNN
for i in range(matrix.shape[0]):
g.add_edges(i, indices[i])
g = dgl.add_self_loop(g)
return g
def MakegraphHT(matrix):
# Find K nearest neighbors
edge_index = knn_graph(matrix, k=1, loop=True)
graph = Data(x=matrix, edge_index=edge_index)
return graph