python如何计算平方_Python lmfit如何计算R平方?

时间:2024-11-20 07:46:27

这可能是个愚蠢的问题,但我在lmfit's documentation中找不到答案。我的问题很简单:如何检索R的平方?(我知道我可以用1 - SS_res / SS_tot手动计算)

更新:

我试着自己计算R平方,并将其与statsmodels中的R平方进行了比较。

两种估计中的参数是相同的,但R平方不是。在

代码:from lmfit import minimize, Parameters

import numpy as np

import as sm

import random

x = (0, 15, 10)

x_ols = sm.add_constant(x)

y = [(0,15) for r in xrange(10)]

model = (y,x_ols)

results = ()

print "OLS: ", format([0], '.5f'), format([1], '.5f'), "R^2: ",

# define objective function: returns the array to be minimized

def fcn2min(params, x, data):

a = params['a'].value

b = params['b'].value

model = a + b * x

return model - data

for i in range(0,1):

# create a set of Parameters

params = Parameters()

('a', value= i)

('b', value= 20)

# do fit, here with leastsq model

result = minimize(fcn2min, params, args=(x, y))

yhat = params['a'].value + params['b'].value * x

ybar = (y)/len(y)

ssreg = ((yhat-ybar)**2) # or sum([ (yihat - ybar)**2 for yihat in yhat])

sstot = ((y - ybar)**2) # or sum([ (yi - ybar)**2 for yi in y])

r2 = ssreg / sstot

print "lmfit: ", format(params['a'].value, '.5f'), format(params['b'].value, '.5f'), "R^2: ", r2