标签的长度必须等于输入数据中的行数
The length of labels must equal to the number of rows in the input data
我不知道为什么会出现此错误!我的数据 training
是一个稀疏矩阵。
dim(training)
> 14407 161
dim(label.train)
> 14407 1
xgb.train <- xgb.DMatrix(data = training, label = label.train)
> Error in setinfo.xgb.DMatrix(dmat, names(p), p[[1]]) :
The length of labels must equal to the number of rows in the input data
我检查了我的数据并且:
label.train
是一个 data.frame
training
没有全零行或零列
training
中的所有值都是数字
PS。我的数据很大,所以我无法 post 一个可重现的代码,只需要那些遇到过这个错误的人提供的可能出错的提示。
您收到错误是因为您的标签是 data.frame。将它们作为向量或矩阵传递对我有用。
vec_y <- mtcars$vs
mat_y <- as.matrix(mtcars$vs)
df_y <- mtcars[,8,drop=FALSE] #column vs is the 8th column
x <- as.matrix(mtcars[,-8]) #column vs is the 8th column
#vector labels: works
xgboost::xgb.DMatrix(data=x, label=vec_y)
#matrix labels: works
xgboost::xgb.DMatrix(data=x, label=mat_y)
#df labels: doesnt work
xgboost::xgb.DMatrix(data=x, label=df_y)
很可能您的其他脚本的数据没有任何缺失 (NA) 值。当您将数据帧稀疏(我猜您正在尝试对一个热编码列进行编码)到矩阵时,R 将自动删除缺失值并因此删除错误。
最佳做法是使用“is.na”将所有空值替换为 0。
我不知道为什么会出现此错误!我的数据 training
是一个稀疏矩阵。
dim(training)
> 14407 161
dim(label.train)
> 14407 1
xgb.train <- xgb.DMatrix(data = training, label = label.train)
> Error in setinfo.xgb.DMatrix(dmat, names(p), p[[1]]) :
The length of labels must equal to the number of rows in the input data
我检查了我的数据并且:
label.train
是一个 data.frametraining
没有全零行或零列training
中的所有值都是数字
PS。我的数据很大,所以我无法 post 一个可重现的代码,只需要那些遇到过这个错误的人提供的可能出错的提示。
您收到错误是因为您的标签是 data.frame。将它们作为向量或矩阵传递对我有用。
vec_y <- mtcars$vs
mat_y <- as.matrix(mtcars$vs)
df_y <- mtcars[,8,drop=FALSE] #column vs is the 8th column
x <- as.matrix(mtcars[,-8]) #column vs is the 8th column
#vector labels: works
xgboost::xgb.DMatrix(data=x, label=vec_y)
#matrix labels: works
xgboost::xgb.DMatrix(data=x, label=mat_y)
#df labels: doesnt work
xgboost::xgb.DMatrix(data=x, label=df_y)
很可能您的其他脚本的数据没有任何缺失 (NA) 值。当您将数据帧稀疏(我猜您正在尝试对一个热编码列进行编码)到矩阵时,R 将自动删除缺失值并因此删除错误。
最佳做法是使用“is.na”将所有空值替换为 0。