R-squared, the degree of correlation, the correlation coefficient between two variables, positive correlation negative correlation sample code (to python3)

Code:

 1 # -*- coding:utf-8 -*-
 2 
 3 import numpy as np
 4 import math
 5 
 6 
 7 # 相关度
 8 def computeCorrelation(X, Y):
 9     xBar = np.mean(X)
10     yBar = np.mean(Y)
11     SSR = 0
12     varX = 0
13     varY = 0
14     for i in range(0, len(X)):
15         diffXXbar = X[i] - xBar
16         diffYYbar = Y[i] -ybar
 . 17          the SSR + = (* diffXXbar diffYYbar)
 18 is          varX diffXXbar ** 2 = +
 . 19          Vary diffYYbar ** + 2 =
 20 is      the SST = Math.sqrt (varX * Vary)
 21 is      return the SSR / the SST
 22 is  
23 is  
24  
25  
26 is  # Print ( "correlation R & lt:", computeCorrelation (testX, testy)) 
27  # affinity R & lt: .940310076545 
28  
29  # R & lt square 
30  # simple linear regression: 
31 is  # Print ( "R & lt ^ 2:", STR (computeCorrelation (testX, testy ) ** 2)) 
32  # R & lt ^ 2: 0.884183040052
33 is  
34 is  # plurality of arguments x: 
35  DEF polyfit (x, Y, Degree):   # Degree number argument x 
36      Result = {}
 37 [      coeffs = np.polyfit (x, Y, Degree)
 38 is      Result [ ' Polynomial ' ] = coeffs.tolist ()
 39  
40      P = np.poly1d (coeffs)
 41 is      yhat = P (X)
 42 is      ybaR = np.sum (Y) / len (Y)
 43 is      ssreg np.sum = ((yhat - ybaR ) ** 2 )
 44 is      sstot np.sum = ((Y - ybaR) ** 2 )
 45     result['determination'] = ssreg / sstot
46 
47     return result
48 
49 # 测试
50 testX = [1, 3, 8, 7, 9]
51 testY = [1,1,1,1,1]
52 
53 inf=float("inf")
54 ninf=float("-inf")
55 nan=float("nan")
56 result=polyfit(testY, testX, 1)["determination"]
57 
58 print(inf)
59 if result == inf:
60     print("PPPP")
61 # 测试
62 print(result)
63 # r^2:0.884183040052

 

Guess you like

Origin www.cnblogs.com/smartisn/p/12596092.html