本文整理匯總了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()
示例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]
示例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()
示例4: anticoupling_law
# 需要導入模塊: import torch [as 別名]
# 或者: from torch import reciprocal [as 別名]
def anticoupling_law(self, a, b):
return torch.mul(a, torch.reciprocal(b))
示例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
示例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)
示例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
示例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
示例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
示例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
示例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)]
示例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
示例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)))
示例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)
示例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)