【论文代码】GraphSAGE(更新ing)

简介: (4)root_weight (bool, optional): If set to :obj:False, the layer will not add transformed root node features to the output.(default: :obj:True)(5)bias (bool, optional): If set to :obj:False, the layer will not learn an additive bias. (default: :obj:True)(6)**kwargs (optional): Additional arguments

1.1 加载数据

1.2 Unsupervised Loss

1.3 Models

1.4 评估与模型使用

1.5 Main

二、PyG版本

image.png

class SAGEConv(MessagePassing):

(1)in_channels (int or tuple): Size of each input sample, or :obj:-1 to derive the size from the first input(s) to the forward method.A tuple corresponds to the sizes of source and target dimensionalities.

(2)out_channels (int): Size of each output sample.

(3)normalize (bool, optional): If set to :obj:True, output features will be :math:ℓ 2 \ell_2ℓ

2

-normalized, i.e., :math:

image.png

. (default: :obj:False)

(4)root_weight (bool, optional): If set to :obj:False, the layer will not add transformed root node features to the output.(default: :obj:True)

(5)bias (bool, optional): If set to :obj:False, the layer will not learn an additive bias. (default: :obj:True)

(6)**kwargs (optional): Additional arguments of

官方代码:https://github.com/williamleif/graphsage-simple/

如果我们使用pytorch的PyG也能很方便调用:

# -*- coding: utf-8 -*-
"""
Created on Fri Oct  8 23:16:13 2021
@author: 86493
"""
import torch
from torch_geometric.datasets import Planetoid
from torch_geometric.transforms import NormalizeFeatures
dataset = Planetoid(root='C:/dataset/Cora/processed', name='Cora', transform=NormalizeFeatures())
print()
print(f'Dataset: {dataset}:')
print('======================')
print(f'Number of graphs: {len(dataset)}')
print(f'Number of features: {dataset.num_features}')
print(f'Number of classes: {dataset.num_classes}')
data = dataset[0]  # Get the first graph object.
print()
print(data)
print('======================')
# Gather some statistics about the graph.
print(f'Number of nodes: {data.num_nodes}')
print(f'Number of edges: {data.num_edges}')
print(f'Average node degree: {data.num_edges / data.num_nodes:.2f}')
print(f'Number of training nodes: {data.train_mask.sum()}')
print(f'Training node label rate: {int(data.train_mask.sum()) / data.num_nodes:.2f}')
print(f'Contains isolated nodes: {data.has_isolated_nodes()}')
print(f'Contains self-loops: {data.has_self_loops()}')
print(f'Is undirected: {data.is_undirected()}')
# 2.可视化节点表征分布的方法
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
def visualize(h, color):
    z = TSNE(n_components=2).fit_transform(h.detach().cpu().numpy())
    plt.figure(figsize=(10,10))
    plt.xticks([])
    plt.yticks([])
    plt.scatter(z[:, 0], z[:, 1], s=70, c=color, cmap="Set2")
    plt.show()
# 网络的构造
import torch
from torch.nn import Linear
import torch.nn.functional as F
"""
from torch_geometric.nn import GCNConv
class GCN(torch.nn.Module):
    def __init__(self, hidden_channels):
        super(GCN, self).__init__()
        torch.manual_seed(12345)
        self.conv1 = GCNConv(dataset.num_features, hidden_channels)
        self.conv2 = GCNConv(hidden_channels, dataset.num_classes)
    def forward(self, x, edge_index):
        x = self.conv1(x, edge_index)
        x = x.relu()
        x = F.dropout(x, p=0.5, training=self.training)
        x = self.conv2(x, edge_index)
        return x
"""
from torch_geometric.nn import SAGEConv
class SAGE(torch.nn.Module):
    def __init__(self, hidden_channels):
        super(SAGE, self).__init__()
        torch.manual_seed(12345)
        self.conv1 = SAGEConv(dataset.num_features, hidden_channels)
        self.conv2 = SAGEConv(hidden_channels, dataset.num_classes)
    def forward(self, x, edge_index):
        x = self.conv1(x, edge_index)
        x = x.relu()
        x = F.dropout(x, p=0.5, training=self.training)
        x = self.conv2(x, edge_index)
        return x
