写一段基于pyg的图神经网络的节点分类的代码
时间: 2024-06-01 10:09:58 浏览: 152
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch_geometric.datasets import Planetoid
import torch_geometric.nn as pyg_nn
# Load dataset
dataset = Planetoid(root='/tmp/Cora', name='Cora')
data = dataset[0]
# Define model
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = pyg_nn.GCNConv(data.num_features, 16)
self.conv2 = pyg_nn.GCNConv(16, dataset.num_classes)
def forward(self, x, edge_index):
x = self.conv1(x, edge_index)
x = F.relu(x)
x = F.dropout(x, training=self.training)
x = self.conv2(x, edge_index)
return F.log_softmax(x, dim=1)
# Initialize model and optimizer
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
# Training loop
def train():
model.train()
optimizer.zero_grad()
out = model(data.x, data.edge_index)
loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])
loss.backward()
optimizer.step()
return loss.item()
# Testing loop
def test():
model.eval()
with torch.no_grad():
out = model(data.x, data.edge_index)
pred = out.argmax(dim=1)
test_correct = pred[data.test_mask] == data.y[data.test_mask]
test_acc = int(test_correct.sum()) / int(data.test_mask.sum())
return test_acc
# Train and test
for epoch in range(1, 201):
loss = train()
test_acc = test()
print(f'Epoch {epoch:03d}, Loss: {loss:.4f}, Test Acc: {test_acc:.4f}')
阅读全文