pytorch|图卷积神经网络(GCN)与图注意力(GAT)在cora数据集的应用

pytorch简单实现GCN 论文:SEMI-SUPERVISED CLASSIFICATION WITH GRAPH CONVOLUTIONAL NETWORKS 前言:学习图卷积刚入门,看了一篇GNN开山之作,而后看了最开始的四代GCN,每一代都在上代上有所更新,大致明白了GCN的发展以及原理,这篇论文是这个系列最后一篇,也是这篇论文中出现了现在GCN的逐层传播公式,后续最新的图网络都是在这个基础上进行更新,个人觉得这四篇论文对图网络感兴趣的朋友入门还是很有帮助的。 这篇文章主要是针对最终得出来的公式进行翻译,简单测试。 1. 阅读详情

本文实现的两层GCN与GAT在cora数据集上效果,并可视化展示。

1.导入的相关包

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import torch
from torch._C import parse_ir
import torch_geometric
from torch_geometric import datasets
from torch_geometric.data import Data, InMemoryDataset
from torch_geometric.datasets import Planetoid
import torch.nn.functional as F
from torch_geometric.nn import GCNConv,GATConv # GCN
from sklearn.manifold import TSNE

2.数据处理部分

path = "E:\\download\\cora\\cora\\"
cites = path + "cora.cites"
content = path + "cora.content"

# 索引字典,将原本的论文id转换到从0开始编码
index_dict = dict()
# 标签字典,将字符串标签转化为数值
label_to_index = dict()

features = []
labels = []
edge_index = []

with open(content,"r") as f:
    nodes = f.readlines()
    for node in nodes:
        node_info = node.split()
        index_dict[int(node_info[0])] = len(index_dict)
        features.append([int(i) for i in node_info[1:-1]])
        
        label_str = node_info[-1]
        if(label_str not in label_to_index.keys()):
            label_to_index[label_str] = len(label_to_index)
        labels.append(label_to_index[label_str])

with open(cites,"r") as f:
    edges = f.readlines()
    for edge in edges:
        start, end = edge.split()
        # 训练时将边视为无向的,但原本的边是有向的,因此需要正反添加两次
        edge_index.append([index_dict[int(start)],index_dict[int(end)]])
        edge_index.append([index_dict[int(end)],index_dict[int(start)]])

# 转换为Tensor
labels = torch.LongTensor(labels)
features = torch.FloatTensor(features)
# 行归一化
features = torch.nn.functional.normalize(features, p=1, dim=1)
edge_index =  torch.LongTensor(edge_index)

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # 本电脑只有一个GPU

mask = torch.randperm(len(index_dict)) # 随机打乱顺序
train_mask = mask[:140]
val_mask = mask[140:640]
test_mask = mask[1708:2708]


cora = Data(x = features, edge_index = edge_index.t().contiguous(), y = labels).to(device)

3.GCN模块

class GCNNet(torch.nn.Module):
    def __init__(self, num_feature, num_label):
        super(GCNNet,self).__init__()
        self.GCN1 = GCNConv(num_feature, 16)
        self.GCN2 = GCNConv(16, num_label)  
        self.dropout = torch.nn.Dropout(p=0.5)
        
    def forward(self, data):
        x, edge_index = data.x, data.edge_index
        
        x = self.GCN1(x, edge_index)
        x = F.relu(x)
        x = self.dropout(x)
        x = self.GCN2(x, edge_index)
        
        return F.log_softmax(x, dim=1)


4.GAT模块

class GATNet(torch.nn.Module):
    def __init__(self, num_feature, num_label):
        super(GATNet,self).__init__()
        self.GAT1 = GATConv(num_feature, 8, heads = 8, concat = True, dropout = 0.6)
        self.GAT2 = GATConv(8*8, num_label, dropout = 0.6)  
        
    def forward(self, data):
        x, edge_index = data.x, data.edge_index
        
        x = self.GAT1(x, edge_index)
        x = F.relu(x)
        x = self.GAT2(x, edge_index)
        
        return F.log_softmax(x, dim=1)


5.画图及显示模块

