带有 plotly 的交互式 3D 部分依赖图
# Random seed to reproduce the results
set.seed(1)
# Create artificial data for a binary classification problem
y <- factor(sample(c(0,1), size = 100, replace = TRUE), levels = c("0", "1"))
d <- data.frame(y = y, x1 = rnorm(100), x2 = rnorm(100), x3 = rnorm(100))
# Build a random forest model
library(randomForest)
rf1 <- randomForest::randomForest(y ~., n.trees = 100, mtry = 2, data = d)
###### Bivariate partial dependency plots ######
# Step 1: compute the partial dependence values
# given two variables using the pdp library
library(pdp)
pd <- rf1 %>% partial(pred.var = c("x1", "x2"), n.trees = 100)
# Step 2: construct the plot using the plotly library
library(plotly)
p <- plot_ly(x = pd$x1, y = pd$x2, z = pd$yhat, type = 'mesh3d')
# Step 3: add labels to the plot
p <- p %>% layout(scene = list(xaxis = list(title = "x1"),
yaxis = list(title = "x2"),
zaxis = list(title = "Partial Dependence")))
# Step 4: show the plot
show(p)
交互式等高线图(即扁平 2 变量 PDP),使用 plotly 为部分相关值提供色标
###### Bivariate PDPs with colored scale ######
# Interpolate the partial dependence values
dens <- akima::interp(x = pd$x1, y = pd$x2, z = pd$yhat)
# Flattened contour partial dependence plot for 2 variables
p2 <- plot_ly(x = dens$x,
y = dens$y,
z = dens$z,
colors = c("blue", "grey", "red"),
type = "contour")
# Add axis labels for 2D plots
p2 <- p2 %>% layout(xaxis = list(title = "x1"), yaxis = list(title = "x2"))
# Show the plot
show(p2)
交互式 3D 部分依赖图,带有使用 plotly 的部分依赖值的色标
###### Interactive 3D partial dependence plot with coloring scale ######
# Interpolate the partial dependence values
dens <- akima::interp(x = pd$x1, y = pd$x2, z = pd$yhat)
# 3D partial dependence plot with a coloring scale
p3 <- plot_ly(x = dens$x,
y = dens$y,
z = dens$z,
colors = c("blue", "grey", "red"),
type = "surface")
# Add axis labels for 3D plots
p3 <- p3 %>% layout(scene = list(xaxis = list(title = "x1"),
yaxis = list(title = "x2"),
zaxis = list(title = "Partial Dependence")))
# Show the plot
show(p3)