大规模图数据思路代码

复制代码
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}')
相关推荐
默_笙5 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
LaughingZhu5 天前
Product Hunt 每日热榜 | 2026-09-19
人工智能·深度学习·神经网络·搜索引擎·百度
qq_426003965 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫5 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技5 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
风合星语5 天前
2026 具身智能技术实战(一):VLA 到底怎么控制机器人?——用 LeRobot 跑通 SmolVLA 推理
pytorch·机器人·具身智能·vla·lerobot·smolvla
伞伞悦读5 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
猎头南楼5 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
只睡四小时5 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
高洁015 天前
未来三年,AI 落地的五个确定性判断一
人工智能·深度学习·机器学习·transformer·知识图谱