GAT学习:PyG实现GAT(图注意力神经网络)网络(一)

2024-02-01 08:18

本文主要是介绍GAT学习:PyG实现GAT(图注意力神经网络)网络(一),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

PyG实现GAT网络

  • 预备知识
  • 代码分析
    • 完整代码
    • GAL层

注意!!!:本文的实现方法为笔者使用pyg的数据结构实现的,效果并不是最佳效果,pyg内部有封装好的GAT函数,使用pyg封装函数的方法请跳转下面,链接中文章的效果是可以达到论文效果的:
GAT学习:PyG实现GAT(使用PyG封装好的GATConv函数)(三)

目前PyG的教程几乎都是教怎么实现GCN的,但没找到GAT的PyG的实现,基本都是Pytorch实现。Paper需要,学习了GAT,为了保证和GCN用同一框架实现,所以用PyG实现了GAT,这里记录下来,用PyG搭建了GAT网络。

预备知识

1.GAT的原理移步这里向往的GAT,介绍的很详细。
2.PyG的基本操作移步这几篇:
GCN学习:Pytorch-Geometric教程(一)
GCN学习:Pytorch-Geometric教程(二)
GCN学习:用PyG实现自定义layers的GCN网络及训练(五)

代码分析

完整代码

import torch
import math
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_self_loops,degree
from torch_geometric.datasets import Planetoid
import ssl
import torch.nn.functional as Fclass GAL(MessagePassing):def __init__(self,in_features,out_featrues):super(GAL,self).__init__(aggr='add')self.a = torch.nn.Parameter(torch.zeros(size=(2*out_featrues, 1)))torch.nn.init.xavier_uniform_(self.a.data, gain=1.414)  # 初始化# 定义leakyrelu激活函数self.leakyrelu = torch.nn.LeakyReLU()self.linear=torch.nn.Linear(in_features,out_featrues)def forward(self,x,edge_index):x=self.linear(x)N=x.size()[0]row,col=edge_indexa_input = torch.cat([x[row], x[col]], dim=1)print('a_input.size',a_input.size())# [N, N, 1] => [N, N] 图注意力的相关系数(未归一化)temp=torch.mm(a_input,self.a).squeeze()print('temp.size',temp.size())e = self.leakyrelu(temp)print('e',e)print('e.size', e.size())#e_all为同一个节点与其全部邻居的计算的分数的和,用于计算归一化softmaxe_all=torch.zeros(x.size()[0])count = 0for i in col:e_all[i]+=e[count]count=count+1print('e_all',e_all)for i in range(len(e)):e[i]=math.exp(e[i])/math.exp(e_all[col[i]])print('attention',e)print('attention.size',e.size())return self.propagate(edge_index,x=x,norm=e)def message(self, x_j, norm):print('x_j:', x_j)print('x_j.size', x_j.size())print('norm', norm)print('norm.size', norm.size())print('norm.view.size', norm.view(-1, 1).size())return norm.view(-1, 1) * x_jssl._create_default_https_context = ssl._create_unverified_context
dataset = Planetoid(root='Cora', name='Cora')
x=dataset[0].x
edge_index=dataset[0].edge_indexclass Net(torch.nn.Module):def __init__(self):super(Net, self).__init__()self.gal = GAL(dataset.num_node_features,16)def forward(self, data):x, edge_index = data.x, data.edge_indexx = F.dropout(x, training=self.training)x = self.gal(x, edge_index)print('x_gal',x.size())return F.log_softmax(x, dim=1)model=Net()
data=dataset[0]
out=Net()(data)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
model.train()
for epoch in range(1):optimizer.zero_grad()out = model(data)loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])loss.backward()optimizer.step()
model.eval()
_, pred = model(data).max(dim=1)
correct = int(pred[data.test_mask].eq(data.y[data.test_mask]).sum().item())
acc = correct/int(data.test_mask.sum())
print('Accuracy:{:.4f}'.format(acc))
>>>Accuracy:0.3880

GAL层

GAL层的写法思路参考GCN学习:用PyG实现自定义layers的GCN网络及训练(五)从而可以实现自定义网络层。所以核心内容还是编写init forward message函数。
在这里插入图片描述
在这里插入图片描述在这里插入图片描述

GAL层要实现的工作:
1.进行特征映射
2.计算所有 e e eij
3.计算所有 a l p h a alpha alphaij
4.加权求和

