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
相关推荐
Blossom.11811 分钟前
《探索边缘计算:重塑未来智能物联网的关键技术》wgc2k38 分钟前
吴恩达深度学习复盘(6)神经网络的矢量化原理?Agony1 小时前
P17_ResNeXt-50Ronin-Lotus1 小时前
深度学习篇---模型训练早停机制浪淘沙jkp1 小时前
大模型学习四:DeepSeek Janus-Pro 多模态理解和生成模型 本地部署指南(折腾版)yolo大师兄2 小时前
【YOLO系列(V5-V12)通用数据集-火灾烟雾检测数据集】liruiqiang052 小时前
循环神经网络 - 机器学习任务之同步的序列到序列模式汲海2 小时前
Jupyter 505独好紫罗兰2 小时前
洛谷题单3-P4956 [COCI 2017 2018 #6] Davor-python-流程图重构摆烂仙君2 小时前
3D意识(3D Awareness)浅析