【DGL】节点分类(GCN、SAGE、自定义)

2024-02-20 09:30

本文主要是介绍【DGL】节点分类(GCN、SAGE、自定义),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

    • 使用dgl进行节点分类(GCN)
      • 数据集
      • 搭建网络
      • 训练
    • 使用dgl进行节点分类(SAGE)
      • 实现SAGE
      • 引入边权
      • 更多自定义操作

使用dgl进行节点分类(GCN)

数据集

dataset = dgl.data.CoraGraphDataset()
print("Number of categories:", dataset.num_classes)
g = dataset[0]

数据集信息:
Cora dataset,引用网络图,其中,节点表示论文,边表示论文的引用。任务是预测给定论文的类别。

NumNodes: 2708NumEdges: 10556NumFeats: 1433NumClasses: 7NumTrainingSamples: 140NumValidationSamples: 500NumTestSamples: 1000
Done loading data from cached files.
Number of categories: 7

其中,含有一个graph:

Graph(num_nodes=2708, num_edges=10556,ndata_schemes={'train_mask': Scheme(shape=(), dtype=torch.bool), 'label': Scheme(shape=(), dtype=torch.int64), 'val_mask': Scheme(shape=(), dtype=torch.bool), 'test_mask': Scheme(shape=(), dtype=torch.bool), 'feat': Scheme(shape=(1433,), dtype=torch.float32)}edata_schemes={})

train_mask: A boolean tensor indicating whether the node is in the training set.
val_mask: A boolean tensor indicating whether the node is in the validation set.
test_mask: A boolean tensor indicating whether the node is in the test set.
label: The ground truth node category.
feat: The node features.

搭建网络

根据Graph Convolutional Network (GCN)搭建两层的图卷积神经网络。每一层通过聚合邻居节点的信息来计算新的节点表示。
在这里插入图片描述

class GCN(nn.Module):def __init__(self, in_feats, h_feats, num_classes):super(GCN, self).__init__()self.conv1 = GraphConv(in_feats, h_feats)self.conv2 = GraphConv(h_feats, num_classes)def forward(self, g, in_feat):h = self.conv1(g, in_feat)h = F.relu(h)h = self.conv2(g, h)return hmodel = GCN(g.ndata['feat'].shape[1], 16, dataset.num_classes)
print(model)

数学上表示成1 h i ( l + 1 ) = σ ( b ( l ) + ∑ j ∈ N ( i ) 1 c j i h j ( l ) W ( l ) ) h_i^{(l+1)} = \sigma(b^{(l)} + \sum_{j\in\mathcal{N}(i)}\frac{1}{c_{ji}}h_j^{(l)}W^{(l)}) hi(l+1)=σ(b(l)+jN(i)cji1hj(l)W(l))

模型结构:

GCN((conv1): GraphConv(in=1433, out=16, normalization=both, activation=None)(conv2): GraphConv(in=16, out=7, normalization=both, activation=None)
)

训练