class GAL(MessagePassing):def __init__(in_features,out_featrues):#进行加权求和super(GAL,self).__init__(aggr='add')#定义attention参数aself.a = torch.nn.Parameter(torch.zeros(size=(2*out_featrues, 1)))torch.nn.init.xavier_uniform_(self.a.data, gain=1.414)  # 初始化# 定义leakyrelu激活函数self.leakyrelu = torch.nn.LeakyReLU()self.linear=torch.nn.Linear(in_features,out_featrues)def forward(self,x,edge_index):#特征映射x=self.linear(x)N=x.size()[0]col,row=edge_index#将相邻接点的特征拼接,然后计算e值a_input = torch.cat([x[row], x[col]], dim=1)print('a_input.size',a_input.size())#将规模压缩到一维temp=torch.mm(a_input,self.a).squeeze()print('temp.size',temp.size())e = self.leakyrelu(temp)print('e',e)print('e.size', e.size())#e_all为同一个节点与其全部邻居的计算的分数的和,用于计算归一化softmaxe_all=torch.zeros(x.size()[0])count = 0for i in col:e_all[i]+=e[count]count=count+1print('e_all',e_all)#计算alpha值for i in range(len(e)):e[i]=math.exp(e[i])/math.exp(e_all[col[i]])print('attention',e)print('attention.size',e.size())#传递信息return self.propagate(edge_index,x=x,norm=e)def message(self, x_j, norm):print('x_j:', x_j)print('x_j.size', x_j.size())print('norm', norm)print('norm.size', norm.size())print('norm.view.size', norm.view(-1, 1).size())#计算求和项return norm.view(-1, 1) * x_j
>>>a_input.size torch.Size([10556, 32])
temp.size torch.Size([10556])
e tensor([-0.0023, -0.0004, -0.0010,  ..., -0.0054, -0.0048, -0.0023],grad_fn=<LeakyReluBackward0>)
e.size torch.Size([10556])
e_all tensor([-0.0037,  0.7354,  0.1100,  ..., -0.0025,  0.0254, -0.0182],grad_fn=<CopySlices>)
attention tensor([1.0014, 1.0033, 1.0027,  ..., 1.0130, 1.0135, 1.0161],grad_fn=<CopySlices>)
attention.size torch.Size([10556])
x_j: tensor([[-0.0411,  0.0475, -0.0020,  ...,  0.1014,  0.1919,  0.0331],[-0.0411,  0.0475, -0.0020,  ...,  0.1014,  0.1919,  0.0331],[-0.0411,  0.0475, -0.0020,  ...,  0.1014,  0.1919,  0.0331],...,[-0.1486, -0.1743, -0.1428,  ...,  0.1968,  0.0718, -0.0176],[-0.1486, -0.1743, -0.1428,  ...,  0.1968,  0.0718, -0.0176],[-0.1486, -0.1743, -0.1428,  ...,  0.1968,  0.0718, -0.0176]],grad_fn=<IndexSelectBackward>)
x_j.size torch.Size([10556, 16])
norm tensor([1.0014, 1.0033, 1.0027,  ..., 1.0130, 1.0135, 1.0161],grad_fn=<CopySlices>)
norm.size torch.Size([10556])
norm.view.size torch.Size([10556, 1])
x_gal torch.Size([2708, 16])
a_input.size torch.Size([10556, 32])
temp.size torch.Size([10556])
e tensor([-0.0016, -0.0020, -0.0010,  ...,  0.2144,  0.0202, -0.0003],grad_fn=<LeakyReluBackward0>)
e.size torch.Size([10556])
e_all tensor([-0.0046,  0.1969,  0.4509,  ...,  0.1620, -0.0042,  0.3253],grad_fn=<CopySlices>)
attention tensor([1.0030, 1.0026, 1.0036,  ..., 0.8951, 0.7370, 0.7221],grad_fn=<CopySlices>)
attention.size torch.Size([10556])
x_j: tensor([[-0.1055, -0.0221,  0.0717,  ...,  0.0453,  0.0534,  0.0031],[-0.1055, -0.0221,  0.0717,  ...,  0.0453,  0.0534,  0.0031],[-0.1055, -0.0221,  0.0717,  ...,  0.0453,  0.0534,  0.0031],...,[ 0.0421,  0.0349, -0.0459,  ...,  0.1171,  0.0008,  0.0766],[ 0.0421,  0.0349, -0.0459,  ...,  0.1171,  0.0008,  0.0766],[ 0.0421,  0.0349, -0.0459,  ...,  0.1171,  0.0008,  0.0766]],grad_fn=<IndexSelectBackward>)
x_j.size torch.Size([10556, 16])
norm tensor([1.0030, 1.0026, 1.0036,  ..., 0.8951, 0.7370, 0.7221],grad_fn=<CopySlices>)
norm.size torch.Size([10556])
norm.view.size torch.Size([10556, 1])
x_gal torch.Size([2708, 16])
a_input.size torch.Size([10556, 32])
temp.size torch.Size([10556])
e tensor([ 0.2280,  0.2321, -0.0004,  ...,  0.1363,  0.3448,  0.0414],grad_fn=<LeakyReluBackward0>)
e.size torch.Size([10556])
e_all tensor([ 0.4597, -0.0024,  0.2359,  ...,  0.0669,  0.2952,  0.5938],grad_fn=<CopySlices>)
attention tensor([0.7932, 0.7964, 0.6312,  ..., 0.6329, 0.7796, 0.5756],grad_fn=<CopySlices>)
attention.size torch.Size([10556])
x_j: tensor([[-0.0510,  0.0875,  0.1096,  ..., -0.1464, -0.0774, -0.0326],[-0.0510,  0.0875,  0.1096,  ..., -0.1464, -0.0774, -0.0326],[-0.0510,  0.0875,  0.1096,  ..., -0.1464, -0.0774, -0.0326],...,[ 0.0554,  0.0655, -0.0448,  ..., -0.0251, -0.0492, -0.1602],[ 0.0554,  0.0655, -0.0448,  ..., -0.0251, -0.0492, -0.1602],[ 0.0554,  0.0655, -0.0448,  ..., -0.0251, -0.0492, -0.1602]],grad_fn=<IndexSelectBackward>)
x_j.size torch.Size([10556, 16])
norm tensor([0.7932, 0.7964, 0.6312,  ..., 0.6329, 0.7796, 0.5756],grad_fn=<CopySlices>)
norm.size torch.Size([10556])
norm.view.size torch.Size([10556, 1])