def gcn_apply():
    model = GCNNet(features.shape[1], len(label_to_index)).to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)

    acc_record = []
    loss_record = []

    for epoch in range(500):
        optimizer.zero_grad()
        out = model(cora)
        loss = F.nll_loss(out[train_mask], cora.y[train_mask])
        loss_record.append(loss.item())
        print('epoch: %d loss: %.4f' %(epoch, loss))
        loss.backward()
        optimizer.step()
        
        # if((epoch + 1)% 10 == 0):
        model.eval()
        _, pred = model(cora).max(dim=1)
        correct = int(pred[test_mask].eq(cora.y[test_mask]).sum().item())
        acc = correct / len(test_mask)
        acc_record.append(acc)
        print('Accuracy: {:.4f}'.format(acc))
        model.train()
            


    ts = TSNE(n_components=2)
    ts.fit_transform(out[test_mask].to('cpu').detach().numpy())

    x = ts.embedding_
    y = cora.y[test_mask].to('cpu').detach().numpy()

    xi = []
    for i in range(7):
        xi.append(x[np.where(y==i)])

    colors = ['mediumblue','green','red','yellow','cyan','mediumvioletred','mediumspringgreen']
    plt.figure(figsize=(8, 6))
    for i in range(7):
        plt.scatter(xi[i][:,0],xi[i][:,1],s=30,color=colors[i],marker='+',alpha=1)
    plt.show()

    plt.figure(figsize=(14, 9))
    x = range(500)

    plt.plot(x,acc_record,label='acc')
    plt.plot(x,loss_record,label='loss')
    plt.legend()
    plt.grid()
    plt.show()


def gat_apply():
    seed = 1
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)  
    np.random.seed(seed)  # Numpy module.
    # random.seed(seed)  # Python random module.
    torch.manual_seed(seed)
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True
    model = GATNet(features.shape[1], len(label_to_index)).to(device)

    optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)

    acc_record = []
    loss_record = []


    for epoch in range(500):
        optimizer.zero_grad()
        out = model(cora)
        loss = F.nll_loss(out[train_mask], cora.y[train_mask])
        loss_record.append(loss.item())
        print('epoch: %d loss: %.4f' %(epoch, loss))
        loss.backward()
        optimizer.step()
        
        # if((epoch + 1)% 10 == 0):
        model.eval()
        _, pred = model(cora).max(dim=1)
        correct = int(pred[test_mask].eq(cora.y[test_mask]).sum().item())
        acc = correct / len(test_mask)
        acc_record.append(acc)
        print('Accuracy: {:.4f}'.format(acc))
        model.train()
            


    ts = TSNE(n_components=2)
    ts.fit_transform(out[test_mask].to('cpu').detach().numpy())

    x = ts.embedding_
    y = cora.y[test_mask].to('cpu').detach().numpy()

    xi = []
    for i in range(7):
        xi.append(x[np.where(y==i)])

    colors = ['mediumblue','green','red','yellow','cyan','mediumvioletred','mediumspringgreen']
    plt.figure(figsize=(8, 6))
    for i in range(7):
        plt.scatter(xi[i][:,0],xi[i][:,1],s=30,color=colors[i],marker='+',alpha=1)
    plt.show()

    plt.figure(figsize=(14, 9))
    x = range(500)

    plt.plot(x,acc_record,label='acc')
    plt.plot(x,loss_record,label='loss')
    plt.legend()
    plt.grid()
    plt.show()

6.主函数

if __name__ == "__main__":
    gcn_apply()
    gat_apply()

7.整个网络的代码

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import torch
from torch._C import parse_ir
import torch_geometric
from torch_geometric import datasets
from torch_geometric.data import Data, InMemoryDataset
from torch_geometric.datasets import Planetoid
import torch.nn.functional as F
from torch_geometric.nn import GCNConv,GATConv # GCN
from sklearn.manifold import TSNE

path = "E:\\download\\cora\\cora\\"
cites = path + "cora.cites"
content = path + "cora.content"

