一组R ^ 2值

时间:2014-11-02 13:28:03

标签: python

我有一个函数,用于计算指定度数的给定x和y数据集的R ^ 2值:

import numpy as np

# Polynomial Regression
    def polyfit(x,y,degree):
    coeffs = np.polyfit(x, y, degree)

# Polynomial Coefficients
    results = coeffs.tolist()
# r-squared
    p = np.poly1d(coeffs)
# fit values, and mean
    yhat = p(x)                         # or [p(z) for z in x]
    ybar = np.sum(y)/len(y)          # or sum(y)/len(y)
    ssreg = np.sum((yhat-ybar)**2)   # or sum([ (yihat - ybar)**2 for yihat in yhat])
    sstot = np.sum((y - ybar)**2)    # or sum([ (yi - ybar)**2 for yi in y])
    r2= ssreg / sstot

    results=r2

return results

我尝试将此函数用于一组示例数据:

x = np.arange(1,5)
y = np.arange(1,5)

print polyfit(x,y,1)

>>1.0

到目前为止一切顺利。我现在的问题是我想通过迭代来改变度数(polyfit函数的第3个参数)。我正在考虑使用

n=np.linspace(1,9,100)

并且对于n的每个值,我可以获得r ^ 2值,然后将其存储到数组中。

r2= [] #array for each r^2 value for each value of n in linspace

有人可以帮我这个吗?我是python中的新手,我仍然很难进行迭代。谢谢。

1 个答案:

答案 0 :(得分:0)

   linspace中每个n值的每个r ^ 2值的数组

你可以把它写成列表理解:

r2 = [polyfit(x, y, n) for n in np.linspace(1,9,100)]

转换为numpy数组并不难:

r2 = np.array(r2)