import torch
import torch.nn.functional as F
from torch_geometric.datasets import Planetoid
from torch_geometric.nn import GCNConv
from torch_geometric.loader import NeighborSampler
# 定义图神经网络模型
class GCN(torch.nn.Module):
def __init__(self, num_features, num_classes):
super(GCN, self).__init__()
self.conv1 = GCNConv(num_features, 16)
self.conv2 = GCNConv(16, num_classes)
def forward(self, x, edge_index, size):
# 使用邻居信息进行采样
x = self.conv1(x, edge_index)
x = F.relu(x)
x = F.dropout(x, training=self.training)
x = self.conv2(x, edge_index, size)
return F.log_softmax(x, dim=1)
# 加载数据集
dataset = Planetoid(root='/tmp/Cora', name='Cora')
data = dataset[0]
# 创建邻居采样迭代器
train_loader = NeighborSampler(data.edge_index,
node_idx=data.train_mask,
sizes=[10, 10], # 每层采样的邻居数
batch_size=64, # 每次批次的节点数
num_nodes=data.num_nodes)
# 初始化模型和优化器
model = GCN(num_features=dataset.num_node_features, num_classes=dataset.num_classes)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# 训练模型
def train(loader, model, optimizer):
model.train()
total_loss = 0
for batch_size, n_id, adj in loader:
optimizer.zero_grad()
# 通过采样得到节点特征和边列表
x = data.x[n_id].to(device)
out = model(x, adj.edge_index, adj.size)
loss = F.nll_loss(out[adj.node_idx], data.y[adj.node_idx].to(device))
loss.backward()
optimizer.step()
total_loss += loss.item()
return total_loss
# 评估模型
def test(model):
model.eval()
with torch.no_grad():
out = model(data.x.to(device), data.edge_index.to(device), data.num_nodes)
pred = out.argmax(dim=1)
correct = pred[data.test_mask.to(device)] == data.y[data.test_mask.to(device)]
acc = int(correct.sum()) / int(data.test_mask.sum())
return acc
# 训练和验证
for epoch in range(200):
loss = train(train_loader, model, optimizer)
if epoch % 20 == 0:
train_acc = test(model)
print(f'Epoch {epoch}, Loss: {loss:.4f}, Train Accuracy: {train_acc:.4f}')
# 测试模型
test_acc = test(model)
print(f'Test Accuracy: {test_acc:.4f}')
大规模图数据思路代码
医学小达人2024-07-27 22:44
相关推荐
红色的山茶花9 分钟前
YOLOv9-0.1部分代码阅读笔记-loss_tal.py岑梓铭33 分钟前
(CentOs系统虚拟机)Standalone模式下安装部署“基于Python编写”的Spark框架游客5201 小时前
opencv中的各种滤波器简介一位小说男主1 小时前
编码器与解码器:从‘乱码’到‘通话’Eric.Lee20211 小时前
moviepy将图片序列制作成视频并加载字幕 - python 实现Dontla1 小时前
vscode怎么设置anaconda python解释器(anaconda解释器、vscode解释器)qq_529025292 小时前
Torch.gather数据小爬虫@2 小时前
如何高效利用Python爬虫按关键字搜索苏宁商品