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
相关推荐
uncle_ll7 分钟前
PyTorch图像预处理:计算均值和方差以实现标准化在下不上天8 分钟前
Flume日志采集系统的部署,实现flume负载均衡,flume故障恢复SEVEN-YEARS11 分钟前
深入理解TensorFlow中的形状处理函数EterNity_TiMe_16 分钟前
【论文复现】(CLIP)文本也能和图像配对Suyuoa27 分钟前
附录2-pytorch yolov5目标检测好看资源平台2 小时前
网络爬虫——综合实战项目:多平台房源信息采集与分析系统余生H2 小时前
transformer.js(三):底层架构及性能优化指南进击的六角龙2 小时前
深入浅出:使用Python调用API实现智能天气预报檀越剑指大厂2 小时前
【Python系列】浅析 Python 中的字典更新与应用场景罗小罗同学2 小时前
医工交叉入门书籍分享:Transformer模型在机器学习领域的应用|个人观点·24-11-22