Skip to content

Commit

Permalink
Fix edge_insensitive homophily measure (#4152)
Browse files Browse the repository at this point in the history
* Fix torch_geometric/utils/homophily.py: mean -> sum & div_by_c-1

* Fix torch_geometric/utils/homophily: edge_homophily -> h_k

* Fix torch_geometric/utils/homophily.py: batch mode

* fix test

Co-authored-by: Matthias Fey <matthias.fey@tu-dortmund.de>
  • Loading branch information
jinjh0123 and rusty1s authored Mar 10, 2022
1 parent f4443f1 commit e493a68
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
4 changes: 2 additions & 2 deletions test/utils/test_homophily.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ def test_homophily():
assert homophily(edge_index, y, batch, method).tolist() == [1., 0.]

method = 'edge_insensitive'
assert pytest.approx(homophily(edge_index, y, method=method)) == 0.0999999
assert pytest.approx(homophily(adj, y, method=method)) == 0.0999999
assert pytest.approx(homophily(edge_index, y, method=method)) == 0.1999999
assert pytest.approx(homophily(adj, y, method=method)) == 0.1999999
assert homophily(edge_index, y, batch, method).tolist() == [0., 0.]
6 changes: 4 additions & 2 deletions torch_geometric/utils/homophily.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def homophily(edge_index: Adj, y: Tensor, batch: OptTensor = None,
and size of each class:
.. math::
\frac{1}{C} \sum_{k=1}^{C} \max \left(0, h_k - \frac{|\mathcal{C}_k|}
\frac{1}{C-1} \sum_{k=1}^{C} \max \left(0, h_k - \frac{|\mathcal{C}_k|}
{|\mathcal{V}|} \right),
where :math:`C` denotes the number of classes, :math:`|\mathcal{C}_k|`
Expand Down Expand Up @@ -93,6 +93,7 @@ def homophily(edge_index: Adj, y: Tensor, batch: OptTensor = None,
elif method == 'edge_insensitive':
assert y.dim() == 1
num_classes = int(y.max()) + 1
assert num_classes >= 2
batch = torch.zeros_like(y) if batch is None else batch
num_nodes = degree(batch, dtype=torch.int64)
num_graphs = num_nodes.numel()
Expand All @@ -105,7 +106,8 @@ def homophily(edge_index: Adj, y: Tensor, batch: OptTensor = None,
counts = counts.view(num_graphs, num_classes)
proportions = counts / num_nodes.view(-1, 1)

out = (h - proportions).clamp_(min=0).mean(dim=-1)
out = (h - proportions).clamp_(min=0).sum(dim=-1)
out /= num_classes - 1
return out if out.numel() > 1 else float(out)

else:
Expand Down

0 comments on commit e493a68

Please sign in to comment.