# 索引字典,将原本的论文id转换到从0开始编码
index_dict = dict()
# 标签字典,将字符串标签转化为数值
label_to_index = dict()

features = []
labels = []
edge_index = []

with open(content,"r") as f:
    nodes = f.readlines()
    for node in nodes:
        node_info = node.split()
        index_dict[int(node_info[0])] = len(index_dict)
        features.append([int(i) for i in node_info[1:-1]])
        
        label_str = node_info[-1]
        if(label_str not in label_to_index.keys()):
            label_to_index[label_str] = len(label_to_index)
        labels.append(label_to_index[label_str])

with open(cites,"r") as f:
    edges = f.readlines()
    for edge in edges:
        start, end = edge.split()
        # 训练时将边视为无向的,但原本的边是有向的,因此需要正反添加两次
        edge_index.append([index_dict[int(start)],index_dict[int(end)]])
        edge_index.append([index_dict[int(end)],index_dict[int(start)]])


class GCNNet(torch.nn.Module):
    def __init__(self, num_feature, num_label):
        super(GCNNet,self).__init__()
        self.GCN1 = GCNConv(num_feature, 16)
        self.GCN2 = GCNConv(16, num_label)  
        self.dropout = torch.nn.Dropout(p=0.5)
        
    def forward(self, data):
        x, edge_index = data.x, data.edge_index
        
        x = self.GCN1(x, edge_index)
        x = F.relu(x)
        x = self.dropout(x)
        x = self.GCN2(x, edge_index)
        
        return F.log_softmax(x, dim=1)


class GATNet(torch.nn.Module):
    def __init__(self, num_feature, num_label):
        super(GATNet,self).__init__()
        self.GAT1 = GATConv(num_feature, 8, heads = 8, concat = True, dropout = 0.6)
        self.GAT2 = GATConv(8*8, num_label, dropout = 0.6)  
        
    def forward(self, data):
        x, edge_index = data.x, data.edge_index
        
        x = self.GAT1(x, edge_index)
        x = F.relu(x)
        x = self.GAT2(x, edge_index)
        
        return F.log_softmax(x, dim=1)


# 为每个节点增加自环,但后续GCN层默认会添加自环,跳过即可
# for i in range(2708):
#     edge_index.append([i,i])
  
# 转换为Tensor
labels = torch.LongTensor(labels)
features = torch.FloatTensor(features)
# 行归一化
features = torch.nn.functional.normalize(features, p=1, dim=1)
edge_index =  torch.LongTensor(edge_index)

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # 本电脑只有一个GPU

mask = torch.randperm(len(index_dict)) # 随机打乱顺序
train_mask = mask[:140]
val_mask = mask[140:640]
test_mask = mask[1708:2708]


cora = Data(x = features, edge_index = edge_index.t().contiguous(), y = labels).to(device)

def gcn_apply():
    model = GCNNet(features.shape[1], len(label_to_index)).to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)

    acc_record = []
    loss_record = []

    for epoch in range(500):
        optimizer.zero_grad()
        out = model(cora)
        loss = F.nll_loss(out[train_mask], cora.y[train_mask])
        loss_record.append(loss.item())
        print('epoch: %d loss: %.4f' %(epoch, loss))
        loss.backward()
        optimizer.step()
        
        # if((epoch + 1)% 10 == 0):
        model.eval()
        _, pred = model(cora).max(dim=1)
        correct = int(pred[test_mask].eq(cora.y[test_mask]).sum().item())
        acc = correct / len(test_mask)
        acc_record.append(acc)
        print('Accuracy: {:.4f}'.format(acc))
        model.train()
            


    ts = TSNE(n_components=2)
    ts.fit_transform(out[test_mask].to('cpu').detach().numpy())

    x = ts.embedding_
    y = cora.y[test_mask].to('cpu').detach().numpy()

    xi = []
    for i in range(7):
        xi.append(x[np.where(y==i)])

    colors = ['mediumblue','green','red','yellow','cyan','mediumvioletred','mediumspringgreen']
    plt.figure(figsize=(8, 6))
    for i in range(7):
        plt.scatter(xi[i][:,0],xi[i][:,1],s=30,color=colors[i],marker='+',alpha=1)
    plt.show()

    plt.figure(figsize=(14, 9))
    x = range(500)

    plt.plot(x,acc_record,label='acc')
    plt.plot(x,loss_record,label='loss')
    plt.legend()
    plt.grid()
    plt.show()


