numpy 在python中导入scipy.spatial.distance时出错

nfeuvbwi  于 2023-10-19  发布在  Python
关注(0)|答案(2)|浏览(145)

当我在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。谁能帮帮我先谢了。

8cdiaqws

8cdiaqws1#

pip install -U scipy

这将解决您的问题。我试过了,它为我做了。你可能会得到一个错误,scikit-learn没有正确安装。如果你得到这个错误,你可以先运行:

pip install -U scikit-learn

然后,将上面的代码

icomxhvb

icomxhvb2#

安装包 sklearn 解决了我的问题。

相关问题