當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。