model = SAGE(hidden_channels=16)
print(model)
# 可视化由未经训练的图神经网络生成的节点表征
model = SAGE(hidden_channels=16)
model.eval()
out = model(data.x, data.edge_index)
visualize(out, color=data.y)
# 图神经网络的训练
model = SAGE(hidden_channels=16)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
criterion = torch.nn.CrossEntropyLoss()
def train():
      model.train()
      optimizer.zero_grad()  # Clear gradients.
      out = model(data.x, data.edge_index)  # Perform a single forward pass.
      loss = criterion(out[data.train_mask], data.y[data.train_mask])  # Compute the loss solely based on the training nodes.
      loss.backward()  # Derive gradients.
      optimizer.step()  # Update parameters based on gradients.
      return loss
for epoch in range(1, 201):
    loss = train()
    print(f'Epoch: {epoch:03d}, Loss: {loss:.4f}')
# 增加loss折线图
import pandas as pd
df = pd.DataFrame(columns = ["Loss"]) # columns列名
df.index.name = "Epoch" 
for epoch in range(1, 201):
    loss = train()
    #df.loc[epoch] = loss.item()
    df.loc[epoch] = loss.item()
df.plot() 
# 图神经网络的测试
def test():
      model.eval()
      out = model(data.x, data.edge_index)
      pred = out.argmax(dim=1)  # Use the class with highest probability.
      test_correct = pred[data.test_mask] == data.y[data.test_mask]  # Check against ground-truth labels.
      test_acc = int(test_correct.sum()) / int(data.test_mask.sum())  # Derive ratio of correct predictions.
      return test_acc
test_acc = test()
print(f'Test Accuracy: {test_acc:.4f}')
# 可视化由训练后的图神经网络生成的节点表征
model.eval()
out = model(data.x, data.edge_index)
visualize(out, color=data.y)

打印出的结果为:

Dataset: Cora():
======================
Number of graphs: 1
Number of features: 1433
Number of classes: 7
Data(
  x=[2708, 1433], edge_index=[2, 10556], 
  y=[2708], train_mask=[2708], 
  val_mask=[2708], test_mask=[2708]
  )
======================
Number of nodes: 2708
Number of edges: 10556
Average node degree: 3.90
Number of training nodes: 140
Training node label rate: 0.05
Contains isolated nodes: False
Contains self-loops: False
Is undirected: True
SAGE(
  (conv1): SAGEConv(1433, 16)
  (conv2): SAGEConv(16, 7)
)

image.png

可视化的图如上所示,也可以可视化loss的200个epoch的折线图:

image.png

Reference

(1)https://github.com/twjiang/graphSAGE-pytorch/tree/master/src

(2)https://zhuanlan.zhihu.com/p/410407148

(3)https://blog.csdn.net/weixin_44027006/article/details/116888648

(4)GraphSAGE 代码解析(二) - layers.py

(5)https://www.zhihu.com/search?q=GraphSAGE%E4%BB%A3%E7%A0%81PyG%E8%A7%A3%E8%AF%BB&utm_content=search_history&type=content

