【问题标题】:Error "variable lengths differ" when assigning weights parameter in caret (R)在插入符号(R)中分配权重参数时出现错误“可变长度不同”
【发布时间】:2018-01-15 16:22:32
【问题描述】:

我想使用下面的代码在插入符号中应用加权观察:

model_weights <- ifelse(train$y == 0,
                        (1/table(train$y)[1]) * 0.5,
                        (1/table(train$y)[2]) * 0.5)

xgbT <- train(x = as.matrix(train[,-21]), y = make.names(as.factor(train$y)), 
              method = "xgbTree", 
              trControl = cctrl1,
              metric = "MCC",
              maximize = TRUE,
              weights = model_weights,
              preProc = c("center", "scale"),
              tuneGrid = expand.grid(nrounds = c(150), #number of trees
                                    max_depth = c(7), #max tree depth
                                    eta = c(0.03), #learning rate
                                    gamma = c(0.3), #min split loss
                                    colsample_bytree = c(0.7),
                                    min_child_weight = c(10, 1, 5), #min number of instances in the leaf
                                    subsample = c(0.6)), #subsample ratio of the training instance
              early_stop_round = c(3), #if no improvements over specified rounds
              objective = c("binary:logistic"),
              silent = 0)

但是,它给了我这个错误:Error in model.frame.default(formula = .outcome ~ ., data = dat, weights = wts) : variable lengths differ (found for '(weights)')

虽然我已经检查过它们的长度与下面的代码相同:

> table(model_weights)
model_weights
0.0000277654375832963  0.000231481481481481 
                18008                  2160 
> table(train$y)

    0     1 
18008  2160 

知道如何解决这个问题吗?

注意:我可以在没有 weights 参数的情况下运行 train 函数。

【问题讨论】:

  • @missuse 是的,我在这里检查过:topepo.github.io/caret/…
  • 哪一个?请分享链接
  • 对不起,早上...我以为你链接了它:Here 它是 - test_class_cv_form_weight 示例
  • 当我在 topepo's code 你的 model_weights 上运行时,我仍然得到结果。它必须在您的数据中。也许尝试将数据减少到可以重现问题的较小样本并提供dput 或作为下载链接。
  • 尝试使用weights = model_weights/max(model_weights) 如果我没有提供输出,但模型是无意义的。

标签: r r-caret


【解决方案1】:

经过进一步调试,发现问题是因为我在cctrl1中应用了sampling。因此,weights 的长度不同,因为我在它们应用重新采样之前生成它。

因此,您只需从 trControl 中删除 sampling 即可解决此问题。如果您仍然想应用重新采样,那么您必须在运行以下代码之前重新采样数据:

model_weights <- ifelse(train$y == 0,
                    (1/table(train$y)[1]) * 0.5,
                    (1/table(train$y)[2]) * 0.5)

【讨论】:

  • 用这样的权重得到的模型有意义吗?我发现其中一个权重需要为 1,模型才能预测这两个类别。
  • 好像它们影响模型一样有意义,答案是肯定的。但是,现在我意识到,一旦我们应用重新采样,我们可能不需要应用加权。
  • 如果您应用欠采样或过采样或诸如 SMOTE/ROSE 之类的算法,那么权重不是一个好主意。但通常我更喜欢使用权重。它们更容易实施,也更直接。
  • 哦。感谢您的时间和帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多