def train(g, model):optimizer = torch.optim.Adam(model.parameters(), lr=0.01)best_val_acc = 0best_test_acc = 0features = g.ndata['feat']labels = g.ndata['label']train_mask = g.ndata['train_mask']val_mask = g.ndata['val_mask']test_mask = g.ndata['test_mask']for e in range(100):logits = model(g, features)pred = logits.argmax(1)loss = F.cross_entropy(logits[train_mask], labels[train_mask])train_acc = (pred[train_mask] == labels[train_mask]).float().mean()val_acc = (pred[val_mask] == labels[val_mask]).float().mean()test_acc = (pred[test_mask] == labels[test_mask]).float().mean()if(best_val_acc < val_acc):best_val_acc = val_accbest_test_acc = test_accoptimizer.zero_grad()loss.backward()optimizer.step()if(e%5==0):print("In epoch {}, loss: {:.3f}, val acc: {:.3f} (best {:.3f}), test acc: {:.3f} (best {:.3f})".format(e, loss, val_acc, best_val_acc, test_acc, best_test_acc))train(g, model)
In epoch 0, loss: 1.946, val acc: 0.240 (best 0.240), test acc: 0.254 (best 0.254)
In epoch 5, loss: 1.903, val acc: 0.642 (best 0.642), test acc: 0.639 (best 0.639)
In epoch 10, loss: 1.837, val acc: 0.696 (best 0.700), test acc: 0.711 (best 0.715)
In epoch 15, loss: 1.746, val acc: 0.674 (best 0.700), test acc: 0.685 (best 0.715)
In epoch 20, loss: 1.628, val acc: 0.694 (best 0.700), test acc: 0.710 (best 0.715)
In epoch 25, loss: 1.484, val acc: 0.690 (best 0.700), test acc: 0.715 (best 0.715)
In epoch 30, loss: 1.321, val acc: 0.710 (best 0.710), test acc: 0.732 (best 0.732)
In epoch 35, loss: 1.144, val acc: 0.714 (best 0.720), test acc: 0.738 (best 0.737)
In epoch 40, loss: 0.966, val acc: 0.730 (best 0.730), test acc: 0.742 (best 0.742)
In epoch 45, loss: 0.797, val acc: 0.742 (best 0.742), test acc: 0.745 (best 0.745)
In epoch 50, loss: 0.647, val acc: 0.756 (best 0.756), test acc: 0.756 (best 0.756)
In epoch 55, loss: 0.520, val acc: 0.762 (best 0.762), test acc: 0.759 (best 0.759)
In epoch 60, loss: 0.416, val acc: 0.768 (best 0.768), test acc: 0.767 (best 0.765)
In epoch 65, loss: 0.334, val acc: 0.762 (best 0.768), test acc: 0.771 (best 0.765)
In epoch 70, loss: 0.270, val acc: 0.758 (best 0.768), test acc: 0.774 (best 0.765)
In epoch 75, loss: 0.220, val acc: 0.760 (best 0.768), test acc: 0.777 (best 0.765)
In epoch 80, loss: 0.182, val acc: 0.764 (best 0.768), test acc: 0.779 (best 0.765)
In epoch 85, loss: 0.151, val acc: 0.764 (best 0.768), test acc: 0.780 (best 0.765)
In epoch 90, loss: 0.128, val acc: 0.764 (best 0.768), test acc: 0.782 (best 0.765)
In epoch 95, loss: 0.109, val acc: 0.766 (best 0.768), test acc: 0.779 (best 0.765)Process finished with exit code 0

使用dgl进行节点分类(SAGE)

dgl遵循消息传递网络范式2。GraphSAGE convolution (Hamilton et al., 2017)具有以下形式:

h N ( v ) k ← A v e r a g e { h u k − 1 , ∀ u ∈ N ( v ) } h v k ← R e L U ( W k ⋅ C O N C A T ( h v k − 1 , h N ( v ) k ) ) h_\mathcal{N(v)}^k \gets Average\{ h_u ^{k-1} , \forall u \in \mathcal{N}(v) \} \\ h_v^k \gets ReLU(W^k \cdot CONCAT(h_v^{k-1}, h^k _{\mathcal{N}(v)})) hN(v)kAverage{huk1,uN(v)}hvkReLU(WkCONCAT(hvk1,hN(v)k))

实现SAGE

在dgl中有内置的SAGEConv。下面来自己实现:

class SAGEConv(nn.Module):def __init__(self, in_feat, out_feat):super(SAGEConv, self).__init__()# A linear submodule for projecting the input and neighbor feature to the output.self.linear = nn.Linear(in_feat*2, out_feat) # Wdef forward(self, g, h):with g.local_scope():#在这个区域内对g的修改不会同步到原始的图上g.ndata['h'] = hg.update_all(    #对所有的节点和边采用下面的message函数和reduce函数message_func=fn.copy_u("h", "m"), #message函数:将节点特征'h'作为消息传递给邻居,命名为'm'reduce_func=fn.mean("m", "h_N"),  #reduce函数:将接收到的'm'信息取平均,保存至节点特征'h_N')h_N = g.ndata["h_N"]h_total = torch.cat([h, h_N], dim=1)return self.linear(h_total)

依此搭建新的网络:

class Model(nn.Module):def __init__(self, in_feats, h_feats, num_classes):super(Model, self).__init__()self.conv1 = SAGEConv(in_feats, h_feats)self.conv2 = SAGEConv(h_feats, num_classes)def forward(self, g, in_feat):h = self.conv1(g, in_feat)h = F.relu(h)h = self.conv2(g, h)return hmodel = Model(g.ndata['feat'].shape[1], 16, dataset.num_classes)

效果和GCN差不多吧

引入边权

