使用shap库时R Markdown编译flex dashboard报错
Flex Dashboard编译R Markdown时导入shap库触发figsize类型转换错误
问题场景
用R Markdown生成flex dashboard时,Python代码块里导入shap库就会触发报错,切换成html_document格式编译则完全正常;其他Python库导入无异常,新建空白文档单独导入shap也能正常运行。
报错信息:
Quitting from lines 45-46 [unnamed-chunk-1] (working_example.Rmd) Error: ! RuntimeError: ValueError: Key figure.figsize: Could not convert [6.0, 3.75] to float Backtrace: 1. rmarkdown::render(...) 2. knitr::knit(knit_input, knit_output, envir = envir, quiet = quiet) 3. knitr:::process_file(text, output) 7. knitr:::process_group.block(group) 8. knitr:::call_block(x) ... 12. knitr (local) engine(options) 13. reticulate::eng_python(options) 14. reticulate:::py_compile_eval(snippet, compile_mode) 17. builtins$eval(compiled, globals, locals) 18. reticulate:::py_call_impl(callable, dots$args, dots$keywords) Execution halted
问题原因
flexdashboard默认会将matplotlib的figure.figsize参数设置为列表格式[6.0, 3.75],但matplotlib的rcParams实际期望的是元组或浮点数对格式,shap在初始化过程中读取该参数时,会因格式不匹配触发类型转换错误。
解决方法
方法1:导入shap前重置matplotlib参数
在Python代码块开头先修正figsize的格式,再导入shap:
import matplotlib # 将列表格式改为matplotlib接受的元组格式 matplotlib.rcParams['figure.figsize'] = (6.0, 3.75) import shap # 后续shap相关代码正常执行即可
方法2:禁用flexdashboard对matplotlib的默认配置
在R Markdown的YAML头部添加配置,阻止flexdashboard修改matplotlib的figsize参数:
--- title: "你的仪表盘标题" output: flexdashboard::flex_dashboard: config: matplotlib: figsize: null ---
编译时matplotlib会使用自身默认的figsize设置,shap导入即可正常完成。
内容的提问来源于stack exchange,提问作者Mageentta
相关产品推荐
相关产品推荐

