Python 線性回歸計(jì)算r-squared方法

背景

計(jì)算線性回歸ab值后,希望計(jì)算r-squared,對(duì)比是否為最佳擬合

Excel擬合

數(shù)據(jù)源

擬合結(jié)果

Python擬合

import math
import numpy as np
from scipy import stats

testX = [174.5,171.2,172.9,161.6,123.6,112.1,107.1,98.6,98.7,97.5,95.8,93.5,91.1,85.2,75.6,72.7,68.6,69.1,63.8,60.1,65.2,71,75.8,77.8]
testY = [88.3,87.1,88.7,85.8,89.4,88,83.7,73.2,71.6,71,71.2,70.5,69.2,65.1,54.8,56.7,62,68.2,71.1,76.1,79.8,80.9,83.7,85.8]
 
def computeCorrelation(X, Y):
    xBar = np.mean(X)
    yBar = np.mean(Y)
    SSR = 0
    varX = 0
    varY = 0
    for i in range(0 , len(X)):
        diffXXBar = X[i] - xBar
        diffYYBar = Y[i] - yBar
        SSR += (diffXXBar * diffYYBar)
        varX +=  diffXXBar**2
        varY += diffYYBar**2
    
    SST = math.sqrt(varX * varY)
    print ("使用math庫(kù):r:", SSR / SST,"r-squared:", (SSR / SST)**2)
    return 
 
computeCorrelation(testX, testY)

x = np.array(testX)
y = np.array(testY)
#擬合 y = ax + b
poly = np.polyfit(x, y, deg=1)
print("使用numpy庫(kù):a:" + str(poly[0]) + ",b:" + str(poly[1]))


def rsquared(x, y): 
    slope, intercept, r_value, p_value, std_err = stats.linregress(x, y) 
    #a、b、r
    print("使用scipy庫(kù):a:",slope,"b:", intercept,"r:", r_value,"r-squared:", r_value**2)

rsquared(testX, testY)
Python擬合結(jié)果

相關(guān)鏈接

我如何使用Python和Numpy來(lái)計(jì)算r-squared

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容