Shortcuts

MarginLoss

class pybind11_ke.module.loss.MarginLoss(*args: Any, **kwargs: Any)[源代码]

TransE [BUGD+13] 原论文中应用这种损失函数完成模型训练。

备注

forward() 中的正样本评分函数的得分应小于负样本评分函数的得分。

例子:

from pybind11_ke.module.model import TransE
from pybind11_ke.module.loss import MarginLoss
from pybind11_ke.module.strategy import NegativeSampling

# define the model
transe = TransE(
        ent_tol = dataloader.get_ent_tol(),
        rel_tol = dataloader.get_rel_tol(),
        dim = 50, 
        p_norm = 1, 
        norm_flag = True
)

# define the loss function
model = NegativeSampling(
        model = transe, 
        loss = MarginLoss(margin = 1.0),
        regul_rate = 0.01
)
__call__(*args: Any, **kwargs: Any) Any

Call self as a function.

__init__(adv_temperature: float | None = None, margin: float = 6.0)[源代码]

创建 MarginLoss 对象。

参数:
  • adv_temperature (float) – RotatE 提出的自我对抗负采样中的温度。

  • margin (float) – gamma。

static __new__(cls, *args: Any, **kwargs: Any) Any
__repr__() str

Return repr(self).

__weakref__

list of weak references to the object (if defined)

adv_flag: bool

是否启用 RotatE 提出的自我对抗负采样。

adv_temperature: torch.nn.parameter.Parameter

RotatE 提出的自我对抗负采样中的温度。

forward(p_score: torch.Tensor, n_score: torch.Tensor) torch.Tensor[源代码]

计算 margin-based ranking criterion 损失函数。定义每次调用时执行的计算。 torch.nn.Module 子类必须重写 torch.nn.Module.forward()

参数:
  • p_score (torch.Tensor) – 正样本评分函数的得分。

  • n_score (torch.Tensor) – 负样本评分函数的得分。

返回:

损失值

返回类型:

torch.Tensor

get_parameters(mode: str = 'numpy', param_dict: dict[str, Any] | None = None) dict[str, numpy.ndarray] | dict[str, list] | dict[str, torch.Tensor]

获得模型权重。

参数:
  • mode – 模型保存的格式,可以选择 numpylistTensor

  • param_dict (dict[str, Any] | None) – 可以选择从哪里获得模型权重。

返回:

模型权重字典。

返回类型:

dict[str, numpy.ndarray] | dict[str, list] | dict[str, torch.Tensor]

get_weights(n_score: torch.Tensor) torch.Tensor[源代码]

计算 RotatE 提出的自我对抗负采样中的负样本的分布概率。

参数:

n_score (torch.Tensor) – 负样本评分函数的得分。

返回:

自我对抗负采样中的负样本的分布概率

返回类型:

torch.Tensor

load_checkpoint(path: str)

加载模型权重。

参数:

path (str) – 模型保存的路径

load_parameters(path: str)

加载模型权重。

参数:

path (str) – 模型保存的路径

margin: torch.nn.parameter.Parameter

gamma

pi_const: torch.nn.parameter.Parameter

常数 pi

save_checkpoint(path: str)

保存模型权重。

参数:

path (str) – 模型保存的路径

save_parameters(path: str)

用 json 格式保存模型权重。

参数:

path (str) – 模型保存的路径

set_parameters(parameters: dict[str, Any])

加载模型权重。

参数:

parameters (dict[str, Any]) – 模型权重字典。

zero_const: torch.nn.parameter.Parameter

常数 0

Docs

Access comprehensive developer documentation for Pybind11-OpenKE

View Docs