def gat_apply():
    seed = 1
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)  
    np.random.seed(seed)  # Numpy module.
    # random.seed(seed)  # Python random module.
    torch.manual_seed(seed)
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True
    model = GATNet(features.shape[1], len(label_to_index)).to(device)

    optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)

    acc_record = []
    loss_record = []


    for epoch in range(500):
        optimizer.zero_grad()
        out = model(cora)
        loss = F.nll_loss(out[train_mask], cora.y[train_mask])
        loss_record.append(loss.item())
        print('epoch: %d loss: %.4f' %(epoch, loss))
        loss.backward()
        optimizer.step()
        
        # if((epoch + 1)% 10 == 0):
        model.eval()
        _, pred = model(cora).max(dim=1)
        correct = int(pred[test_mask].eq(cora.y[test_mask]).sum().item())
        acc = correct / len(test_mask)
        acc_record.append(acc)
        print('Accuracy: {:.4f}'.format(acc))
        model.train()
            


    ts = TSNE(n_components=2)
    ts.fit_transform(out[test_mask].to('cpu').detach().numpy())

    x = ts.embedding_
    y = cora.y[test_mask].to('cpu').detach().numpy()

    xi = []
    for i in range(7):
        xi.append(x[np.where(y==i)])

    colors = ['mediumblue','green','red','yellow','cyan','mediumvioletred','mediumspringgreen']
    plt.figure(figsize=(8, 6))
    for i in range(7):
        plt.scatter(xi[i][:,0],xi[i][:,1],s=30,color=colors[i],marker='+',alpha=1)
    plt.show()

    plt.figure(figsize=(14, 9))
    x = range(500)

    plt.plot(x,acc_record,label='acc')
    plt.plot(x,loss_record,label='loss')
    plt.legend()
    plt.grid()
    plt.show()

if __name__ == "__main__":
    gcn_apply()
    gat_apply()

8.相关图片

图片(1)程序运行截图
在这里插入图片描述
图片(2)GCN分类图
在这里插入图片描述
图片(3)GCN LOSS与ACC
在这里插入图片描述
图片(4)GAT分类可视化
在这里插入图片描述
图片(5)GAT LOSS与ACC
在这里插入图片描述

保姆级教程:用PyTorch Geometric从零搭建GCN和GAT,搞定Cora论文分类 本文提供了一份详细的PyTorch Geometric教程,从零开始构建GCN和GAT模型,并应用于Cora论文分类任务。通过环境准备、数据加载、模型构建、训练评估等步骤,帮助读者掌握图神经网络的核心技术。教程特别适合希望深入了解GNN实践的开发者,涵盖了节点分类的关键技巧和常见问题解决方案。 阅读详情

相关推荐

GCN vs GAT实战对比:在Cora数据集上,谁才是节点分类的王者?(附PyTorch Geometric代码)

本文对比了图卷积网络(GCN)和图注意力网络(GAT)在Cora数据集上的节点分类性能,提供了详细的PyTorch Geometric实现代码。实验结果显示,GAT在准确率上略胜一筹,但GCN在训练速度和资源消耗上更具优势。文章还给出了针对不同场景的技术选型建议和优化技巧,帮助开发者根据实际需求选择最合适的模型。

weixin_30505225的博客 414

[图神经网络]PyTorch简单实现一个GCN

图神经网络PyG实现

就随便写写.... 3750

Pytorch实现GCN(基于PyTorch实现)

本专栏整理了《图神经网络代码实战》,内包含了不同图神经网络的相关代码实现(PyG以及自实现),理论与实践相结合,如GCN、GAT、GraphSAGE等经典图网络,每一个代码实例都附带有完整的代码。

CSDN 精品推荐 6954

实战-----基于 PyTorch 的 GNN 搭建

