PyG-GAT-Cora(在Cora数据集上应用GAT做节点分类)

文章目录

model.py

py 复制代码
import torch.nn as nn
from torch_geometric.nn import GATConv
import torch.nn.functional as F
class gat_cls(nn.Module):
    def __init__(self,in_dim,hid_dim,out_dim,dropout_size=0.5):
        super(gat_cls,self).__init__()
        self.conv1 = GATConv(in_dim,hid_dim)
        self.conv2 = GATConv(hid_dim,hid_dim)
        self.fc = nn.Linear(hid_dim,out_dim)
        self.relu  = nn.ReLU()
        self.dropout_size = dropout_size
    def forward(self,x,edge_index):
        x = self.conv1(x,edge_index)
        x = F.dropout(x,p=self.dropout_size,training=self.training)
        x = self.relu(x)
        x = self.conv2(x,edge_index)
        x = self.relu(x)
        x = self.fc(x)
        return x

main.py

py 复制代码
import torch
import torch.nn as nn
from torch_geometric.datasets import Planetoid
from model import gat_cls
import torch.optim as optim
dataset = Planetoid(root='./data/Cora', name='Cora')
print(dataset[0])
cora_data = dataset[0]

epochs = 50
lr = 1e-3
weight_decay = 5e-3
momentum = 0.5
hidden_dim = 128
output_dim = 7


net = gat_cls(cora_data.x.shape[1],hidden_dim,output_dim)
optimizer = optim.AdamW(net.parameters(),lr=lr,weight_decay=weight_decay)
#optimizer = optim.SGD(net.parameters(),lr = lr,momentum=momentum)
criterion = nn.CrossEntropyLoss()
print("****************Begin Training****************")
net.train()
for epoch in range(epochs):
    out = net(cora_data.x,cora_data.edge_index)
    optimizer.zero_grad()
    loss_train = criterion(out[cora_data.train_mask],cora_data.y[cora_data.train_mask])
    loss_val   = criterion(out[cora_data.val_mask],cora_data.y[cora_data.val_mask])
    loss_train.backward()
    print('epoch',epoch+1,'loss-train {:.2f}'.format(loss_train),'loss-val {:.2f}'.format(loss_val))
    optimizer.step()

net.eval()
out = net(cora_data.x,cora_data.edge_index)
loss_test = criterion(out[cora_data.test_mask],cora_data.y[cora_data.test_mask])
_,pred = torch.max(out,dim=1)
pred_label = pred[cora_data.test_mask]
true_label = cora_data.y[cora_data.test_mask]
acc = sum(pred_label==true_label)/len(pred_label)
print("****************Begin Testing****************")
print('loss-test {:.2f}'.format(loss_test),'acc {:.2f}'.format(acc))

参数设置

bash 复制代码
epochs = 50
lr = 1e-3
weight_decay = 5e-3
momentum = 0.5
hidden_dim = 128
output_dim = 7

运行图

相关推荐
迅易科技44 分钟前
借助腾讯云质检平台的新范式,做工业制造企业质检的“AI慧眼”
人工智能·视觉检测·制造
古希腊掌管学习的神2 小时前
[机器学习]XGBoost(3)——确定树的结构
人工智能·机器学习
ZHOU_WUYI2 小时前
4.metagpt中的软件公司智能体 (ProjectManager 角色)
人工智能·metagpt
靴子学长3 小时前
基于字节大模型的论文翻译(含免费源码)
人工智能·深度学习·nlp
梧桐树04294 小时前
python常用内建模块:collections
python
AI_NEW_COME4 小时前
知识库管理系统可扩展性深度测评
人工智能
Dream_Snowar4 小时前
速通Python 第三节
开发语言·python
海棠AI实验室4 小时前
AI的进阶之路:从机器学习到深度学习的演变(一)
人工智能·深度学习·机器学习
hunteritself4 小时前
AI Weekly『12月16-22日』:OpenAI公布o3,谷歌发布首个推理模型,GitHub Copilot免费版上线!
人工智能·gpt·chatgpt·github·openai·copilot
IT古董5 小时前
【机器学习】机器学习的基本分类-强化学习-策略梯度(Policy Gradient,PG)
人工智能·机器学习·分类