text: '''
  Code of 'Remote Photoplethysmograph Signal Measurement from Facial Videos Using Spatio-Temporal Networks'
  By Zitong Yu, 2019/05/05
  If you use the code, please cite:
  @inproceedings{yu2019remote,
      title={Remote Photoplethysmograph Signal Measurement from Facial Videos Using Spatio-Temporal Networks},
      author={Yu, Zitong and Li, Xiaobai and Zhao, Guoying},
      booktitle= {British Machine Vision Conference (BMVC)},
      year = {2019}
  }
  Only for research purpose, and commercial use is not allowed.
  MIT License
  Copyright (c) 2019
  '''
  import torch.nn as nn
  import torch
  
  
  class NegPearson(nn.Module):  # Pearson range [-1, 1] so if < 0, abs|loss| ; if >0, 1- loss
      def __init__(self):
          super(NegPearson, self).__init__()
          return
  
      def forward(self, preds, labels):  # tensor [Batch, Temporal]
          loss = 0
          for i in range(preds.shape[0]):
              sum_x = torch.sum(preds[i])  # x
              sum_y = torch.sum(labels[i])  # y
              sum_xy = torch.sum(preds[i] * labels[i])  # xy
              sum_x2 = torch.sum(torch.pow(preds[i], 2))  # x^2
              sum_y2 = torch.sum(torch.pow(labels[i], 2))  # y^2
              N = preds.shape[1]
              pearson = (N * sum_xy - sum_x * sum_y) / (
                  torch.sqrt((N * sum_x2 - torch.pow(sum_x, 2)) * (N * sum_y2 - torch.pow(sum_y, 2))))
  
              loss += 1 - pearson
  
          loss = loss / preds.shape[0]
          return loss
  
  
  