当前位置: 首页>>代码示例>>Python>>正文


Python torch.reciprocal方法代码示例

本文整理汇总了Python中torch.reciprocal方法的典型用法代码示例。如果您正苦于以下问题:Python torch.reciprocal方法的具体用法?Python torch.reciprocal怎么用?Python torch.reciprocal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在torch的用法示例。


在下文中一共展示了torch.reciprocal方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_mrr

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def get_mrr(indices, targets):
    """
    Calculates the MRR score for the given predictions and targets
    Args:
        indices (Bxk): torch.LongTensor. top-k indices predicted by the model.
        targets (B): torch.LongTensor. actual target indices.

    Returns:
        mrr (float): the mrr score
    """

    tmp = targets.view(-1, 1)
    targets = tmp.expand_as(indices)
    hits = (targets == indices).nonzero()
    ranks = hits[:, -1] + 1
    ranks = ranks.float()
    rranks = torch.reciprocal(ranks)
    mrr = torch.sum(rranks).data / targets.size(0)
    return mrr.item() 
开发者ID:Wang-Shuo,项目名称:Neural-Attentive-Session-Based-Recommendation-PyTorch,代码行数:21,代码来源:metric.py

示例2: _get_discount

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def _get_discount(self, slate_size: int) -> Tensor:
        weights = DCGSlateMetric._weights
        if (
            weights is None
            or weights.shape[0] < slate_size
            or weights.device != self._device
        ):
            DCGSlateMetric._weights = torch.reciprocal(
                torch.log2(
                    torch.arange(
                        2, slate_size + 2, dtype=torch.double, device=self._device
                    )
                )
            )
        weights = DCGSlateMetric._weights
        assert weights is not None
        return weights[:slate_size] 
开发者ID:facebookresearch,项目名称:ReAgent,代码行数:19,代码来源:slate_estimators.py

示例3: evaluateMetric

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def evaluateMetric(ranks, metric):
    ranks = ranks.data.numpy()
    if metric == 'r1':
        ranks = ranks.reshape(-1)
        return 100 * (ranks == 1).sum() / float(ranks.shape[0])
    if metric == 'r5':
        ranks = ranks.reshape(-1)
        return 100 * (ranks <= 5).sum() / float(ranks.shape[0])
    if metric == 'r10':
        # ranks = ranks.view(-1)
        ranks = ranks.reshape(-1)
        # return 100*torch.sum(ranks <= 10).data[0]/float(ranks.size(0))
        return 100 * (ranks <= 10).sum() / float(ranks.shape[0])
    if metric == 'mean':
        # ranks = ranks.view(-1).float()
        ranks = ranks.reshape(-1).astype(float)
        return ranks.mean()
    if metric == 'mrr':
        # ranks = ranks.view(-1).float()
        ranks = ranks.reshape(-1).astype(float)
        # return torch.reciprocal(ranks).mean().data[0]
        return (1 / ranks).mean() 
开发者ID:naver,项目名称:aqm-plus,代码行数:24,代码来源:metrics.py

示例4: anticoupling_law

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def anticoupling_law(self, a, b):
        return torch.mul(a, torch.reciprocal(b)) 
开发者ID:paultsw,项目名称:nice_pytorch,代码行数:4,代码来源:layers.py

示例5: init_alpha_and_beta

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def init_alpha_and_beta(self, init_beta):
        """
        Initialize the alpha and beta of quantization function.
        init_data in numpy format.
        """
        # activations initialization (obtained offline)
        self.beta.data = torch.Tensor([init_beta]).cuda()
        self.alpha.data = torch.reciprocal(self.beta.data)
        self.alpha_beta_inited = True 
开发者ID:aliyun,项目名称:alibabacloud-quantization-networks,代码行数:11,代码来源:quantization.py

