Reputation: 2524
I am using the package ridge
to do ridge regression Let's say that I am using the mtcars data and that I want to predict the variable qsec
so I do:
install.packages('ridge')
library(ridge)
library(stats)
library(dplyr) #for the select
data(mtcars)
index=1:floor(0.75*nrow(mtcars))
train=mtcars[index,]
test=select(mtcars[-index,],-qsec)
ridge.model<-linearRidge(qsec~.,data=train)
That seems to work just fine then I can try to predict the next values using predict
function.
qsec.pred<-predict(ridge.model,test)
That works perfectly fine again but when I try to do it with a test of only one row:
qsec.pred.first.row<-predict(ridge.model,test[1,])
I get the following error :
Error in as.matrix(mm) %*% beta : non-conformable arguments
There seems to be a problem with handling data when there is only one line. Do you know a way to fix that ? Or did I do something wrong ?
Upvotes: 1
Views: 727
Reputation: 206197
There does appear to be a bug in the ridge:::predict.ridgeLinear
code. Specifically, when they subset their model matrix, with only one row, they are loosing the proper structure of the matrix.
You can fix it by writing your own version
predict.ridgeLinear <- ridge:::predict.ridgeLinear
body(predict.ridgeLinear)[[7]][[3]] <- quote(mm <- cbind(1, X[, ll, drop=FALSE]))
body(predict.ridgeLinear)[[7]][[4]] <- quote(mm <- X[, ll, drop=FALSE])
environment(predict.ridgeLinear) <- asNamespace("ridge")
This is essentially hacking specific line numbers so it's not very robust. I've only tested in on version ridge_2.1-3
. But, after we define this function, we can call
predict(ridge.model,test[1,])
# Pontiac Firebird
# 17.65554
predict(ridge.model,test[1:2,])
# Pontiac Firebird Fiat X1-9
# 17.65554 19.34306
You may wish to contact the package maintainer if you think this fix should be permanently included in the package. Feel free to refer to this answer.
The other work around would be to always predict more than one row at a time. Even if it's the same row twice.
qsec.pred.first.row <- predict(ridge.model,test[c(1,1),])
Upvotes: 1