我正在尝试将此功能移植到 python 中
> x <- 0:10
> y <- x**2
> lm(y ~ ns(x,df=2))
如:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
x = pd.DataFrame(np.arange(11))
y = x**2
formula="y ~ cr(x, df = 3)"
reg = smf.ols(formula,data=x).fit()
print(res.summary())
但是使用这个 python 公式,我无法设置 df<3. Any suggestions how I can have a natural spline in python with two degrees of freedom, and use it in patsy as an R style equation?
这些显然产生了不同的基础:我不确定有什么区别。自然(边界处的线性约束)与无约束?
x <- 0:10
X1 <- model.matrix(~splines::ns(x, df = 3))
matplot(x, X1, type = "l")
import numpy as np
import pandas as pd
import patsy
import matplotlib.pyplot as plt
x = np.arange(11)
X2 = patsy.dmatrix(
'cr(x, df = 3)',
{'x': x}, return_type='dataframe')
plt.plot(X2)