R语言neuralnet包神经网络绘图标签截断问题求助
解决neuralnet绘图标签截断问题
方法1:调整绘图参数与画布尺寸
neuralnet的plot函数支持width和height参数控制画布大小,同时可通过par()增大绘图边距,给标签留出更多空间:
# 调整全局绘图边距,重点增大左右边距(顺序:下、左、上、右) par(mar = c(5, 8, 4, 8)) # 调用plot时指定更大的画布尺寸 plot(net_model, width = 10, height = 8)
如果需要保存为文件,直接在绘图设备中设置高分辨率和大尺寸:
png("nn_visualization.png", width = 1200, height = 800, res = 150) par(mar = c(5, 8, 4, 8)) plot(net_model, width = 10, height = 8) dev.off()
方法2:自定义neuralnet绘图函数(调整标签位置)
默认的plot.neuralnet函数对标签位置的计算比较紧凑,可修改源码中标签绘制的坐标:
- 先复制原函数代码:
plot.neuralnet <- neuralnet:::plot.neuralnet
- 找到函数中绘制输入/输出标签的
text调用,调整x坐标值(比如输入标签左移、输出标签右移):
# 修改输入层标签的位置(x值减小,让标签更靠左) body(plot.neuralnet)[[which(grepl("text(", body(plot.neuralnet), fixed = TRUE))]] <- substitute( text(layer_positions[[1]] - 0.15, rep(1:nrow(weights[[1]]), each = ncol(weights[[1]])), labels = input_names, cex = 0.8, pos = 2) ) # 修改输出层标签的位置(x值增大,让标签更靠右) body(plot.neuralnet)[[which(grepl("text(", body(plot.neuralnet), fixed = TRUE)[-1])]] <- substitute( text(layer_positions[[length(layer_positions)]] + 0.15, 1:ncol(weights[[length(weights)]]), labels = output_names, cex = 0.8, pos = 4) ) # 使用修改后的函数绘图 plot(net_model)
方法3:改用第三方可视化工具
如果neuralnet自带的绘图始终无法满足需求,可借助DiagrammeR手动构建网络可视化,完全控制标签显示:
library(DiagrammeR) # 提取网络结构参数 input_num <- length(n[!n %in% targets]) hidden_layers <- c(8, 4, 4) output_num <- length(targets) # 创建节点数据 nodes <- create_nodes( nodes = 1:(input_num + sum(hidden_layers) + output_num), label = c(n[!n %in% targets], paste0("H", rep(1:length(hidden_layers), hidden_layers)), targets), shape = c(rep("rectangle", input_num), rep("circle", sum(hidden_layers)), rep("rectangle", output_num)), style = "filled", fillcolor = c(rep("#a6cee3", input_num), rep("#1f78b4", sum(hidden_layers)), rep("#b2df8a", output_num)) ) # 创建边数据 edges <- create_edges( from = c(rep(1:input_num, each=hidden_layers[1]), rep((input_num+1):(input_num+hidden_layers[1]), each=hidden_layers[2]), rep((input_num+sum(hidden_layers[1:2])+1):(input_num+sum(hidden_layers)), each=output_num)), to = c(rep((input_num+1):(input_num+hidden_layers[1]), input_num), rep((input_num+hidden_layers[1]+1):(input_num+sum(hidden_layers[1:2])), hidden_layers[1]), rep((input_num+sum(hidden_layers)+1):(input_num+sum(hidden_layers)+output_num), hidden_layers[3])) ) # 生成并渲染图形 graph <- create_graph(nodes_df = nodes, edges_df = edges) render_graph(graph)
内容的提问来源于stack exchange,提问作者coolhand
相关产品推荐
相关产品推荐