相关文章
|
12月前
|
运维 监控 数据可视化
别再手画 Visio 了!如何实现 L2/L3 层网络拓扑自动发现与实时监控?
运维十年老兵感慨:网络故障如黑屋寻针。OpManager以SNMP自动构建动态拓扑,实现全网可视,精准定位根因,屏蔽无效告警,让运维从“盲人摸象”变为“一目了然”,真正掌控复杂环境。
326 0
|
传感器 人工智能 物联网
无线气体自动灭火系统在数据机房的应用,沃思智能
无线气体自动灭火系统融合物联网与AI技术,实现火灾秒级响应、智能判断与自动灭火,广泛应用于数据中心、电力设施等高价值场所。系统无需布线、安装灵活,支持远程监控与多设备联动,显著降低误报率与运维成本。随着5G与绿色灭火剂发展,正迈向“预测性防护”新阶段,助力消防进入智能化时代。(238字)
595 1
|
存储 人工智能 自然语言处理
AI代理内存消耗过大?9种优化策略对比分析
在AI代理系统中,多代理协作虽能提升整体准确性,但真正决定性能的关键因素之一是**内存管理**。随着对话深度和长度的增加,内存消耗呈指数级增长,主要源于历史上下文、工具调用记录、数据库查询结果等组件的持续积累。本文深入探讨了从基础到高级的九种内存优化技术,涵盖顺序存储、滑动窗口、摘要型内存、基于检索的系统、内存增强变换器、分层优化、图形化记忆网络、压缩整合策略以及类操作系统内存管理。通过统一框架下的代码实现与性能评估,分析了每种技术的适用场景与局限性,为构建高效、可扩展的AI代理系统提供了系统性的优化路径和技术参考。
1148 4
AI代理内存消耗过大?9种优化策略对比分析
|
自然语言处理 Serverless 测试技术
DeepSeek 模型快速体验,魔搭+函数计算一键部署模型上云
DeepSeek模型近期备受关注,其开源版本DeepSeek-V3和DeepSeek-R1在多个基准测试中表现出色,性能比肩OpenAI顶尖模型。为降低本地部署门槛,Modelscope社区推出DeepSeek-R1-Distill-Qwen模型的一键部署服务,支持函数计算FC平台的闲置GPU实例,大幅降低成本。用户可选择不同参数量的小模型进行快速部署和推理,体验DeepSeek的强大性能。
1310 40
DeepSeek 模型快速体验,魔搭+函数计算一键部署模型上云
|
机器学习/深度学习 人工智能 算法
深度学习用于求解车间调度问题,性能如何呢?
基于深度学习来求解车间调度问题,不仅求解速度快,求解的质量也越来越好
1000 24
|
存储 运维 监控
深度体验阿里云系统控制台:SysOM 让 Linux 服务器监控变得如此简单
作为一名经历过无数个凌晨三点被服务器报警电话惊醒的运维工程师,我对监控工具有着近乎苛刻的要求。记得去年那次大型活动,我们的主站流量暴增,服务器内存莫名其妙地飙升到90%以上,却找不到原因。如果当时有一款像阿里云 SysOM 这样直观的监控工具,也许我就不用熬通宵排查问题了。今天,我想分享一下我使用 SysOM 的亲身体验,特别是它那令人印象深刻的内存诊断功能。
925 1
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot中的全局异常处理——拦截自定义异常
本文介绍了在实际项目中如何拦截自定义异常。首先,通过定义异常信息枚举类 `BusinessMsgEnum`,统一管理业务异常的代码和消息。接着,创建自定义业务异常类 `BusinessErrorException`,并在其构造方法中传入枚举类以实现异常信息的封装。最后,利用 `GlobalExceptionHandler` 拦截并处理自定义异常,返回标准的 JSON 响应格式。文章还提供了示例代码和测试方法,展示了全局异常处理在 Spring Boot 项目中的应用价值。
806 0
|
消息中间件 架构师 Java
阿里面试:秒杀的分布式事务, 是如何设计的?
在40岁老架构师尼恩的读者交流群中,近期有小伙伴在面试阿里、滴滴、极兔等一线互联网企业时,遇到了许多关于分布式事务的重要面试题。为了帮助大家更好地应对这些面试题,尼恩进行了系统化的梳理,详细介绍了Seata和RocketMQ事务消息的结合,以及如何实现强弱结合型事务。文章还提供了分布式事务的标准面试答案,并推荐了《尼恩Java面试宝典PDF》等资源,帮助大家在面试中脱颖而出。
|
运维 Kubernetes Docker
微服务的成本效益分析
【8月更文第29天】随着微服务架构的流行,越来越多的企业开始考虑采用这一架构模式来构建他们的应用程序和服务。然而,迁移到微服务并非没有代价。本文旨在评估采用微服务架构所带来的成本增加与收益,并探讨如何优化资源使用,以最大化成本效益比。
1293 1
|
数据采集 自然语言处理 测试技术
CodeFuse-13B: 预训练多语言代码大模型
该论文针对蚂蚁集团的现实应用场景,详细介绍了CodeFuse-13B预训练模型的数据准备和训练过程,揭秘了CodeFuse是如何成为一款能够同时处理英文和中文提示的高效预训练代码大型语言模型(LLM)。论文还对CodeFuse在代码生成、翻译、注释和测试用例生成等应用场景中的性能进行了评估。CodeFuse-13B在蚂蚁集团内广
1120 2