简体   繁体   English

R中脊回归的预测

[英]Predictions of ridge regression in R

I've been really stuck on this, hope anyone can help me! 我一直坚持这个,希望有人能帮助我! I have a dataset with 54 columns and I want to make predictions on a test set with ridge regression. 我有一个包含54列的数据集,我想在使用岭回归的测试集上进行预测。

nn <-nrow(longley)
index <- 1:nrow(longley)
testindex <- sample(index, trunc(length(index)/3))
testset <- longley[testindex,]
trainset <-longley[-testindex,]
trainset1 <- trainset[,-7]

# Fit the ridge regression model:

mod <- lm.ridge(y ~., data = trainset, lambda = 0.661)

# Predict and evaluate it by using MAE function:

mae <- function(model) {
  y = trainset$Employed  
  y.pred <- predict(model, trainset)
  return(mean(abs(y-y.pred)))
}

When I do this I get the following error message: 当我这样做时,我收到以下错误消息:

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

What could be another way to make predictions with ridge regression that works (also with evaluation metrics such as rsquared and MAE)? 什么可能是使用岭回归进行预测的另一种方法(也有评估指标,如rsquared和MAE)?

There is indeed no predict method for ridgelm object: you will have to do it by hands. 确实没有ridgelm物体的predict方法:你必须用手去做。 By the way, there is neither summary as you can see with: 顺便说summary ,你看不到任何summary

> methods(class = 'ridgelm')
[1] coef   plot   print  select

This is linear model, so that fitting is just a question of matricial computation: 这是线性模型,因此拟合只是一个基本计算的问题:

y.pred <- as.matrix(cbind(const=1,trainset)) %*% coef(model)

We need to add the constant 1 to be associated with the constant coefficient of the linear mode. 我们需要将常数1加到与线性模式的常系数相关联。

Important: to use ridge regression, one usually scale explanatory variables, so that means are substracted. 重要提示:使用岭回归,通常可以缩放解释变量,从而减少均值。 The best practice should be to learn scaling definition from training and then to use training set means to center variables from new data. 最佳实践应该是从训练中学习缩放定义,然后使用训练集方法来中心来自新数据的变量。 You may be interested in this related post on cross-validated: 您可能对这个相关的交叉验证帖子感兴趣:

https://stats.stackexchange.com/questions/152203/how-to-calculate-predicted-values-using-an-lm-ridge-object https://stats.stackexchange.com/questions/152203/how-to-calculate-predicted-values-using-an-lm-ridge-object

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

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