Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何正确地重塑张量?_Python_Reshape_Tensor - Fatal编程技术网

Python 如何正确地重塑张量?

Python 如何正确地重塑张量?,python,reshape,tensor,Python,Reshape,Tensor,我试图使用pytorch geometric实现经典GCN模型的规范化邻接矩阵,如下所示,代码取自文档 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 impo

我试图使用pytorch geometric实现经典GCN模型的规范化邻接矩阵,如下所示,代码取自文档

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()
这个张量的输出是
torch.Size([500])

如何获得(50,50)的输出?
任何帮助都将不胜感激

我想您会感到困惑,因为PyTorch Geometric使用了邻接矩阵的压缩或稀疏表示。 我是PyTorch的新手,但以下内容将满足您的需求:

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)