将原来的半监督模式改为全监督模式,只需要在模型的最后一层添加一个全连接层,输出所有节点的分类概率即可。

以下是一个示例代码:

import torch
import torch.nn as nn
from torch_geometric.nn import GCNConv

class GCN(nn.Module):
    def __init__(self, in_channels, hidden_channels, out_channels):
        super(GCN, self).__init__()
        self.conv1 = GCNConv(in_channels, hidden_channels)
        self.conv2 = GCNConv(hidden_channels, hidden_channels)
        self.conv3 = GCNConv(hidden_channels, out_channels)
        self.fc = nn.Linear(out_channels, out_channels)

    def forward(self, x, edge_index):
        x = self.conv1(x, edge_index).relu()
        x = self.conv2(x, edge_index).relu()
        x = self.conv3(x, edge_index)

        # 添加全连接层
        x = self.fc(x)

        return x

# 生成随机数据
x = torch.randn(100, 16)
edge_index = torch.randint(0, 100, (2, 1000))
y = torch.randint(0, 10, (100,))

# 创建模型并训练
model = GCN(16, 32, 10)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)

for epoch in range(100):
    optimizer.zero_grad()
    out = model(x, edge_index)
    loss = criterion(out, y)
    loss.backward()
    optimizer.step()

    print('Epoch {}, Loss: {:.4f}'.format(epoch, loss.item()))
图卷积神经网络全监督模式代码示例

原文地址: https://www.cveoy.top/t/topic/odC8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录