Search code examples
pythonnumpypytorchtensorweighted-average

Weighted Average of PyTorch Tensors


I have two Pytorch tensors of the form [y11, y12] and [y21, y22]. How do I get the weighted mean of the two tensors?


Solution

  • you can add two tensors using torch.add and then get the mean of output tensor using torch.mean assuming weight as 0.6 for tensor1 and 0.4 for tensor2 example:

    tensor1 = [y11, y12] * 0.6 # multiplying with weight
    tensor2 = [y21, y22] * 0.4 # multiplying with weight
    pt_addition_result_ex = tensor1.add(tensor2) # addition of two tensors
    
    torch.mean(pt_addition_result_ex) # mean of output tensors