pyG edge_index矩阵 转 普通邻接矩阵,COO稀疏矩阵,包含同质图和异质图

搜这个转化实在难找,在此记录一下!

**pyG的edge_index 转 COO

同质图**


import torch_geometric
torch_geometric.utils.to_scipy_sparse_matrix(data.edge_index)

异质图

import numpy as np
# 假如异质图size:N*M
from scipy.sparse import coo_matrix
row = (hetedata['节点1','边', '节点2'].edge_index)[0]
col = (hetedata['节点1','边', '节点2'].edge_index)[1]
value = torch.ones(hetedata['节点1','边', '节点2'].num_edges)
adj = coo_matrix((value, (row, col)), shape=(hetedata['节点1'].num_nodes, hetedata['节点2'].num_nodes))

下面是pytorch版本

edge_shape= torch.zeros((N,M)).shape
value = torch.ones(hetedata['节点1','边', '节点2'].num_edges))
adj = torch.sparse_coo_tensor(hetedata['节点1','边', '节点2'].edge_index,value,edge_shape)

**pyG的edge_index 转 coo 再转普通矩阵

python
adj = adj.toarray()
pytorch
adj = adj.to_dense() 
  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个使用Pytorch Geometric (PyG)库训练卷积网络(GCN)进行骨骼识别的代码示例: ```python import torch import torch.nn.functional as F from torch_geometric.datasets import Human36M from torch_geometric.nn import GCNConv # 加载数据集 train_dataset = Human36M(root='/path/to/dataset', train=True) test_dataset = Human36M(root='/path/to/dataset', train=False) # 定义卷积网络模型 class GCN(torch.nn.Module): def __init__(self): super(GCN, self).__init__() self.conv1 = GCNConv(54, 128) # 第一层GCN卷积 self.conv2 = GCNConv(128, 128) # 第二层GCN卷积 self.fc1 = torch.nn.Linear(128, 64) # 全连接层 self.fc2 = torch.nn.Linear(64, 32) # 全连接层 self.fc3 = torch.nn.Linear(32, 17) # 全连接层 def forward(self, x, edge_index): # x: 特征向量 # edge_index: 邻接矩阵 x = F.relu(self.conv1(x, edge_index)) # GCN卷积层1 x = F.relu(self.conv2(x, edge_index)) # GCN卷积层2 x = F.relu(self.fc1(x)) # 全连接层1 x = F.relu(self.fc2(x)) # 全连接层2 x = self.fc3(x) # 全连接层3, 输出17维向量 return x # 实例化模型 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = GCN().to(device) # 定义损失函数和优化器 criterion = torch.nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001) # 训练模型 model.train() for epoch in range(50): train_loss = 0.0 for batch in train_dataset: x, edge_index, y = batch.x.to(device), batch.edge_index.to(device), batch.y.to(device) optimizer.zero_grad() out = model(x, edge_index) loss = criterion(out, y) loss.backward() optimizer.step() train_loss += loss.item() * batch.num_graphs train_loss /= len(train_dataset) print('Epoch: {:03d}, Train Loss: {:.7f}'.format(epoch, train_loss)) # 测试模型 model.eval() test_loss = 0.0 for batch in test_dataset: x, edge_index, y = batch.x.to(device), batch.edge_index.to(device), batch.y.to(device) out = model(x, edge_index) loss = criterion(out, y) test_loss += loss.item() * batch.num_graphs test_loss /= len(test_dataset) print('Test Loss: {:.7f}'.format(test_loss)) ``` 在这个示例中,我们使用了Human3.6M数据集进行骨骼识别。该数据集包含了大量的人体骨骼姿态数据,每个姿态由17个关键点组成。我们使用GCN对每个关键点进行分类,输出17维向量,每一维代表一个关键点的分类得分。我们使用均方误差(MSE)作为损失函数,使用Adam优化器进行优化。在训练过程中,我们使用了50个epoch进行训练,每个epoch中遍历整个训练集。在测试过程中,我们仅仅计算了测试集上的损失,没有进行预测。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值