2011-12-10 97 views
12

我試圖在數據集上使用glmnet包。我使用cv.glmnet()獲得glmnet()的lambda值。我將1,2,7,12列排除在外:id列,響應列,包含NA,幷包含NA。R glmnet as.matrix()錯誤信息

這裏的數據集和錯誤消息:

> head(t2) 
    X1 X2  X3 X4 X5   X6 X7 X8 X9 X10 X11 X12 
1 1 1 0.7661266 45 2 0.80298213 9120 13 0 6 0 2 
2 2 0 0.9571510 40 0 0.12187620 2600 4 0 0 0 1 
3 3 0 0.6581801 38 1 0.08511338 3042 2 1 0 0 0 
4 4 0 0.2338098 30 0 0.03604968 3300 5 0 0 0 0 
5 5 0 0.9072394 49 1 0.02492570 63588 7 0 1 0 0 
6 6 0 0.2131787 74 0 0.37560697 3500 3 0 1 0 1 
> str(t2) 
'data.frame': 150000 obs. of 12 variables: 
$ X1 : int 1 2 3 4 5 6 7 8 9 10 ... 
$ X2 : int 1 0 0 0 0 0 0 0 0 0 ... 
$ X3 : num 0.766 0.957 0.658 0.234 0.907 ... 
$ X4 : int 45 40 38 30 49 74 57 39 27 57 ... 
$ X5 : int 2 0 1 0 1 0 0 0 0 0 ... 
$ X6 : num 0.803 0.1219 0.0851 0.036 0.0249 ... 
$ X7 : int 9120 2600 3042 3300 63588 3500 NA 3500 NA 23684 ... 
$ X8 : int 13 4 2 5 7 3 8 8 2 9 ... 
$ X9 : int 0 0 1 0 0 0 0 0 0 0 ... 
$ X10: int 6 0 0 0 1 1 3 0 0 4 ... 
$ X11: int 0 0 0 0 0 0 0 0 0 0 ... 
$ X12: int 2 1 0 0 0 1 0 0 NA 2 ... 

> cv1 <- cv.glmnet(as.matrix(t2[,-c(1,2,7,12)]), t2[,2], family="binomial") 
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: invalid class 'NA' to dup_mMatrix_as_dgeMatrix 
> cv1 <- cv.glmnet(as.matrix(t2[,-c(1,2,7,12)]), t2[,2], family="multinomial") 
Error in t(.Call(Csparse_dense_crossprod, y, t(x))) : 
    error in evaluating the argument 'x' in selecting a method for function 't': Error: invalid class 'NA' to dup_mMatrix_as_dgeMatrix 

有什麼建議?

+8

我自己的想法。而不是as.matrix()我需要使用:data.matrix()。 – screechOwl

+0

我對這個軟件包不太熟悉,但它看起來像是在方程兩邊提供了二項式響應... x = t [,c(1,2,7,12)] AND y = t [,2] ...如果你注意到你的模型看起來太好,那麼這可能是爲什麼。 –

+0

不知道是否有圖形錯誤,但輸入向量是x = t [, - c(1,2,7,12)]。 c()前面的' - '表示排除這些列並保留其他所有內容,所以響應只應該在等式的一邊。 – screechOwl

回答

15

出於某種原因glmnet喜歡data.matrix()as.matrix()

cv1 <- cv.glmnet(data.matrix(t2[,-c(1,2,7,12)]), t2[,2], family="multinomial") 

應該做的工作。

4

我得到了同樣的錯誤消息。不幸的是,它不像使用data.matrix()那麼簡單。

錯誤發生在輸入矩陣和模型係數的交叉積中。

在predict.glmnet:

nfit = as.matrix(cbind2(1下一頁末)%。*%nbeta)

什麼解決了這個問題對我來說是迫使X的dgCMatrix 。我嚴重不明白爲什麼,但它對我有用。

predict(object = lm, newx = as(x, "dgCMatrix"), type = "response") 

因爲我還沒有看到本作中的許多問題之一關於這個錯誤我想我會在這裏發佈一個答案。

+1

爲了給未來的人添加這個功能,我碰到了同樣的問題,並且使用as(x,「dgCMatrix」)和as.vector(分類)結合起來看起來有效。 示例代碼: cvfit = cv.glmnet(x = as(data,「dgCMatrix」),y = as.vector(classification),family =「binomial」) –

3

使用cv.glmnet時,我有類似的錯誤信息。 cv.glmnet會在RStudio中正確運行,但在使用Rscript時會失效。對我來說,倫敦定盤添加到我的腳本的頂部:

require(methods)

看來,「glmnet」包可能是使用從「方法」包中的一些功能,但是這個包是不是在裝啓動時使用Rscript。然而,正常裝載的「方法」包被默認R.

下面是關於這個RSCRIPT功能的信息:

Rscript does not load methods package, R does -- why, and what are the consequences?

我希望這可以幫助別人運行到,我也做了同樣的問題。

+0

這是值得加票的,它解決了我的問題。 –