GNN 代码实现图编码,要求每个图(而不是节点)都有自己的标签,尽可能让编码向量可以表征对应标签信息。给出训练、测试用例
时间: 2024-02-03 13:15:33 浏览: 212
matlab二值化处理的代码-craquelure-graphs:从图像中提取和表征裂纹图案
4星 · 用户满意度95%
下面是一个简单的 GNN 代码实现图编码的示例,其中每个图都有自己的标签,编码向量可以表征对应标签信息。
训练用例:
```python
import torch
import torch.nn.functional as F
from torch_geometric.datasets import TUDataset
from torch_geometric.utils import degree
from torch_geometric.nn import GCNConv
# 加载数据集
dataset = TUDataset(root='/tmp/ENZYMES', name='ENZYMES')
# 计算每个节点的度数
data = dataset[0]
data.degrees = degree(data.edge_index[0], data.num_nodes)
data = data.to('cuda')
# 定义模型
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = GCNConv(dataset.num_node_features, 16)
self.conv2 = GCNConv(16, 32)
self.lin = torch.nn.Linear(32, dataset.num_classes)
def forward(self, x, edge_index, degrees):
x = F.relu(self.conv1(x, edge_index, degrees))
x = F.relu(self.conv2(x, edge_index, degrees))
x = torch_geometric.nn.global_mean_pool(x, data.batch)
x = self.lin(x)
return x
model = Net().to('cuda')
# 训练模型
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
criterion = torch.nn.CrossEntropyLoss()
for epoch in range(100):
optimizer.zero_grad()
out = model(data.x, data.edge_index, data.degrees)
loss = criterion(out, data.y)
loss.backward()
optimizer.step()
# 测试模型
model.eval()
correct = 0
for data in dataset:
data = data.to('cuda')
pred = model(data.x, data.edge_index, data.degrees).max(dim=1)[1]
correct += int(pred.eq(data.y).sum())
print(f'Accuracy: {correct / len(dataset)}')
```
测试用例:
```python
import torch
import torch.nn.functional as F
from torch_geometric.datasets import TUDataset
from torch_geometric.utils import degree
from torch_geometric.nn import GCNConv
# 加载数据集
dataset = TUDataset(root='/tmp/ENZYMES', name='ENZYMES')
# 计算每个节点的度数
data = dataset[0]
data.degrees = degree(data.edge_index[0], data.num_nodes)
data = data.to('cuda')
# 定义模型
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = GCNConv(dataset.num_node_features, 16)
self.conv2 = GCNConv(16, 32)
self.lin = torch.nn.Linear(32, dataset.num_classes)
def forward(self, x, edge_index, degrees):
x = F.relu(self.conv1(x, edge_index, degrees))
x = F.relu(self.conv2(x, edge_index, degrees))
x = torch_geometric.nn.global_mean_pool(x, data.batch)
x = self.lin(x)
return x
model = Net().to('cuda')
# 加载训练好的模型
model.load_state_dict(torch.load('model.pt'))
# 测试模型
model.eval()
correct = 0
for data in dataset:
data = data.to('cuda')
pred = model(data.x, data.edge_index, data.degrees).max(dim=1)[1]
correct += int(pred.eq(data.y).sum())
print(f'Accuracy: {correct / len(dataset)}')
```
阅读全文