在以上的实验中,我们对 PyG 中的图数据类以及自身具备的图数据进行了实践,整体而言比较简单,和 PyTorch 中的一些相关操作也有相似之处。唯一美中不足的是,在加载 PyG 中的图数据时经常会遇到问题,需要手工下载数据集并且修改原代码。1%29%7D网址在此。

qq_56164625的博客 6047

Pytorch实现GCN(基于Message Passing消息传递机制实现)

本专栏整理了《图神经网络代码实战》,内包含了不同图神经网络的相关代码实现(PyG以及自实现),理论与实践相结合,如GCN、GAT、GraphSAGE等经典图网络,每一个代码实例都附带有完整的代码。

CSDN 精品推荐 6036

【深度学习常用算法】十二、图神经网络(GNN):从基础理论到GCN与GAT的全栈解析与实战

摘要:本文系统阐述图神经网络(GNN)的核心原理、关键变体及其在多领域的应用实践。作为处理图结构数据的专用深度学习模型,GNN通过聚合邻居节点信息实现图数据特征学习,在社交网络分析、分子结构预测、推荐系统等领域展现独特优势。文中深入解析图卷积网络(GCN)和图注意力网络(GAT)的算法机制,通过PyTorch Geometric实现完整模型训练与推理,在Cora引文网络和ZINC分子数据集上进行实验验证。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 1127

PyTorch深度学习实战:图神经网络

本文介绍了图神经网络(GNN)的基本概念与应用实践。课程内容涵盖图数据表示方法、图卷积网络(GCN)和图注意力网络(GAT)的原理实现,以及使用PyTorch Geometric进行优化。通过Cora(节点分类)和MUTAG(图分类)两个经典数据集,展示了GNN在不同层级任务(节点级、边级、图级)的应用方法。课程提供了完整的环境配置指南,包括PyTorch Lightning框架和NPU/CPU/MPS等多种计算设备的适配方案,旨在帮助学习者掌握GNN的核心技术及其在社交网络、知识图谱等领域的实际应用能力。

WSSWWWSSW的博客 883

图神经网络实战(8)——图注意力网络(Graph Attention Networks, GAT)

图注意力网络 (Graph Attention Networks, GAT) 是对图卷积网络 (Graph Convolutional Network, GCN) 的改进,提出了一种通过自注意力 (self-attention) 过程计算的加权因子,而不是使用静态的归一化系数。在本节中,我们介绍了 GAT 架构。通过从线性变换到多头注意力的四个主要步骤,了解了 GAT 的工作原理,并在 NumPy 中从零开始构建了 GAT 层。最后,将 GAT 模型应用于 Cora 和 CiteSeer 数据集。

盼小辉丶的博客 1万+

图神经网络完全指南:从零开始掌握GNN的核心原理与应用

图神经网络(GNN)是深度学习领域中专门处理图结构数据的强大工具,已广泛应用于社交网络分析、推荐系统、分子结构预测等多个领域。本指南将帮助你从零开始理解GNN的核心概念、工作原理及实际应用,即使没有深厚的数学背景也能轻松入门。 ## 一、什么是图神经网络? 图神经网络(Graph Neural Network, GNN)是一类专门设计用于处理图结构数据的神经网络模型。与传统的CNN和RNN不同

gitblog_00340的博客 767

GCN的pytorch实现

本代码可以纵观从数据load到GCN训练的全过程,是一份比较好的学习demo。 本代码参考自https://colab.research.google.com/drive/1mMUKnvM_Byu8wEcJpFSYGnniPPhIOD7N?usp=sharing。

带你学习Android中的ContentObserver

通过使用,开发者可以有效地监听系统设置的变化,例如屏幕亮度等。这种机制使得应用能够动态响应系统设置的更改,提升用户体验。在实现需要与系统设置交互的应用时,合理使用是非常重要的。

执剑人 1317

第17篇:图神经网络(GNN):处理非欧几里得数据的利器

