R:难以生成 0 和 1 之间的正交多项式

R: difficulties generating orthogonal polynomials between 0 and 1

我正在尝试对区间为 [0,1] 的变量进行一些回归。我想包括正交二次和三次分量。我之后的多项式是 Shifted Legendre polynomials(Wikipedia).

我对 R 中 poly() 函数的行为感到困惑。 它不仅 return 不是 [0,1] 中的向量,它 做的向量 return 随输入向量的长度而变化。

此代码生成说明性示例。该代码从 x 生成一些一阶多项式(线)。结果多项式的区间范围从 [-0.36,0.36] 到 [-0.017,0.017].

x <- seq(0,1,by = 0.1) # base variable
plot(x,x,col=2)

M<-matrix(nrow=6,ncol=4)
dfpoly<-data.frame(M)

v<- c(0.05,0.01,0.005,0.001,0.0005,0.0001) # This vector alters the length of x

for (i in 1:length(v)){
    x <- seq(0,1,by = v[i])
    y <- poly(x,degree = 3)[,1] #first order polynomial, should in my mind be the same as x
    points(x,y)
    dfpoly[i,1] <- length(x)
    dfpoly[i,2] <- min(y)
    dfpoly[i,3] <- max(y)
    dfpoly[i,4] <- mean(diff(y)/diff(x))
    }
names(dfpoly) <- c("x length","y min","y max","y slope")
dfpoly

graph of x vs generated first order polynomials

输出摘要:

  x length          y min         y max       y slope
1       21 -0.36037498508 0.36037498508 0.72074997016
2      101 -0.17064747029 0.17064747029 0.34129494057
3      201 -0.12156314064 0.12156314064 0.24312628128
4     1001 -0.05469022724 0.05469022724 0.10938045447
5     2001 -0.03870080906 0.03870080906 0.07740161813
6    10001 -0.01731791041 0.01731791041 0.03463582082

现在,我希望所有的线都位于与 x 相同的区间 [0,1] 内,并且与图表上的 x(红色点系列)完全重叠。但他们没有。它们也没有任何我可以用肉眼识别的图案。

1. poly() 的奇怪间隔行为的原因是什么?

2。我可以使用其他技术或函数将这些多项式强制为 [0,1] 吗?

poly() 函数 returns 一个矩阵,其列是在 x 的值处评估的多项式的值。从帮助页面 ?poly 可以看出,列相互正交,并且也与常数多项式 p(x) = 1 正交。正交性在向量意义上(即 $\sum x_i y_i = 0$)。

我认为帮助页面不能保证这一点,但实际上列似乎也是单位长度,即 $\sum x_i^2 = 1$.

单位长度条件解释了你的"weird interval behaviour"。更多项意味着它们必须更小才能使平方和仍然等于 1。

要将列强制到范围 [0,1],只需减去最小值并除以范围。这将失去正交性和单位长度属性,但是 将保持度数和线性独立性。

例如,

x <- seq(0,1,by = 0.1) # base variable
plot(x,x,col=2)

M<-matrix(nrow=6,ncol=4)
dfpoly<-data.frame(M)

v<- c(0.05,0.01,0.005,0.001,0.0005,0.0001) # This vector alters the length of x

for (i in 1:length(v)){
        x <- seq(0,1,by = v[i])
        y <- poly(x,degree = 3)[,1] #first order polynomial, should in my mind be the same as x
        y <- (y - min(y))/diff(range(y))
        points(x,y)
        dfpoly[i,1] <- length(x)
        dfpoly[i,2] <- min(y)
        dfpoly[i,3] <- max(y)
        dfpoly[i,4] <- mean(diff(y)/diff(x))
}
names(dfpoly) <- c("x length","y min","y max","y slope")
dfpoly

这会打印

  x length y min y max y slope
1       21     0     1       1
2      101     0     1       1
3      201     0     1       1
4     1001     0     1       1
5     2001     0     1       1
6    10001     0     1       1