r - 错误:y 中的观察数不等于 x 的行数
问题描述
这是我的代码:
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) 的行数
我究竟做错了什么?
解决方案
很可能您在 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)
推荐阅读
- javascript - how do I run code after the last element has completed its jQuery slideup effect?
- html - 如何在 ruby on rails 的 2 个字符串之间插入和变量
- arrays - 无法访问 AWS Athena 中的数组元素
- json - 带有 JSON ObservedObject 的 SwiftUI
- python - Python OpenCV 无法识别我的第二个网络摄像头 [已关闭]
- mysql - MySQL Multiple SELECT 与 WHERE 一起使用
- c# - 在 C# 中使用 FsCheck.Xunit 调整字符串生成器以避免“\0”
- ios - 如何使 navigationItem.backbarbuttonitem 与前一个视图的 navigationItem 的标题不同?
- cocoa - 如何使用自动布局调整 NSWindow 的大小?
- terraform - 如何从 terraform 状态中删除资源?