摘要:本文系统讲解图神经网络(GNN)的核心原理与应用,重点解析图卷积网络(GCN)的谱域/空域实现、图注意力网络(GAT)的注意力机制、图自编码器(GAE)与图生成方法。通过PyTorch Geometric(PyG)库,演示Cora引文网络的节点分类与链接预测实战。内容涵盖图数据特性、消息传递机制、GNN模型架构及前沿研究方向,帮助读者掌握处理社交网络、分子结构等非欧几里得数据的图学习方法,并附有完整代码实现与学习建议。

to do , to be . 1367

MMSegmentation 安装教程,避免mmcv不合适版本,及相关问题解决

都行,不做要求。

qq_43683133的博客 1224

DGL官方教程--图注意力网络(GAT)

Note: Click here to download the full example code Graph attention network Authors: Hao Zhang, Mufei Li , Minjie Wang Zheng Zhang 在本教程中,您将学习图注意力网络(GAT)以及如何在PyTorch中实现它。您还可以学习可视化并了解注意力机制所学到的知识。 图卷积网络...

weixin_45613751的博客 1万+

从理论到波形:NE555多谐振荡器设计与示波器实战验证

本文详细介绍了NE555多谐振荡器的设计原理与实战验证方法。从基础理论到电路参数计算,再到面包板搭建与示波器测量,全面解析如何利用NE555芯片实现稳定的方波输出。通过实际案例演示了频率调整、占空比优化等技巧,并提供了常见问题排查指南,帮助电子爱好者快速掌握这一经典电路设计。

weixin_29159613的博客 289

基于继电器与三极管的自动水泵控制器DIY:从电路原理到PCB制作实战

继电器作为一种利用电磁原理实现电路通断控制的电气开关,其核心价值在于通过小电流信号控制大电流负载,实现强弱电之间的安全隔离。在自动化控制领域,继电器常与三极管等半导体器件配合,构成驱动电路,将微弱的传感器信号放大,从而可靠地控制电机、水泵等执行机构。这种组合技术广泛应用于工业控制、智能家居及各类电子DIY项目中,例如实现水箱水位的自动检测与控制。本文将以一个典型的自动水泵控制器项目为例,深入剖析如何利用继电器与三极管搭建水位检测与驱动电路,并详细讲解从电路设计、PCB自制(热转印法)到系统调试的完整工程实践

weixin_31774841的博客 355

图神经网络进阶:图注意力网络(Graph Attention Networks, GAT)让邻居“说话”有轻重

计算分类准确率:预测正确的样本数 ÷ 总样本数。注意:此函数假设输入是一维张量(如argmax后的类别索引)。特性说明使用 GATv2Conv比原始 GAT 表达能力更强,能学习更复杂的注意力函数多头注意力(8 heads)提升模型容量和鲁棒性高比例 Dropout(0.6)应对小训练集过拟合问题端到端训练/验证/测试封装代码结构清晰,易于复用利用图结构(edge_index)通过注意力机制动态聚合邻居GCN 是“平均听邻居说话”,GAT 是“有选择地听重要的邻居说话”。通过引入注意力机制。

sweet_ran的博客 1913

YOLOv8n模型导出ONNX的避坑指南:解决版本差异,正确生成TensorRT/RKNN所需输出节点

本文详细介绍了YOLOv8n模型导出ONNX格式的实战避坑指南,涵盖版本差异处理、代码修改技巧及TensorRT/RKNN部署优化方案。针对不同推理框架需求,提供输出节点生成、动态轴处理和后处理划分等核心问题的解决方案,帮助开发者高效完成模型部署。

weixin_33247358的博客 370

深入理解图注意力机制

图卷积网络Graph Convolutional Network (GCN) 告诉我们将局部的图结构和节点特征结合可以在节点分类任务中获得不错的表现。美中不足的是 GCN 结合邻近节点特征的方式和图的结构依依相关,这局限了训练所得模型在其他图结构上的泛化能力。 Graph Attention Network (GAT) 提出了用注意力机制对邻近节点特征加权求和。邻近节点特征的权重完全取决于节点...

zzx3163967592的博客 6650

教程: 将 SolidWorks 设计导出为 ROS 的 URDF

