examples.py 2.43 KB
Newer Older
1
import numpy as np
2
from ged import graph_edit_distance
3

4
import dgl
5

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

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


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


# Exact edit distance with astar search
18
19
20
21
22
23
24
25
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
26
27

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

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

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

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

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

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

53
54
55
56
57
58
59
60
61
62
63
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",
)
64

65
print(distance)  # 0.5
66
67
68


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

# Approximate edit distance with bipartite heuristic, it is more than or equal to the exact edit distance
75
76
77
78
79
80
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
81
82
83


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