这是基于Mohammad-Reza Malekpour的答案,但从Vandermonde矩阵中去除了截距列。
import numpy as np
def poly(x, degree):
return np.vander(x, degree + 1, increasing=True)[:, 1:]
例子:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
n = 30
np.random.seed(42)
x = np.random.uniform(0, 1, size=n)
y = 1 + 2 * x + 3 * x**2 + 4 * x**3 + np.random.normal(0, 0.001, size=n)
df = pd.DataFrame({"x": x, "y": y})
results = smf.ols(formula="y ~ poly(x, 3)", data=df).fit()
print(results.summary().tables[1])
=================================================================================
coef std err t P>|t| [0.025 0.975]
---------------------------------------------------------------------------------
Intercept 1.0009 0.001 1599.564 0.000 1.000 1.002
poly(x, 3)[0] 1.9935 0.006 361.673 0.000 1.982 2.005
poly(x, 3)[1] 3.0124 0.013 232.711 0.000 2.986 3.039
poly(x, 3)[2] 3.9919 0.009 463.711 0.000 3.974 4.010
=================================================================================
与之相比:
results = smf.ols(formula="y ~ x + I(x**2) + I(x**3)", data=df).fit()
print(results.summary().tables[1])
==============================================================================
coef std err t P>|t| [0.025 0.975]
Intercept 1.0009 0.001 1599.564 0.000 1.000 1.002
x 1.9935 0.006 361.673 0.000 1.982 2.005
I(x ** 2) 3.0124 0.013 232.711 0.000 2.986 3.039
I(x ** 3) 3.9919 0.009 463.711 0.000 3.974 4.010
==============================================================================
h_hours
的数据类型是什么?如果它被视为分类变量,那么你需要将其转换为浮点数或其他被 patsy 视为数值型的类型。 - Josef