Exemple #1
0
def norm(t):
    """
    Computes the :math:`L^2` (Frobenius) norm of a tensor.

    :param t: a :class:`Tensor`

    :return: a scalar :math:`\ge 0`
    """

    return torch.sqrt(torch.clamp(tn.normsq(t), min=0))
Exemple #2
0
def var(t):
    """
    Computes the variance of a :class:`Tensor`.

    :param t: a :class:`Tensor`

    :return: a scalar :math:`\ge 0`
    """

    return tn.normsq(t - tn.mean(t)) / t.numel()
Exemple #3
0
def r_squared(gt, approx):
    """
    Computes the :math:`R^2` score between two tensors (torch or tntorch).

    :param gt: a torch or tntorch tensor
    :param approx: a torch or tntorch tensor

    :return: a scalar <= 1
    """

    gt, approx = _process(gt, approx)
    if isinstance(gt, torch.Tensor) and isinstance(approx, torch.Tensor):
        return 1 - torch.dist(gt, approx)**2 / torch.dist(gt, torch.mean(gt))**2
    return 1 - tn.dist(gt, approx)**2 / tn.normsq(gt-tn.mean(gt))
Exemple #4
0
def var(t, marginals=None):
    """
    Computes the variance of a :class:`Tensor`.

    :param t: a :class:`Tensor`
    :param marginals: an optional list of vectors

    :return: a scalar :math:`\ge 0`
    """

    if marginals is not None:
        assert len(marginals) == t.dim()
        tcentered = t - tn.mean(t, marginals=marginals)
        pdf = tn.Tensor(
            [marg[None, :, None] / marg.sum() for marg in marginals])
        return tn.dot(tcentered * pdf, tcentered)

    return tn.normsq(t - tn.mean(t)) / t.numel()
Exemple #5
0
    def normsq(self, **kwargs):
        """
        See :func:`metrics.normsq()`.
        """

        return tn.normsq(self, **kwargs)