1

当我在 ubuntu 14.04 中运行这段代码时,我想用 scipy.spatial.distance 计算数组的余弦距离。但这让我在导入 scipy.spatial.distance 时出错。

import numpy as np
import scipy
from scipy.spatial.distance import pdist


x=np.array([[[-0.22008298,  0.28819615,  0.09895946,  0.16789497,  0.02379252,
   -0.25700486,  0.1628186,   0.12296761,  0.01750283]],

 [[ 0.29891527,  0.17249978, -0.10084602, -0.16522293,  0.06811064,
    0.07434326, -0.19697316, -0.22199543,  0.07647966]],

 [[-0.04112297,  0.13392878, -0.06575392,  0.0893533,   0.22577047,
    0.00289264,  0.09996213,  0.17324321,  0.08673526]]])


B =x.transpose(1,2,0).reshape(-1,x.shape[0])
print(B.shape) 
print (B.ndim)
#array.astype(int)
print(B)
y=1-(pdist(B, metric='cosine'))
print(y)

它抛出这个错误,

     Traceback (most recent call last):
  File "cos1.py", line 3, in <module>
    from scipy.spatial.distance import pdist
  File "/home/mayesha/venv/local/lib/python2.7/site-packages/scipy/spatial/__init__.py", line 94, in <module>
    from .kdtree import *
  File "/home/mayesha/venv/local/lib/python2.7/site-packages/scipy/spatial/kdtree.py", line 8, in <module>
    import scipy.sparse
  File "/home/mayesha/venv/local/lib/python2.7/site-packages/scipy/sparse/__init__.py", line 229, in <module>
    from .csr import *
  File "/home/mayesha/venv/local/lib/python2.7/site-packages/scipy/sparse/csr.py", line 20, in <module>
    from .compressed import _cs_matrix
  File "/home/mayesha/venv/local/lib/python2.7/site-packages/scipy/sparse/compressed.py", line 11, in <module>
    from scipy._lib._util import _prune_array
  File "/home/mayesha/venv/local/lib/python2.7/site-packages/scipy/_lib/_util.py", line 9, in <module>
    import inspect
  File "/usr/lib/python2.7/inspect.py", line 37, in <module>
    import dis
  File "/home/mayesha/dis.py", line 2, in <module>
    from scipy.spatial.distance import pdist
  File "/home/mayesha/venv/local/lib/python2.7/site-packages/scipy/spatial/distance.py", line 119, in <module>
    from scipy._lib._util import _asarray_validated
ImportError: cannot import name _asarray_validated

我正在使用 pip 的虚拟环境。有人能帮我吗。提前致谢。

4

1 回答 1

0
pip install -U scipy

这将解决您的问题。我试过了,它对我有用。您可能会收到 scikit-learn 未正确安装的错误。如果您收到该错误,您可以先运行:

pip install -U scikit-learn

然后重新运行上面的代码。

于 2020-08-07T04:45:13.790 回答