这篇关于GAT学习:PyG实现GAT(图注意力神经网络)网络(一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/666652

相关文章

Java实现优雅日期处理的方案详解

《Java实现优雅日期处理的方案详解》在我们的日常工作中,需要经常处理各种格式,各种类似的的日期或者时间,下面我们就来看看如何使用java处理这样的日期问题吧,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言一、日期的坑1.1 日期格式化陷阱1.2 时区转换二、优雅方案的进阶之路2.1 线程安全重构2

Android实现两台手机屏幕共享和远程控制功能

《Android实现两台手机屏幕共享和远程控制功能》在远程协助、在线教学、技术支持等多种场景下,实时获得另一部移动设备的屏幕画面,并对其进行操作,具有极高的应用价值,本项目旨在实现两台Android手... 目录一、项目概述二、相关知识2.1 MediaProjection API2.2 Socket 网络

使用Python实现图像LBP特征提取的操作方法

《使用Python实现图像LBP特征提取的操作方法》LBP特征叫做局部二值模式,常用于纹理特征提取,并在纹理分类中具有较强的区分能力,本文给大家介绍了如何使用Python实现图像LBP特征提取的操作方... 目录一、LBP特征介绍二、LBP特征描述三、一些改进版本的LBP1.圆形LBP算子2.旋转不变的LB

Redis消息队列实现异步秒杀功能

《Redis消息队列实现异步秒杀功能》在高并发场景下,为了提高秒杀业务的性能,可将部分工作交给Redis处理,并通过异步方式执行,Redis提供了多种数据结构来实现消息队列,总结三种,本文详细介绍Re... 目录1 Redis消息队列1.1 List 结构1.2 Pub/Sub 模式1.3 Stream 结

C# Where 泛型约束的实现

《C#Where泛型约束的实现》本文主要介绍了C#Where泛型约束的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录使用的对象约束分类where T : structwhere T : classwhere T : ne

将Java程序打包成EXE文件的实现方式

《将Java程序打包成EXE文件的实现方式》:本文主要介绍将Java程序打包成EXE文件的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录如何将Java程序编程打包成EXE文件1.准备Java程序2.生成JAR包3.选择并安装打包工具4.配置Launch4

MySQL索引的优化之LIKE模糊查询功能实现

《MySQL索引的优化之LIKE模糊查询功能实现》:本文主要介绍MySQL索引的优化之LIKE模糊查询功能实现,本文通过示例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一、前缀匹配优化二、后缀匹配优化三、中间匹配优化四、覆盖索引优化五、减少查询范围六、避免通配符开头七、使用外部搜索引擎八、分

Python实现特殊字符判断并去掉非字母和数字的特殊字符

《Python实现特殊字符判断并去掉非字母和数字的特殊字符》在Python中,可以通过多种方法来判断字符串中是否包含非字母、数字的特殊字符,并将这些特殊字符去掉,本文为大家整理了一些常用的,希望对大家... 目录1. 使用正则表达式判断字符串中是否包含特殊字符去掉字符串中的特殊字符2. 使用 str.isa

Spring Boot 集成 Quartz并使用Cron 表达式实现定时任务

《SpringBoot集成Quartz并使用Cron表达式实现定时任务》本篇文章介绍了如何在SpringBoot中集成Quartz进行定时任务调度,并通过Cron表达式控制任务... 目录前言1. 添加 Quartz 依赖2. 创建 Quartz 任务3. 配置 Quartz 任务调度4. 启动 Sprin

Android实现悬浮按钮功能

《Android实现悬浮按钮功能》在很多场景中,我们希望在应用或系统任意界面上都能看到一个小的“悬浮按钮”(FloatingButton),用来快速启动工具、展示未读信息或快捷操作,所以本文给大家介绍... 目录一、项目概述二、相关技术知识三、实现思路四、整合代码4.1 Java 代码(MainActivi