Pearson Correlation Coefficient


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. def pearson(x,y):
  2. n=len(x)
  3. vals=range(n)
  4.  
  5. #regular sums
  6. sumx=sum([float(x[i]) for i in vals])
  7. sumy=sum([float(y[i]) for i in vals])
  8.  
  9. #sum of the squares
  10. sumxSq=sum([x[i]**2.0 for i in vals])
  11. sumySq=sum([y[i]**2.0 for i in vals])
  12.  
  13. #sum of the products
  14. pSum=sum([x[i]*y[i] for i in vals])
  15.  
  16. #do pearson score
  17. num=pSum-(sumx*sumy/n)
  18. den=((sumxSq-pow(sumx,2)/n)*(sumySq-pow(sumy,2))**.5
  19. if den=0: return 1
  20. r=num/den
  21. return r

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.