Вопрос

I am trying to predict a car's mpg based on a number of variables by using ridge regression in R's glmnet package. I have already separated the data into training and test data and dummy coded the categorical variables.

I fit a cross-validation model as follows:

require("glmnet")

x <- as.matrix(data.frame(cylinderDummy[,2:ncol(cylinderDummy)], trainData$displacement,
            trainData$horsepower, trainData$weight, trainData$acceleration,
            originDummy[,2:ncol(originDummy)]))
y <- trainData$mpg
cv.fit <- cv.glmnet(x, y, alpha = 1, nfolds=5,type.measure="mse")

That's all well and good, however, the problem occurs when I attempt to use the predict() function on the test data from the fitted model:

prediction <- predict(cv.fit, testData$mpg, s="lambda.1se")

I get the following error:

Error in as.matrix(cbind2(1, newx) %*% nbeta) : 
error in evaluating the argument 'x' in selecting a method for function 'as.matrix': 
Error in t(.Call(Csparse_dense_crossprod, y, t(x))) : 
error in evaluating the argument 'x' in selecting a method for function 't': 
Error: Cholmod error 'X and/or Y have wrong dimensions' at file
../MatrixOps/cholmod_sdmult.c, line 90

Can anyone tell me what I'm doing wrong?? Thank you!

Это было полезно?

Решение

prediction <- predict(cv.fit, testData$mpg, s="lambda.1se")

It seems that testData$mpg is a vector, model should use the whole testdata set to predict instead of the single mpg values.

In your case, it should be something like

testdata <- as.matrix(data.frame(cylinderDummy[,2:ncol(cylinderDummy)], testData$displacement,
        testData$horsepower, testData$weight, testData$acceleration,
        originDummy[,2:ncol(originDummy)]))
prediction <- predict(cv.fit, testData, s="lambda.1se")
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top