Numpy矢量化Numpy.dot函数

2024-09-27 09:36:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有a=np.array([array([1,2,3,4],[2,3,4,5]),array([6,7,8,9])])。我想取两个数组的点积,向量为

我试图对np.dot函数进行矢量化

vfunc=np.vectorize(np.dot) 我将vfunc应用于我的数组avfunc(a,v)其中v是我想用点积表示的向量。但是,我得到了这个错误ValueError: setting an array element with a sequence. 。还有别的办法吗


Tags: 函数an错误np数组elementarraysetting
1条回答
网友
1楼 · 发布于 2024-09-27 09:36:11

由于要将对象数据类型数组作为参数传递,因此还需要指定“O”结果类型。如果不使用otypesvectorize将尝试推断返回的数据类型,并且可能会出错。这只是使用np.vectorize的陷阱之一:

In [196]: f = np.vectorize(np.dot, otypes=['O'])                                
In [197]: x = np.array([[1,2,3],[1,2,3,4]])                                     
/usr/local/bin/ipython3:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
  #!/usr/bin/python3

In [199]: f(x, x)                                                               
Out[199]: array([14, 30], dtype=object)

np.vectorize的另一个问题是它比备选方案慢:

In [200]: f1 = np.frompyfunc(np.dot, 2,1)                                       
In [201]: f1(x,x)                                                               
Out[201]: array([14, 30], dtype=object)

In [202]: np.array([np.dot(i,j) for i,j in zip(x,x)])                           
Out[202]: array([14, 30])

In [203]: timeit f(x, x)                                                        
27.1 µs ± 229 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
                                                                       
In [204]: timeit f1(x,x)                                                        
16.9 µs ± 135 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [205]: timeit np.array([np.dot(i,j) for i,j in zip(x,x)])                    
21.3 µs ± 201 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

np.vectorize有一个明确的速度免责声明。阅读完整的文档;它并不像你想象的那么简单。这个名字可能有误导性

相关问题 更多 >

    热门问题