• 定义无向加权图,并使用Pytorch_geometric实现图卷积


    首先定义无向边并定义边的权重

    1. import torch
    2. import torch.nn as nn
    3. from torch_geometric.nn import GCNConv
    4. import torch.nn.functional as F
    5. from torch_geometric.data import Data
    6. a = torch.LongTensor([0, 0, 1, 1, 2, 2, 3, 4])
    7. b= torch.LongTensor([0, 1, 2, 3, 1, 5, 1, 4])
    8. num_A = 5
    9. # 让b重新编号
    10. b = b+num_A
    11. # [源节点,目标节点]
    12. first_c = torch.cat([a, b], dim=-1)
    13. # [目标节点,源节点]
    14. second_c = torch.cat([b, a], dim=-1)
    15. # 拼接变为双向边
    16. edge_index = torch.stack([first_c, second_c], dim=0)
    17. # 因为双向边,把权重的维度要和边的个数匹配
    18. rat = [0.5, 0.8, 1.0, 0.9, 0.7, 0.6,0.2,0.4]
    19. ratings = torch.tensor(rat+rat, dtype=torch.float)
    20. # 定义图
    21. # edge_weight是权重特征,每条边有一个值,即[1,3]
    22. # 如果想要为每条边定义多个特征,例如[[1,2],[2,3]]可以使用edge_attr
    23. graph_data = Data(x=None, edge_index=edge_index,edge_weight=ratings)
    24. print(graph_data.is_undirected())

     最后使用图卷积

    1. class GraphConvNet(nn.Module):
    2. def __init__(self, graph_data):
    3. super(GraphConvNet, self).__init__()
    4. self.A_embeddings = nn.Embedding(5, 20)
    5. self.B_embeddings = nn.Embedding(6, 20)
    6. # 定义图卷积层
    7. self.conv1 = GCNConv(20, 20 // 2)
    8. self.conv2 = GCNConv(20 // 2, 20)
    9. self.norm = torch.nn.BatchNorm1d(20 // 2)
    10. self.data = graph_data
    11. self.data.x = (torch.cat([self.A_embeddings.weight, self.B_embeddings.weight], dim=0))
    12. def forward(self):
    13. x, edge_index,edge_weight = self.data.x, self.data.edge_index,self.data.edge_weight
    14. x = self.conv1(x, edge_index,edge_weight.view(-1))
    15. x = self.norm(x)
    16. x = torch.relu(x)
    17. x = F.dropout(x)
    18. x = self.conv2(x, edge_index,edge_weight)
    19. A_embedded = x[:5]
    20. B_embedded = x[5:]
    21. return A_embedded, B_embedded
    22. gcnmodel = GraphConvNet(graph_data)
    23. A_emb,B_emb = gcnmodel.forward()

  • 相关阅读:
    【C++】STL各容器对比
    leetcode 2520 统计能整除数字的位数
    工具配置-如何在NextCloud私有云盘安装的olnyOffice插件中添加中文字体支持实践操作...
    C++ 之二叉搜索树
    多页面开发
    [题]当天是该年的第几天? #switch的小用法
    积分商城运营成功的7个关键要素
    Linux NetCore下Pdf转图片 内存溢出
    iOS runtime
    基于费舍尔判别分析的故障与诊断(lunwen+文献综述+翻译及原文+MATLAB程序)
  • 原文地址:https://blog.csdn.net/zhangxiaohuiNO1/article/details/134326063