Skip to main content
 首页 » 编程设计

python之Pandas OLS 的替代品

2024年12月31日8三少

我想在 Pandas 系列中制作趋势线。 我喜欢使用 pandas.ols 完成的方式 pandas.ols

目前最好的替代品是什么

请您参考如下方法:

下面是使用 StatsModels 中的线性回归包的示例

这显示了随机生成的数据集的一阶、二阶和三阶多项式拟合(使用普通最小二乘法)。

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
import statsmodels.formula.api as smf 
 
np.random.seed(654123) 
 
# generate a random dataset with heteroscedasticity 
nobs = 1000 
x = np.random.uniform(-4, 4, nobs) 
y = x + 0.25 * x**2 + 0.1 * np.exp(1 + np.abs(x)) * np.random.randn(nobs) 
 
df = pd.DataFrame({'predictor': x, 'response': y}) 
 
x1 = pd.DataFrame({'predictor': np.linspace(df.predictor.min(), df.predictor.max(), nobs)}) 
 
poly_1 = smf.ols(formula='response ~ 1 + predictor', data=df).fit() 
poly_2 = smf.ols(formula='response ~ 1 + predictor + I(predictor ** 2.0)', data=df).fit() 
poly_3 = smf.ols(formula='response ~ 1 + predictor + I(predictor ** 2.0) + I(predictor ** 3.0)', data=df).fit() 
 
plt.figure(figsize=(9 * 1.618, 9)) 
plt.plot(x1.predictor, poly_1.predict(x1), 'r-',  
         label='1st order poly fit, $R^2$=%.2f' % poly_2.rsquared) 
plt.plot(x1.predictor, poly_2.predict(x1), 'b-',  
         label='2nd order poly fit, $R^2$=%.2f' % poly_2.rsquared) 
plt.plot(x1.predictor, poly_3.predict(x1), 'g-',  
         label='3rd order poly fit, $R^2$=%.2f' % poly_2.rsquared) 
 
plt.plot(x, y, 'o', alpha=0.2) 
plt.legend(loc="upper center", fontsize=14) 

scipy.stats.linregress是您可以探索的另一个不错的选择。