示例6: quantizeConvParams

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def quantizeConvParams(self, T, alpha, beta, init, train_phase):
        """
        quantize the parameters in forward
        """
        T = (T > 2000)*2000 + (T <= 2000)*T
        for index in range(self.num_of_params):
            if init:
                beta[index].data = torch.Tensor([self.threshold / self.target_modules[index].data.abs().max()]).cuda()
                alpha[index].data = torch.reciprocal(beta[index].data)
            # scale w
            x = self.target_modules[index].data.mul(beta[index].data)
            
            y = self.forward(x, T, self.QW_biases[index], train=train_phase)
            #scale w^hat
            self.target_modules[index].data = y.mul(alpha[index].data) 
开发者ID:aliyun,项目名称:alibabacloud-quantization-networks,代码行数:17,代码来源:anybit.py

示例7: updateQuaGradWeight

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def updateQuaGradWeight(self, T, alpha, beta, init):
        """
        Calculate the gradients of all the parameters.
        The gradients of model parameters are saved in the [Variable].grad.data.
        Args:
            T: the temperature, a single number. 
            alpha: the scale factor of the output, a list.
            beta: the scale factor of the input, a list. 
            init: a flag represents the first loading of the quantization function.
        Returns:
            alpha_grad: the gradient of alpha.
            beta_grad: the gradient of beta.
        """
        beta_grad = [0.0] * len(beta)
        alpha_grad = [0.0] * len(alpha)
        T = (T > 2000)*2000 + (T <= 2000)*T 
        for index in range(self.num_of_params):
            if init:
                beta[index].data = torch.Tensor([self.threshold / self.target_modules[index].data.abs().max()]).cuda()
                alpha[index].data = torch.reciprocal(beta[index].data)
            x = self.target_modules[index].data.mul(beta[index].data)

            # set T = 1 when train binary model
            y_grad = self.backward(x, 1, self.QW_biases[index]).mul(T)
            # set T = T when train the other quantization model
            #y_grad = self.backward(x, T, self.QW_biases[index]).mul(T)
            
        
            beta_grad[index] = y_grad.mul(self.target_modules[index].data).mul(alpha[index].data).\
                               mul(self.target_modules[index].grad.data).sum()
            alpha_grad[index] = self.forward(x, T, self.QW_biases[index]).\
                                mul(self.target_modules[index].grad.data).sum()

            self.target_modules[index].grad.data = y_grad.mul(beta[index].data).mul(alpha[index].data).\
                                                   mul(self.target_modules[index].grad.data)
        return alpha_grad, beta_grad 
开发者ID:aliyun,项目名称:alibabacloud-quantization-networks,代码行数:38,代码来源:anybit.py

示例8: log_normal_diag

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def log_normal_diag(x, mean, log_var, average=False, reduce=True, dim=None):
    log_norm = -0.5 * (log_var + (x - mean) * (x - mean) * log_var.exp().reciprocal())
    if reduce:
        if average:
            return torch.mean(log_norm, dim)
        else:
            return torch.sum(log_norm, dim)
    else:
        return log_norm 
开发者ID:riannevdberg,项目名称:sylvester-flows,代码行数:11,代码来源:distributions.py

示例9: log_normal_normalized

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def log_normal_normalized(x, mean, log_var, average=False, reduce=True, dim=None):
    log_norm = -(x - mean) * (x - mean)
    log_norm *= torch.reciprocal(2.*log_var.exp())
    log_norm += -0.5 * log_var
    log_norm += -0.5 * torch.log(2. * PI)

    if reduce:
        if average:
            return torch.mean(log_norm, dim)
        else:
            return torch.sum(log_norm, dim)
    else:
        return log_norm 
开发者ID:riannevdberg,项目名称:sylvester-flows,代码行数:15,代码来源:distributions.py

示例10: log_normal_normalized

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def log_normal_normalized(x, mean, log_var, average=False, reduce=True, dim=None):
    log_norm = -(x - mean) * (x - mean)
    log_norm *= torch.reciprocal(2. * log_var.exp())
    log_norm += -0.5 * log_var
    log_norm += -0.5 * torch.log(2. * PI)

    if reduce:
        if average:
            return torch.mean(log_norm, dim)
        else:
            return torch.sum(log_norm, dim)
    else:
        return log_norm 
