0.import torch_geometric 的Data 查看_冬炫的博客-CSDN博客_import torch_geometric
1. import torch_geometric 加载一些常见数据集_冬炫的博客-CSDN博客_torch_geometric 数据集
2. torch_geometric mini batch 的那些事_冬炫的博客-CSDN博客
Learning Methods on Graphs
Cora citation 数据集上搞一个GCN层
For a high-level explanation on GCN, have a look at its blog post.
①加载数据集
from torch_geometric.datasets import Planetoid
dataset = Planetoid(root='/tmp/Cora', name='Cora')
>>> Cora()
构建一个两层的GCN网络
import torch
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
class GCN(torch.nn.Module):
def __init__(self):
super().__init__()
self.conv1 = GCNConv(dataset.num_node_features, 16)
self.conv2 = GCNConv(16, dataset.num_classes)
def forward(self, data):
x, edge_index = data.x, data.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)
竟然如此之简单,整个就是在一张batch 大图上进行图卷积!!!!!!!!!\
启动这个网络,train 200 轮
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = GCN().to(device)
data = dataset[0].to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
model.train()
for epoch in range(200):
optimizer.zero_grad()
out = model(data)
loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])
loss.backward()
optimizer.step()
训练后,在测试集测试一下:
model.eval()
pred = model(data).argmax(dim=1)
correct = (pred[data.test_mask] == data.y[data.test_mask]).sum()
acc = int(correct) / int(data.test_mask.sum())
print(f'Accuracy: {acc:.4f}')
>>> Accuracy: 0.8150
The easiest way to learn more about Graph Neural Networks is to study the examples in the examples/
directory and to browse torch_geometric.nn
. Happy hacking!