python - 使用 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 及以后似乎是一个起点,但我对如何应用它感到困惑。
解决方案
推荐阅读
- cython - Cython:是否有将多个 pyx 文件编译成一个扩展模块的用例
- c# - db 的返回值为 null
- bash - 在脚本中使用 docker run 超时
- java - 在 Java Spring Boot 中用两种不同类型的两个 findAll() 填充 DTO
- c - 我可以在信号处理程序中执行 free() 或 close() 吗?
- google-api - 带有 files.get 的 Google Drive API 迁移到 HTTP“webViewLink” - 如何绕过 100mb 病毒页面?
- python - builtins.ValueError:0 不在列表中
- python - 按条件替换数据框中的值与最后一行值的差异
- git - 在跟踪非常大的文件时保持 .git 文件夹的大小较小
- r - 如果满足 dplyr 过滤条件,则更新变量