0

我需要在 tensorflow1 中实现一个 VaR/CVaR 类,以便在 tf1 中编码的模型上使用它。我已经在pytorch中实现了它,但是我对tensorflow1不熟悉,我想寻求一些帮助。熟悉 tf1 的人可以帮帮我吗?下面是我在 pytorch 中的 VaR/CVaR 实现。先感谢您。

class CVaR(nn.Module):
    def __init__(self, alpha, learning_rate=1e-2):
        super(CVaR, self).__init__()

        self._alpha = alpha
        self._var = nn.Parameter(torch.tensor(1.0), requires_grad=True)

        self._optimizer = torch.optim.Adam([{"params": self._var, "lr": learning_rate}])

    def forward(self, losses):
        return self._var + 1 / self._alpha * torch.relu(losses - self._var)

    def zero_grad(self):
        """Reset CVaR internal optimizer."""
        self._optimizer.zero_grad()

    def step(self):
        """Execute a step of the internal CVaR optimizer."""
        self._optimizer.step()

    @property
    def var(self):
        """Get estimated Value-at-Risk."""
        return self._var


class SoftCVaR(CVaR):
    def __init__(self, alpha, learning_rate=1e-3, temperature=1):
        super(SoftCVaR, self).__init__(alpha, learning_rate=learning_rate)

        self._temperature = temperature

    def forward(self, losses):
        return self._var + self._temperature / self._alpha * torch.log(
            1 + torch.exp((losses - self._var) / self._temperature)
        )
4

0 回答 0