TinaTz
TinaTz

Reputation: 311

How to correctly reshape a Tensor?

I am trying to implement the normalized adjacent matrix of classical GCN model using pytorch geometric as below, the code is taken from the documentation

import torch
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_self_loops, degree
import torch
from torch_geometric.data import Data
from torch_geometric.utils import erdos_renyi_graph
edge_index = erdos_renyi_graph(50, edge_prob=0.2)
x = torch.eye(50, 50)
data = Data(edge_index=edge_index, x=x,)

edge_index, _ = add_self_loops(edge_index, num_nodes=data.x.size(0))
row, col = edge_index
deg = degree(col, x.size(0), dtype=x.dtype)
deg_inv_sqrt = deg.pow(-0.5)
norm = deg_inv_sqrt[row] * deg_inv_sqrt[col]
print(norm.size()

the output of this tensor is torch.Size([500])

How can I get the output of (50,50)? Any help will be appreciated

Upvotes: 2

Views: 445

Answers (1)

user11634
user11634

Reputation: 306

I think you are confused because PyTorch Geometric uses a compressed or sparse representation of the adjacency matrix. I am a newbie in PyTorch, but the following will give you what you want:

import torch
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_self_loops, degree
from torch_geometric.data import Data
from torch_geometric.utils import erdos_renyi_graph
from torch_geometric.utils import to_dense_adj

edge_index = erdos_renyi_graph(5, edge_prob=0.3)
x = torch.eye(5, 5)
data = Data(edge_index=edge_index, x=x)

edge_index, _ = add_self_loops(edge_index, num_nodes=data.x.size(0))
row, col = edge_index
# build adjacency matrix
# from sparse to dense representation
adj = to_dense_adj(edge_index)[0]
deg = degree(col, x.size(0), dtype=x.dtype)
deg_inv_sqrt = deg.pow(-0.5)
norm = deg_inv_sqrt[row] * deg_inv_sqrt[col]
# build "normalized" adjacency matrix
normalized_adj = adj * torch.ger(deg_inv_sqrt,deg_inv_sqrt)
print(normalized_adj)

Upvotes: 1

Related Questions