请按照以下步骤应用自定义徽标纹理:创建徽标材质文件:techniquepass材质名称:测试/材质颜色属性:环境、漫反射、镜面和发射都设置为白色(1 1 1 1),这意味着该材质看起来完全是白色的。纹理 在表面应用纹理图像 logo.png。将材质文件复制到 gazebo matrial:复制徽标图像:将 “徽标 ”替换为机器人上徽标所在位置的适当参考值。按照以上步骤,您就可以在 Gazebo 中为机器人添加自定义材质和纹理,包括徽标。

机器人控制与仿真应用 2466

《用 AI 赋能医药科研创新》目录(持续更新)

本专栏旨在指导医学科研和药物研发人员运用AI技术提升研究效率。内容包括:利用AI分析文献、识别研究热点、自动生成研究草稿;在新药研发中,通过AI优化临床方案设计、受试者筛选等环节;介绍AI理论基础如大语言模型、提示词工程学及智能体技术发展历程。专栏采用5000-9000字的长文形式,系统讲解AI在医药研发各环节的应用方法,帮助研究者缩短周期、降低成本,推动医药研发进入智能化新阶段。

MD Code 513

从零实现GCN与GAT:Cora数据集节点分类实战(PyTorch Geometric版)

本文详细介绍了如何使用PyTorch Geometric从零实现GCN与GAT模型,并在Cora数据集上完成节点分类任务。通过代码示例和实战技巧,帮助读者掌握图神经网络的核心原理与应用,包括数据加载、模型构建、训练优化及结果可视化等关键步骤,特别适合图神经网络初学者快速入门。

weixin_29056781的博客 410

SOME/IP协议详解「总目录」

SOME/IP系列文章总目录

雪云飞星的博客 2万+

图卷积神经网络快速入门:基于PyTorch的GCN模型完整指南

图卷积神经网络(GCN)是处理图结构数据的革命性技术,能够有效分析社交网络、推荐系统、生物信息学等复杂关系数据。本文将带你从零开始,快速掌握基于PyTorch的GCN实现,构建一个功能完善的图神经网络演示系统。🚀 ## 传统方法的局限性与GCN的突破 传统神经网络在处理规则数据(如图像、文本)方面表现出色,但当面对**图结构数据**时却显得力不从心。图数据具有非欧几里得特性,节点间的连接关系

gitblog_00814的博客 875

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

PyTorch实战:手把手教你实现GAT图注意力网络(附完整代码)

本文详细介绍了如何使用PyTorch从零实现图注意力网络(GAT),深入解析了其核心的注意力机制与工程实现细节。通过对比GCN,阐述了GAT如何通过可学习的注意力权重动态聚合邻居信息,并提供了完整的代码示例、训练技巧以及在Cora等数据集上的实战应用,帮助读者掌握这一强大的图表示学习工具。

silver的专栏 1022

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

基于pytorch的GAT教程

本文的想法是让非研究人员也能更轻松地理解图注意力网络(以及通用的GNN)!在本文中,您将获得以下问题的答案:✅ GAT 到底是什么?✅ 如何加载和可视化Cora引文网络?✅ 我们如何训练GAT(Cora分类示例)?✅ 如何可视化不同GAT的属性?完成本课程后,您将对图神经网络有更好的理解!注意:在本笔记本中,我们将重点关注 Cora(传导法示例),如果需要可以查看其他笔记本中的PPI - 蛋白质相互作用数据集(归纳法)。很好,让我们开始吧!

GawainTky的博客 1146

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

上一篇: 复杂网络;社交网络;社区检测;节点重要性(重要节点识别);舆论动力学模型; 传染病模型 ;蓄意攻击 、随机攻击;网络鲁棒性、脆弱性、稳定性
下一篇: PyG|邻接矩阵转为coo_matrix格式
xiao黄
xiao黄 优质创作者: 人工智能技术领域 优质创作者: 人工智能技术领域 领域专家: 数据科学与机器学习技术领域 领域专家: 数据科学与机器学习技术领域
博客等级 码龄8年 1万+粉丝 250原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiao黄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址