examples.py 2.37 KB
Newer Older
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
1
import dgl
2
import numpy as np
3
from ged import graph_edit_distance
4

5
6
src1 = [0, 1, 2, 3, 4, 5]
dst1 = [1, 2, 3, 4, 5, 6]
7

8
9
src2 = [0, 1, 3, 4, 5]
dst2 = [1, 2, 4, 5, 6]
10
11
12
13
14
15
16


G1 = dgl.DGLGraph((src1, dst1))
G2 = dgl.DGLGraph((src2, dst2))


# Exact edit distance with astar search
17
18
19
20
21
22
23
24
distance, node_mapping, edge_mapping = graph_edit_distance(
    G1, G1, algorithm="astar"
)
print(distance)  # 0.0
distance, node_mapping, edge_mapping = graph_edit_distance(
    G1, G2, algorithm="astar"
)
print(distance)  # 1.0
25
26

# With user-input cost matrices
27
28
29
node_substitution_cost = np.empty((G1.num_nodes(), G2.num_nodes()))
G1_node_deletion_cost = np.empty(G1.num_nodes())
G2_node_insertion_cost = np.empty(G2.num_nodes())
30

31
32
33
edge_substitution_cost = np.empty((G1.num_edges(), G2.num_edges()))
G1_edge_deletion_cost = np.empty(G1.num_edges())
G2_edge_insertion_cost = np.empty(G2.num_edges())
34
35

# Node substitution cost of 0 when node-ids are same, else 1
36
node_substitution_cost.fill(1.0)
37
38
for i in range(G1.num_nodes()):
    for j in range(G2.num_nodes()):
39
40
        node_substitution_cost[i, j] = 0.0

41
# Node insertion/deletion cost of 1
42
43
G1_node_deletion_cost.fill(1.0)
G2_node_insertion_cost.fill(1.0)
44
45

# Edge substitution cost of 0
46
edge_substitution_cost.fill(0.0)
47
48

# Edge insertion/deletion cost of 0.5
49
50
G1_edge_deletion_cost.fill(0.5)
G2_edge_insertion_cost.fill(0.5)
51

52
53
54
55
56
57
58
59
60
61
62
distance, node_mapping, edge_mapping = graph_edit_distance(
    G1,
    G2,
    node_substitution_cost,
    edge_substitution_cost,
    G1_node_deletion_cost,
    G2_node_insertion_cost,
    G1_edge_deletion_cost,
    G2_edge_insertion_cost,
    algorithm="astar",
)
63

64
print(distance)  # 0.5
65
66
67


# Approximate edit distance with beam search, it is more than or equal to the exact edit distance
68
69
70
71
distance, node_mapping, edge_mapping = graph_edit_distance(
    G1, G2, algorithm="beam", max_beam_size=2
)
print(distance)  # 3.0
72
73

# Approximate edit distance with bipartite heuristic, it is more than or equal to the exact edit distance
74
75
76
77
78
79
distance, node_mapping, edge_mapping = graph_edit_distance(
    G1, G2, algorithm="bipartite"
)
print(
    distance
)  # 9.0, can be different as multiple solutions possible for the intermediate LAP used in this approximation
80
81
82


# Approximate edit distance with hausdorff heuristic, it is less than or equal to the exact edit distance
83
84
85
86
distance, node_mapping, edge_mapping = graph_edit_distance(
    G1, G2, algorithm="hausdorff"
)
print(distance)  # 0.0