Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - Module 'scipy.sparse' has no attribute 'linalg' error in reticulate virtual environment

I have written a function which works exactly as I would like it to in python, but when I try and run it in R I run into a problem with reticulate. I have troubleshooted this problem and have reduced it down to this problem. I have this function in python:

def get_largest_eigenvalue(inc_mat):
    eigen_val = scipy.sparse.linalg.eigs(inc_mat, k = 1)
    eigen_val = eigen_val[0] / inc_mat.shape[0]
    return eigen_val

Essentially this function takes a csr_matrix and returns its largest eigenvalue. It should work for any csr_matrix. I get an error when I run this code using reticulate and solving this will solve my larger problem.

To run this code in reticulate I run

library(reticulate)
use_virtualenv("default")

I have previously run this code to install scipy to this virtual environment

virtualenv_install("default", c("scipy"))

I have then used

source_python("file_name.py")

To load all of my python functions, including the one above. All of the other functions I have loaded work perfectly except the one above. When I try and run it I receive the following error

Error in py_call_impl(callable, dots$args, dots$keywords) : AttributeError: module 'scipy.sparse' has no attribute 'linalg'

I am a bit out of my depth here and I have tried running code like

virtualenv_install("default", c("scipy.sparse"))

But this causes more errors and does not work. Any help would be appreciated! Thank you!

question from:https://stackoverflow.com/questions/65909046/module-scipy-sparse-has-no-attribute-linalg-error-in-reticulate-virtual-envi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add this explicit import to your code:

import scipy.sparse.linalg

Importing just scipy.sparse doesn't import the linalg submodule automatically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...