假设我们有一个数据集其中是我们想知道其部分依赖关系的变量矩阵,是剩余变量的矩阵预测器。设为响应向量(即回归问题)。假设并且我们估计一些拟合。X=[xsxc]∈Rn×pxsxcy∈Ry=f(x)+ϵf^
那么在处的部分依赖(这里位于同一空间),定义为:f^s(x)f^ xxxs
f^s(x)=1n∑i=1nf^(x,xci)
这就是说:对感兴趣的变量因此,我们需要选择感兴趣的变量,并选择所在空间中我们感兴趣的区域。注意:小心将的边际均值外推到该区域之外。xxsf(x)
这是 R 中的一个示例实现。我们首先创建一个示例数据集:
library(tidyverse)
library(ranger)
library(broom)
mt2 <- mtcars %>%
as_tibble() %>%
select(hp, mpg, disp, wt, qsec)
然后我们使用随机森林估计f
fit <- ranger(hp ~ ., mt2)
接下来我们选择我们对估计部分依赖关系感兴趣的特性:
var <- quo(disp)
现在我们可以将数据集拆分为这个预测器和其他预测器:
x_s <- select(mt2, !!var) # grid where we want partial dependencies
x_c <- select(mt2, -!!var) # other predictors
然后我们创建这些数据集的所有组合的数据框:
# if the training dataset is large, use a subsample of x_c instead
grid <- crossing(x_s, x_c)
我们想知道在这个网格上每个点的预测。我为此定义了一个助手:f^broom::augment()
augment.ranger <- function(x, newdata) {
newdata <- as_tibble(newdata)
mutate(newdata, .fitted = predict(x, newdata)$predictions)
}
au <- augment(fit, grid)
现在我们有了预测,我们通过取中每个点的平均值来边缘化:xs
pd <- au %>%
group_by(!!var) %>%
summarize(yhat = mean(.fitted))
我们也可以将其可视化:
pd %>%
ggplot(aes(!!var, yhat)) +
geom_line(size = 1) +
labs(title = "Partial dependence plot for displacement",
y = "Average prediction across all other predictors",
x = "Engine displacement") +
theme_bw()
最后,我们可以根据包检查这个实现pdp以确保它是正确的:
pd2 <- pdp::partial(
fit,
pred.var = quo_name(var),
pred.grid = distinct(mtcars, !!var),
train = mt2
)
testthat::expect_equivalent(pd, pd2) # silent, so we're good
对于分类问题,您可以重复类似的过程,除了预测单个类的类概率。