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)
由于要将对象数据类型数组作为参数传递,因此还需要指定“O”结果类型。如果不使用
otypes
vectorize
将尝试推断返回的数据类型,并且可能会出错。这只是使用np.vectorize
的陷阱之一:np.vectorize
的另一个问题是它比备选方案慢:np.vectorize
有一个明确的速度免责声明。阅读完整的文档;它并不像你想象的那么简单。这个名字可能有误导性相关问题 更多 >
编程相关推荐