首页 > 解决方案 > 使用 pandas 数据框和 numpy 进行多项式拟合

问题描述

我有一个脚本,我在其中获取一个数据框,它看起来像这样:

在此处输入图像描述

并将一些列转换为 numpy 数组进行处理。然后,我使用我编写的一个小函数statsmodels.api来计算基于我传递给函数的两个数组的线性回归。然后该函数返回统计数据和线性拟合方程:

def computeLinearStats(x, y, yName, calc_tau = False):
    '''
    Takes as an argument two numpy arrays, one for x and one y, and a string for the
    name of the y-variable, and a boolean for whether to calculate tau.
    Uses Ordinary Least Squares to compute the statistical parameters for the
    array against log(z), and determines the equation for the line of best fit.
    Returns the results summary, residuals, statistical parameters in a list,
    the best fit equation, and Kendall's tau.
    '''

    #   Mask NaN values in both axes
    mask = ~np.isnan(y) & ~np.isnan(x)
    #   Compute model parameters
    model = sm.OLS(y[mask], sm.add_constant(x[mask]), missing= 'drop')
    results = model.fit()
    residuals = results.resid
    if calc_tau:
        tau = stats.kendalltau(x, y, nan_policy= 'omit')
    else:
        tau = [1, 1]    #   Use this to exclude computation of tau
#    

    #   Compute fit parameters
    params = stats.linregress(x[mask], y[mask])
    fit = params[0]*x + params[1]
    fitEquation = '$(%s)=(%.4g \pm %.4g) \\times log_{10}(redshift)+%.4g$'%(yName,
                    params[0],  #   slope
                    params[4],  #   stderr in slope
                    params[1])  #   y-intercept
    return results, residuals, params, fit, fitEquation, tau

例如,假设我正在从数据帧中寻找loz(z)和“BI”之间的线性拟合。计算完这些变量后,我会调用

results, residuals, params, fit, equation, tau = qf.computeLinearStats(log_z, (B-I), 'B-I', calc_tau = False)

得到线性拟合。

一切正常,但现在我需要拟合多项式而不是线性拟合。

我试过了

sources['log_z'] = np.log10(sources.z)
mask = ~np.isnan((B-I)) & ~np.isnan(log_z)
model = ols(formula='(B-I) ~ log_z', data = [log_z[mask], (B-I) 
[mask]]).fit()

model = ols(formula='(B-I) + np.power((U-R),2) ~ log_z', data = [log_z[mask], (B-I)[mask]]).fit()

但我明白了

PatsyError: Error evaluating factor: TypeError: list indices must be integers or slices, not str
    (B-I) ~ log_z
            ^^^^^

即使 x 和 y 都是数组,而不是字符串。

在这种情况下找到多项式拟合的最简单方法是什么——比如(B-I) + (U-R)**2反对log(z)本网站上的幻灯片 41 及以后似乎是一个起点,但我对如何应用它感到困惑。

标签: pythonpandasnumpystatsmodelsdata-fitting

解决方案


推荐阅读