使用SHAP值时遇numpy np.int属性错误,求非源码修改方案
np.int弃用导致的AttributeError问题 报错信息
"/envs/shapTest/lib/python3.9/site-packages/shap/explainers/_kernel.py", line 277, in explain
num_subset_sizes = np.int(np.ceil((self.M - 1) / 2.0))
AttributeError: module 'numpy' has no attribute 'int'.
np.int was a deprecated alias for the builtin int. To avoid this error in existing code, use int by itself. Doing this will not modify any behavior and is safe. When replacing np.int, you may wish to use e.g. np.int64 or np.int32 to specify the precision. If you wish to review your current use, check the release note link for additional information.
The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at:
https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
问题背景
已尝试不同干净环境及旧版本NumPy,仍未解决问题,求无需修改包源码的解决方案。
可行解决方案
- 升级SHAP到修复版本:该问题是旧版SHAP未适配NumPy 1.20+的弃用规则导致的,直接安装修复此问题的新版SHAP即可。执行命令:
pip install --upgrade shap - 临时恢复
np.int别名:在代码开头添加以下代码,无需修改SHAP源码,临时映射np.int到内置int:import numpy as np if not hasattr(np, 'int'): np.int = int - 锁定兼容的NumPy版本:若需固定SHAP版本,可安装与该SHAP版本兼容的NumPy版本,比如针对SHAP < 0.40.0,安装NumPy 1.19.x:
pip install numpy==1.19.5
内容的提问来源于stack exchange,提问作者Sebastianostby

