r glmnet错误:对象无法强制输入'double'

时间:2017-04-04 01:44:22

标签: r error-handling glmnet

我正在尝试获取lambda值,我发现了这个问题:R glmnet : "(list) object cannot be coerced to type 'double' "

然而无法弄清楚如何使其适用。这是代码:

faba <- read.table("abalone.txt",sep=",")
faba$y <- ifelse(faba$V9>9,1,0)
head(faba)

xtrain <- faba[1:3133,1:8]
ytrain <- faba[1:3133,10]
xtest <- faba[-c(1:3133),1:8]
ytest <- faba[-c(1:3133),10]


#find mean, std in xtrain
mean_xtrain <- sapply(xtrain[2:8], mean)
sd_xtrain <- sapply(xtrain[2:8], sd)


ytrain_norm <- as.factor(ytrain)
ytest_norm <- as.factor(ytest)


#standardise xtrain with overall mean,sd
xtrain_norm <- faba[1:3133,1:8]
for(i in c(2,3,4,5,6,7,8)){
  xtrain_norm[i] <- (xtrain_norm[i]-mean_xtrain[i-1])/sd_xtrain[i-1]
}


#standardise xtest with xtrain mean,sd
xtest_norm <- faba[-c(1:3133),1:8]
for(i in c(2,3,4,5,6,7,8)){
  xtest_norm[i] <- (xtest_norm[i]-mean_xtrain[i-1])/sd_xtrain[i-1]
}


cvstd <- cv.glmnet(xtrain_norm, ytrain, family = "binomial", 
                   alpha = 0, nfolds = 10, type.measure = "class")

然后我得到错误:

Error in lognet(x, is.sparse, ix, jx, y, weights, offset, alpha, nobs,  : 
  (list) object cannot be coerced to type 'double'

我无法弄清楚如何解决这个问题。这个错误甚至意味着什么?任何提示将不胜感激!
 这就是数据的样子:

> head(faba)
  V1    V2    V3    V4     V5     V6     V7    V8 V9 y
1  M 0.455 0.365 0.095 0.5140 0.2245 0.1010 0.150 15 1
2  M 0.350 0.265 0.090 0.2255 0.0995 0.0485 0.070  7 0
3  F 0.530 0.420 0.135 0.6770 0.2565 0.1415 0.210  9 0
4  M 0.440 0.365 0.125 0.5160 0.2155 0.1140 0.155 10 1
5  I 0.330 0.255 0.080 0.2050 0.0895 0.0395 0.055  7 0
6  I 0.425 0.300 0.095 0.3515 0.1410 0.0775 0.120  8 0

1 个答案:

答案 0 :(得分:0)

faba <- read.table("abalone.txt",sep=",")
faba$y <- ifelse(faba$V9>9,1,0)
head(faba)

xtrain <- faba[1:3133,1:8]
ytrain <- faba[1:3133,10]
xtest <- faba[-c(1:3133),1:8]
ytest <- faba[-c(1:3133),10]

#find mean, std in xtrain
(mean_xtrain <- sapply(xtrain[2:8], mean))
(sd_xtrain <- sapply(xtrain[2:8], sd))

#standardise xtrain with overall mean,sd
xtrain_norm <- cbind(xtrain[,1],scale(xtrain[,2:8]))
ytrain_norm <- as.factor(ytrain) 
#standardise xtest with xtrain mean,sd 
xtest_norm <- faba[-c(1:3133),1:8] 
xtest_norm <- cbind(xtest_norm[,1],scale(xtest_norm[,2:8],center=mean_xtrain,scale=sd_xtrain)) 
ytest_norm <- as.factor(ytest)

这允许具有glmnet

所需的矩阵形式