I would like to replicate making this Q
matrix in python, but I can't seem to make it happen.
min = 0
max = 10
tau = seq(min, max)
pDegree = 5
Q <- splines::ns(tau, pDegree)
print(Q)
Here are some tries in python
import numpy as np
from patsy import dmatrix
from scipy import interpolate
min = 0
max = 10
tau = np.arange(min, max + 1)
pDegree = 5
# try one
spline_basis = dmatrix("bs(x, df=" + str(pDegree) + ", include_intercept=True) - 1", {"x": tau})
print(spline_basis)
# try two
spline_basis = dmatrix("bs(x, df=" + str(pDegree) + ", include_intercept=False) - 1", {"x": tau})
print(spline_basis)
This is the matrix I am getting in R
1 2 3 4 5
[1,] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
[2,] 0.02083333 0.00000000 -0.11620871 0.34862613 -0.23241742
[3,] 0.16666667 0.00000000 -0.16903085 0.50709255 -0.33806170
[4,] 0.47916667 0.02083333 -0.12149092 0.36447277 -0.24298185
[5,] 0.66666667 0.16666667 -0.04225771 0.12677314 -0.08451543
[6,] 0.47916667 0.47916667 0.01406302 0.02031093 -0.01354062
[7,] 0.16666667 0.66666667 0.15476190 0.03571429 -0.02380952
[8,] 0.02083333 0.47916667 0.44196429 0.11160714 -0.05357143
[9,] 0.00000000 0.16666667 0.59523810 0.21428571 0.02380952
[10,] 0.00000000 0.02083333 0.35119048 0.32142857 0.30654762
[11,] 0.00000000 0.00000000 -0.14285714 0.42857143 0.71428571
You have a couple of things going on here
tau
in your R code is 0:11, buttau
in your python code is equivalent to0:10
ns()
in your R code.I've found that I can use dmatrix to replicate the basis as estimated by
mgcv
package.For example:
Python: