Macbook Pro M1(Monterey)Scikit-learn导入libgfortran报错求助
解决M1 Mac Monterey上Scikit-learn导入时libgfortran.5.dylib缺失的问题
问题背景
执行import sklearn时触发以下报错:
ImportError: dlopen(/opt/homebrew/lib/python3.9/site-packages/scipy/linalg/_fblas.cpython-39-darwin.so, 0x0002): Library not loaded: '/opt/homebrew/opt/gcc/lib/gcc/11/libgfortran.5.dylib' Referenced from: '/opt/homebrew/lib/python3.9/site-packages/scipy/linalg/_fblas.cpython-39-darwin.so' Reason: tried: '/opt/homebrew/opt/gcc/lib/gcc/11/libgfortran.5.dylib' (no such file), '/usr/local/lib/libgfortran.5.dylib' (no such file), '/usr/lib/libgfortran.5.dylib' (no such file)
已通过locate libgfortran.5.dylib确认存在该库,路径如下:
/opt/homebrew/Cellar/gcc/12.2.0/lib/gcc/12/libgfortran.5.dylib /opt/homebrew/Cellar/gcc/12.2.0/lib/gcc/current/libgfortran.5.dylib /opt/homebrew/lib/python3.10/site-packages/numpy/.dylibs/libgfortran.5.dylib /usr/local/Cellar/gcc/11.1.0/lib/gcc/11/libgfortran.5.dylib
解决方案
方法1:创建软链接匹配期望路径
报错中scipy试图寻找gcc 11版本的libgfortran,但当前安装的是gcc 12,直接创建软链接让系统找到对应库:
# 创建目标目录(若不存在) mkdir -p /opt/homebrew/opt/gcc/lib/gcc/11 # 从gcc12的库路径创建软链接到报错指定的路径 ln -s /opt/homebrew/Cellar/gcc/12.2.0/lib/gcc/12/libgfortran.5.dylib /opt/homebrew/opt/gcc/lib/gcc/11/libgfortran.5.dylib
方法2:设置DYLD_LIBRARY_PATH环境变量
通过环境变量告诉系统额外的库搜索路径,编辑~/.zshrc(M1 Mac默认Shell为zsh):
echo 'export DYLD_LIBRARY_PATH="/opt/homebrew/Cellar/gcc/12.2.0/lib/gcc/12:$DYLD_LIBRARY_PATH"' >> ~/.zshrc # 使配置生效 source ~/.zshrc
方法3:重新安装适配环境的Scipy/Scikit-learn
原安装的scipy可能是针对旧版gcc编译的,重新安装适配当前环境的版本:
- 使用Homebrew安装:
brew install scipy scikit-learn
- 或使用Conda创建独立环境(推荐,自动处理依赖):
conda create -n sklearn_env python=3.9 scikit-learn conda activate sklearn_env
内容的提问来源于stack exchange,提问作者capnahab
相关产品推荐
相关产品推荐

