简体   繁体   English

岭回归 - 如何从ridgelm对象创建lm对象

[英]Ridge regression - how to create lm object from ridgelm object

I am having problems with creating lm object from the ridgelm object. 我在从ridgelm对象创建lm对象时遇到问题。

x1 <- rnorm(20)
x2 <- rnorm(20, mean=x1, sd=.01)
y <- rnorm(20, mean=2+x1+x2)
data <- data.frame(x1=x1, x2=x2, y=y)
model <- lm.ridge(y~x1+x2, lambda=1, data=data)

predict(model, newdata = data)

Gives an error: 给出错误:

Error in UseMethod("predict") : 
  no applicable method for 'predict' applied to an object of class "ridgelm"

I am trying to create a lm object from the ridgelm in order to use it with predict function. 我试图从ridgelm创建一个lm对象,以便将它与预测函数一起使用。 That turns out to be more difficult than I expected. 结果证明比我预期的要困难。

My attempt: 我的尝试:

m <- lm(y~x1+x2, data=data)
m$coefficients[["r1"]] <- model$coef[["r1"]]
m$coefficients[["r2"]] <- model$coef[["r1"]]
m$coefficients[["r3"]] <- model$coef[["r3"]]
m$coefficients[["(Intercept)"]] <- ???

Somehow I am unable to read the intercept from lm.ridge model. 不知怎的,我无法从lm.ridge模型中读取拦截。

Since you are working with a linear model, I think the solution is a simple matrix product of the coefficients and your new data. 由于您正在使用线性模型,我认为该解决方案是系数和新数据的简单矩阵乘积。

Note that you have to add a column consisting entiry of 1, indicating the intercept, to correspond to the first model coefficient. 请注意,您必须添加一个包含1的entiry列,表示截距,以对应第一个模型系数。

Try this: 尝试这个:

set.seed(1)
newdat <- data.frame(1, x1 = rnorm(5), x2=rnorm(5))
as.matrix(newdat) %*% coef(model)

          [,1]
[1,] 0.1648573
[2,] 2.5017097
[3,] 1.7058644
[4,] 4.0967116
[5,] 1.7597485

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM