Python自然样条函数cr在patsy中只接受3个或更多的自由度,而R中的ns接受2

问题描述 投票:0回答:1

我正在尝试将此功能移植到 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?

python r spline patsy
1个回答
0
投票

这些显然产生了不同的基础:我不确定有什么区别。自然(边界处的线性约束)与无约束?

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)

© www.soinside.com 2019 - 2024. All rights reserved.