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
相关推荐
cuber膜拜37 分钟前
jupyter使用 Token 认证登录张登杰踩2 小时前
pytorch2.5实例教程codists2 小时前
《CPython Internals》阅读笔记:p353-p355Change is good2 小时前
selenium定位元素的方法Change is good2 小时前
selenium clear()方法清除文本框内容存内计算开发者3 小时前
机器人奇点:从宇树科技看2025具身智能发展大懒猫软件7 小时前
如何运用python爬虫获取大型资讯类网站文章,并同时导出pdf或word格式文本?XianxinMao8 小时前
RLHF技术应用探析:从安全任务到高阶能力提升查理零世9 小时前
【算法】经典博弈论问题——巴什博弈 python有Li10 小时前
基于深度学习的微出血自动检测及解剖尺度定位|文献速递-视觉大模型医疗图像应用