如何重现Lasso等高线图?白色区域及OLS椭圆实现疑问
Lasso等高线图:白色区域定义与OLS椭圆添加方案
一、白色区域实现
白色区域对应Lasso损失函数低于某一阈值的区域,可通过两种方式实现:
- 掩码赋值:将损失值小于等于阈值的部分设为
NA,绘图时这些区域会显示为白色背景 - 自定义颜色刻度:通过
colorscale将低数值区域映射为白色,同时控制等高线起始值,只绘制高于阈值的部分
二、OLS椭圆添加
OLS的等高线是椭圆,借助ellipse包可快速生成椭圆坐标,再添加到图中。椭圆参数需根据数据协方差矩阵调整,示例中用单位矩阵模拟通用场景。
完整可运行代码
library(plotly) library(ellipse) # 生成网格数据 n1 <- 60 n2 <- 60 data <- expand.grid(x = seq(-3, 3, length.out = n1), y = seq(-3, 3, length.out = n2)) # 计算Lasso损失值 lambda_v <- c(10, 10) V_arr <- rep(0, n1*n2) count <- 1 for (ii in 1:n1){ for (jj in 1:n2){ V_arr[count] <- t(as.matrix(lambda_v)) %*% as.matrix(c(abs(data$x[count]), abs(data$y[count]))) count <- count + 1 } } # 定义白色区域:设定阈值,将低于阈值的部分设为NA threshold <- 10 # 可根据需求调整阈值大小 V_arr_masked <- ifelse(V_arr <= threshold, NA, V_arr) # 生成OLS椭圆(示例用单位协方差矩阵,中心在(0,0)) cov_mat <- diag(2) # 实际应用中替换为你的数据协方差矩阵 ellipse_coords <- ellipse(cov_mat, centre = c(0, 0), level = 0.5) # level控制椭圆大小 # 绘制图形 p <- plot_ly(x = data$x, y = data$y, z = V_arr_masked, type = "contour", colorscale = list(c(0, "white"), c(1, "darkblue")), contours = list( start = threshold, end = max(V_arr), size = 2 )) %>% add_trace(x = ellipse_coords[,1], y = ellipse_coords[,2], type = "scatter", mode = "lines", line = list(color = "red", width = 2), name = "OLS 椭圆") # 显示图形 p
关键说明
- 替换原代码中的
linspace为R原生seq函数,避免语法报错 - 阈值
threshold可根据可视化需求调整,对应Lasso损失的临界值 - 椭圆的
cov_mat(协方差矩阵)和centre(OLS估计值)需替换为你的实际数据参数,以生成准确的OLS等高线椭圆
内容的提问来源于stack exchange,提问作者Sparsity
相关产品推荐
相关产品推荐

