为图卷积实现自定义无监督损失函数

问题描述 投票:0回答:1

我构建了一个图卷积模型,想要实现一个自定义的无监督损失函数,如下图所示:

损失函数

其中 yv 是节点 v 的学习嵌入,rand 表示对所有节点进行随机采样操作

我是 Pytorch 的新手,所以不确定这是否已经实现。任何帮助将不胜感激。

由于我是 Pytorch 的新手,不知道从哪里开始实现自定义损失函数

pytorch pytorch-geometric gnn graphsage
1个回答
0
投票

这是我用于在 PyTorch 中实现自定义损失函数的通用模板。我写了一些细节作为评论。您可以使用它作为起点:

import torch
from torch import nn

# Create a class which inherits from `nn.modules.loss._Loss`
class MyCustomLoss(nn.modules.loss._Loss):  # pylint: disable=protected-access

    # If the loss function has parameters, implement the constructor
    # In your case, it seems that there are no parameters
    def __init__(
            self,
            # Add the parameters, if present. Example:
            # margin: float
    ) -> None:
        super().__init__()
        # An example usage of setting a parameter:
        # self.margin: Final[float] = margin

    # Implement the forward method, specifying the inputs and outputs to your loss function,
    # and the calculation logic
    def forward(
        self,
        # Add your inputs here
    ) -> torch.Tensor:

        pass  # Implement the loss function logic, as is shown in the formula you provided

注意:我没有完全实现这个损失函数,因为我不熟悉您的用例的具体细节。

实现损失函数后,您可以像在训练阶段使用 PyTorch 内置损失函数一样使用它。一个简单的例子是:

# Instantiate the custom loss function
criterion = MyCustomLoss(parameters_if_present)

# Forward pass
model_outputs = model(train_input_or_inputs)

# Calculate loss
loss = criterion(model_outputs)

# Back-propagation and optimization
optimizer.zero_grad()
loss.backward()
optimizer.step()

请注意,根据您的深度学习任务,此示例可能会略有不同。

© www.soinside.com 2019 - 2024. All rights reserved.