在 Python 中,如何拟合最小分位数 b 样条回归线?



你可以像这样找到最小分位数回归线拟合:

import statsmodels.api as sm
import statsmodels.formula.api as smf
from statsmodels.regression.quantile_regression import QuantReg
mod = smf.quantreg('y ~ x', data)
res = mod.fit(q = 0.000001)

但是,如果您想找到最小 b 样条回归拟合线怎么办?

如果你想要三次 b 样条,你可以这样做:

#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import statsmodels.formula.api as smf

x = np.linspace(0, 2, 100)
y = np.sqrt(x) * np.sin(2 * np.pi * x) + np.random.random_sample(100)
mod = smf.quantreg('y ~ bs(x, df=9)', dict(x=x, y=y))
res = mod.fit(q=0.000001)
print(res.summary())
plt.plot(x, y, '.')
plt.plot(x, res.predict(), 'r')
plt.show()

您需要使用自由度(df参数(或指定knots参数。根据您的数据,您可能希望对自然三次样条使用cr()或对循环三次样条使用cc()。有关更多详细信息,请参阅 http://patsy.readthedocs.io/en/latest/spline-regression.html。

最新更新