class WeightedSAGEConv(nn.Module):def __init__(self, in_feat, out_feat):super(WeightedSAGEConv, self).__init__()# A linear submodule for projecting the input and neighbor feature to the output.self.linear = nn.Linear(in_feat * 2, out_feat)def forward(self, g, h, w):with g.local_scope():g.ndata["h"] = hg.edata["w"] = wg.update_all(message_func=fn.u_mul_e("h", "w", "m"), #节点特征'h' 与 邻居间的边特征'w' 的乘积作为消息传递给邻居,记作'm'reduce_func=fn.mean("m", "h_N"), #将接收到的'm'信息取平均,保存至节点特征'h_N')h_N = g.ndata["h_N"]h_total = torch.cat([h, h_N], dim=1)return self.linear(h_total)class Model(nn.Module):def __init__(self, in_feats, h_feats, num_classes):super(Model, self).__init__()self.conv1 = WeightedSAGEConv(in_feats, h_feats)self.conv2 = WeightedSAGEConv(h_feats, num_classes)def forward(self, g, in_feat):h = self.conv1(g, in_feat, torch.ones(g.num_edges(), 1).to(g.device))#数据中没有边特征,在这里手动添加h = F.relu(h)h = self.conv2(g, h, torch.ones(g.num_edges(), 1).to(g.device))return hmodel = Model(g.ndata["feat"].shape[1], 16, dataset.num_classes)

更多自定义操作

见dgl.function

内置函数 dgl.function.u_add_v('hu','hv',' he')等价于:

def message_func(edges):#返回值为字典形式return {'he': edges.src['hu'] + edges.dst['hv']}

  1. https://docs.dgl.ai/generated/dgl.nn.pytorch.conv.GraphConv.html#dgl.nn.pytorch.conv.GraphConv ↩︎

  2. Neural Message Passing for Quantum Chemistry ↩︎

这篇关于【DGL】节点分类(GCN、SAGE、自定义)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

C++链表的虚拟头节点实现细节及注意事项

《C++链表的虚拟头节点实现细节及注意事项》虚拟头节点是链表操作中极为实用的设计技巧,它通过在链表真实头部前添加一个特殊节点,有效简化边界条件处理,:本文主要介绍C++链表的虚拟头节点实现细节及注... 目录C++链表虚拟头节点(Dummy Head)一、虚拟头节点的本质与核心作用1. 定义2. 核心价值二

MySQL中的索引结构和分类实战案例详解

《MySQL中的索引结构和分类实战案例详解》本文详解MySQL索引结构与分类,涵盖B树、B+树、哈希及全文索引,分析其原理与优劣势,并结合实战案例探讨创建、管理及优化技巧,助力提升查询性能,感兴趣的朋... 目录一、索引概述1.1 索引的定义与作用1.2 索引的基本原理二、索引结构详解2.1 B树索引2.2

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

一文详解Java Stream的sorted自定义排序

《一文详解JavaStream的sorted自定义排序》Javastream中的sorted方法是用于对流中的元素进行排序的方法,它可以接受一个comparator参数,用于指定排序规则,sorte... 目录一、sorted 操作的基础原理二、自定义排序的实现方式1. Comparator 接口的 Lam

如何自定义一个log适配器starter

《如何自定义一个log适配器starter》:本文主要介绍如何自定义一个log适配器starter的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录需求Starter 项目目录结构pom.XML 配置LogInitializer实现MDCInterceptor

Druid连接池实现自定义数据库密码加解密功能

《Druid连接池实现自定义数据库密码加解密功能》在现代应用开发中,数据安全是至关重要的,本文将介绍如何在​​Druid​​连接池中实现自定义的数据库密码加解密功能,有需要的小伙伴可以参考一下... 目录1. 环境准备2. 密码加密算法的选择3. 自定义 ​​DruidDataSource​​ 的密码解密3

spring-gateway filters添加自定义过滤器实现流程分析(可插拔)

《spring-gatewayfilters添加自定义过滤器实现流程分析(可插拔)》:本文主要介绍spring-gatewayfilters添加自定义过滤器实现流程分析(可插拔),本文通过实例图... 目录需求背景需求拆解设计流程及作用域逻辑处理代码逻辑需求背景公司要求,通过公司网络代理访问的请求需要做请

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

Pandas使用AdaBoost进行分类的实现

《Pandas使用AdaBoost进行分类的实现》Pandas和AdaBoost分类算法,可以高效地进行数据预处理和分类任务,本文主要介绍了Pandas使用AdaBoost进行分类的实现,具有一定的参... 目录什么是 AdaBoost?使用 AdaBoost 的步骤安装必要的库步骤一:数据准备步骤二:模型

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定