r-如何从与训练分数相对应的gbm中获得具有响应变量的向量



我正在运行gbm函数(来自gbm R包(,并将选项train.fraction设置为0.7。我想得到一个向量,它的响应变量对应于这个子集。我认为这必须保存在输出gbm对象的一个变量中,但我没有找到它,也不知道是否有办法获得它。使用的数据部分保存在gbm.result$data$x.ordered中,但它不包括响应变量。如果这个问题有一个非常明显的答案,我们深表歉意。

如果指定training.fraction=0.7,它会占用数据的前0.7*nrows

如果您查看gbm功能:

train.fraction: The first ‘train.fraction * nrows(data)’ observations
are used to fit the ‘gbm’ and the remainder are used for
computing out-of-sample estimates of the loss function.

我们可以通过检查训练错误和有效错误来验证这一点:

train.error: a vector of length equal to the number of fitted trees
containing the value of the loss function for each boosting
iteration evaluated on the training data
valid.error: a vector of length equal to the number of fitted trees
containing the value of the loss function for each boosting
iteration evaluated on the validation data

例如:

library(gbm)
set.seed(111)
data = iris[sample(nrow(iris)),]
data$Species=as.numeric(data$Species=="versicolor")
fit = gbm(Species ~ .,data=data,train.fraction=0.7,distribution="bernoulli")

由于0.7*150=105,我们将编写一个函数来计算偏差(可以参考此进行推导(,并检查各自的偏差:

# here y is the observed label, 0 or 1
# P is the log-odds obtained from predict.gbm(..)
b_dev = function(y,P){-2*mean(y*P-log(1+exp(P)))}
fit$train.error[length(fit$train.error)]
[1] 0.1408239
b_dev(data$Species[1:105],predict(fit,data[1:105,],n.trees=fit$n.trees))
[1] 0.1408239
fit$valid.error[100]
[1] 0.365474
b_dev(data$Species[106:150],predict(fit,data[106:150,],n.trees=fit$n.trees))
[1] 0.365474

最新更新