【问题标题】:Error: number of observations in y not equal to the number of rows of x错误:y 中的观察数不等于 x 的行数
【发布时间】:2020-03-19 07:31:06
【问题描述】:

这是我的代码:

ames_train_x <- model.matrix(Value ~ ., train)[, -1]
ames_train_y <- log(train$Value)

ames_test_x <- model.matrix(Value ~ ., test)[, -1]
ames_test_y <- log(test$Value)

# Applying LASSO REGRESSION to data

ames_lasso <- glmnet(
  x = ames_train_x,
  y = ames_train_y,
  alpha = 1
)

我收到以下错误:

glmnet 中的错误(x = ames_train_x,y = ames_train_y,alpha = 1): y 中的观察数(3528)不等于 x 的行数(3527)

我做错了什么?

【问题讨论】:

  • 在做矩阵乘法 AB 时,A 中的列数应该等于 B 中的行数。看起来你在这里遇到了类似的问题。
  • 如果您提供您的traintest 数据,或许我们可以为您提供帮助。

标签: r regression glmnet


【解决方案1】:

您很可能在 train 中有 NA 值,model.matrix 会抛出带有 NA 的行,请参见下面的 mtcars 示例:

library(glmnet)
df <- mtcars
train_x <- model.matrix(mpg ~ ., df)[, -1]
dim(train_x)
1] 32 10
train_y <- log(df$mpg)
fit = glmnet(y=train_y,x=train_x)

# now we set 1 value to be NA
df["Fiat 128","cyl"]<-NA
train_x <- model.matrix(mpg ~ ., df)[, -1]
Fiat 128" %in% rownames(train_x)
[1] FALSE
dim(train_x)
1] 31 10

拟合这个,会给你你看到的错误:

fit = glmnet(y=train_y,x=train_x)
Error in glmnet(y = train_y, x = train_x) : 
  number of observations in y (32) not equal to the number of rows of x (31)

【讨论】:

    猜你喜欢
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多