开发者ID:AWehenkel,项目名称:UMNN,代码行数:15,代码来源:distributions.py

示例11: aten_reciprocal

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def aten_reciprocal(inputs, attributes, scope):
    inp = inputs[0]
    ctx = current_context()
    net = ctx.network
    if ctx.is_tensorrt and has_trt_tensor(inputs):
        layer = net.add_unary(inp, trt.UnaryOperation.RECIP)
        output = layer.get_output(0)
        output.name = scope
        layer.name = scope
        return [output]
    elif ctx.is_tvm and has_tvm_tensor(inputs):
        raise NotImplementedError

    return [torch.reciprocal(inp)] 
开发者ID:traveller59,项目名称:torch2trt,代码行数:16,代码来源:unary.py

示例12: give_laplacian_coordinates

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def give_laplacian_coordinates(self, pred, block_id):
        r''' Returns the laplacian coordinates for the predictions and given block.

            The helper matrices are used to detect neighbouring vertices and
            the number of neighbours which are relevant for the weight matrix.
            The maximal number of neighbours is 8, and if a vertex has less,
            the index -1 is used which points to the added zero vertex.

        Arguments:
            pred (tensor): vertex predictions
            block_id (int): deformation block id (1,2 or 3)
        '''
        batch_size = pred.shape[0]
        num_vert = pred.shape[1]
        # Add "zero vertex" for vertices with less than 8 neighbours
        vertex = torch.cat(
            [pred, torch.zeros(batch_size, 1, 3).to(self.device)], 1)
        assert(vertex.shape == (batch_size, num_vert+1, 3))
        # Get 8 neighbours for each vertex; if a vertex has less, the
        # remaining indices are -1
        indices = torch.from_numpy(
            self.lape_idx[block_id-1][:, :8]).to(self.device)
        assert(indices.shape == (num_vert, 8))
        weights = torch.from_numpy(
            self.lape_idx[block_id-1][:, -1]).float().to(self.device)
        weights = torch.reciprocal(weights)
        weights = weights.view(-1, 1).expand(-1, 3)
        vertex_select = vertex[:, indices.long(), :]
        assert(vertex_select.shape == (batch_size, num_vert, 8, 3))
        laplace = vertex_select.sum(dim=2)  # Add neighbours
        laplace = torch.mul(laplace, weights)  # Multiply by weights
        laplace = torch.sub(pred, laplace)  # Subtract from prediction
        assert(laplace.shape == (batch_size, num_vert, 3))
        return laplace 
开发者ID:autonomousvision,项目名称:occupancy_networks,代码行数:36,代码来源:training.py

示例13: step_function

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def step_function(self, x, y):
        return torch.reciprocal(1 + torch.exp(-self.k * (x - y))) 
开发者ID:WenmuZhou,项目名称:DBNet.pytorch,代码行数:4,代码来源:DBHead.py

示例14: reciprocal

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def reciprocal(t):
    """
    Element-wise reciprocal computed using cross-approximation; see PyTorch's `reciprocal()`.

    :param t: input :class:`Tensor`

    :return: a :class:`Tensor`
    """

    return tn.cross(lambda x: torch.reciprocal(x), tensors=t, verbose=False) 
开发者ID:rballester,项目名称:tntorch,代码行数:12,代码来源:ops.py

示例15: rsqrt

# 需要导入模块: import torch [as 别名]
# 或者: from torch import reciprocal [as 别名]
def rsqrt(t):
    """
    Element-wise square-root reciprocal computed using cross-approximation; see PyTorch's `rsqrt()`.

    :param t: input :class:`Tensor`

    :return: a :class:`Tensor`
    """

    return tn.cross(lambda x: torch.rsqrt(x), tensors=t, verbose=False) 
开发者ID:rballester,项目名称:tntorch,代码行数:12,代码来源:ops.py


注:本文中的torch.reciprocal方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。