首页 > 解决方案 > 如何在 R 中为分类模型编写自定义预测函数?

问题描述

我正在尝试将flashlight包与包一起使用h2o。可以在此处找到在回归模型上执行此操作的示例。但是,我正在尝试使其适用于分类模型......为了实现这一点,我遵循了链接中给出的示例。如果您提供自己的自定义预测功能flashlight,则可以使用。h2o但是,下面示例中的预测函数不适用于分类。

这是我正在使用的代码:

library(flashlight)
library(h2o)

h2o.init()
h2o.no_progress()

iris_hf <- as.h2o(iris)
iris_dl <- h2o.deeplearning(x = 1:4, y = "Species", training_frame = iris_hf, seed=123456)

pred_fun <- function(mod, X) as.vector(unlist(h2o.predict(mod, as.h2o(X))))
fl_NN <- flashlight(model = iris_dl, data = iris, y = "Species", label = "NN", 
                    predict_function = pred_fun)

但是当我尝试检查重要性或交互时,我得到一个错误......例如:

light_interaction(fl_NN, type = "H",
              pairwise = TRUE)

抛出错误:

错误:分配的数据predict(x, data = X[, cols, drop = FALSE])必须与现有数据兼容。现有数据有 22500 行。分配的数据有 90000 行。ℹ 仅回收大小为 1 的向量。

我需要以某种方式更改预测功能以使其工作......但我还没有成功......关于如何改变预测功能工作的任何建议?

编辑更新:所以,我找到了一个与该函数一起使用的自定义预测light_interaction函数。那是:

pred_fun <- function(mod, X) as.vector(unlist(h2o.predict(mod, as.h2o(X))[,2]))

以上是针对特定类别的索引。但是,以上不适用于计算重要性。例如:

light_importance(fl_NN)

给出错误:

Warning messages: 
1: In Ops.factor(actual, predicted) : ‘-’ not meaningful for factors 
2: In Ops.factor(actual, predicted) : ‘-’ not meaningful for factors
3: In Ops.factor(actual, predicted) : ‘-’ not meaningful for factors
4: In Ops.factor(actual, predicted) : ‘-’ not meaningful for factors
5: In Ops.factor(actual, predicted) : ‘-’ not meaningful for factors

所以,我还在想办法解决这个问题!?

标签: rh2o

解决方案


推荐阅读