Fix ImportError: cannot import name 'triu' from 'scipy.linalg' in Gensim
Problem
When attempting to import Gensim, you encounter this error traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
File "/usr/local/lib/python3.10/dist-packages/gensim/matutils.py", line 20, in <module>
from scipy.linalg import get_blas_funcs, triu
ImportError: cannot import name 'triu' from 'scipy.linalg' (...)
This occurs because recent versions of SciPy (1.13.0+) removed the triu
, tril
, and tri
functions, which were deprecated in earlier releases. Gensim's matutils.py
module attempts to import triu
, causing the import failure when using incompatible SciPy versions.
Solution
Install a compatible version of SciPy. Choose the method based on your environment:
For pip users
Downgrade to SciPy version 1.12.0 or 1.10.1:
# Either install version 1.12.0
pip install scipy==1.12.0
# Or install version 1.10.1
pip install scipy==1.10.1
TIP
Version 1.12.0 is recommended as it's newer than 1.10.1 while still containing the required triu
function
For conda users
Install any SciPy version below 1.13.0:
conda install "scipy<1.13"
IMPORTANT
Avoid mixing pip and conda installs in the same environment. If you originally installed SciPy with conda, continue using conda for the downgrade to prevent environment conflicts.
Why These Versions Work
SciPy's release notes confirm the deprecation and removal timeline:
- Deprecated in: SciPy 1.11.0 (May 2023)
- Removed in: SciPy 1.13.0 (Dec 2023)
The triu
function exists in any SciPy version earlier than 1.13.0, making versions 1.12.x, 1.11.x, and 1.10.x safe choices.
::: note Future Gensim updates may add support for SciPy 1.13.0+. Check the Gensim GitHub repository for compatibility updates. :::
Steps After Installation
Confirm the fix by importing Gensim:
python -c "import gensim; print('Gensim imported successfully!')"
You should see the success message without errors.
Best Practices
- Specify exact version requirements in
requirements.txt
:txtscipy==1.12.0 gensim==x.x.x # your Gensim version
- Use virtual environments to isolate dependencies
- Test library compatibility before upgrading major versions
TIP
For long-term projects, consider pinning both Gensim and SciPy versions to prevent breaking changes