Numpy移调功能可加快速度和使用案例 [英] Numpy transpose functions speed and use cases
问题描述
那为什么NumPy转置.T
的速度比np.transpose()
快?
So why is the NumPy transpose .T
faster than np.transpose()
?
b = np.arange(10)
#Transpose .T
t=b.reshape(2,5).T
#Transpose function
t = np.transpose(b.reshape(2,5))
#Transpose function without wrapper
t = b.reshape(2,5).transpose()
我在Jupyter中都做了两个timeit
:
I did a timeit
of both in Jupyter:
%timeit -n 1000 b.reshape(2,5).T
1000 loops, best of 3: 391 ns per loop
%timeit -n 1000 np.transpose(b.reshape(2,5))
1000 loops, best of 3: 600 ns per loop
%timeit -n 1000 b.reshape(2,5).transpose()
1000 loops, best of 3: 422 ns per loop
并检查可扩展性,我做了一个更大的矩阵:
and to check scaleablility I did a larger matrix:
b = np.arange( 100000000)
%timeit -n 1000 b.reshape(10000,10000).T
1000 loops, best of 3: 390 ns per loop
%timeit -n 1000 np.transpose(b.reshape(10000,10000))
1000 loops, best of 3: 611 ns per loop
%timeit -n 1000 b.reshape(10000,10000).transpose()
1000 loops, best of 3: 435 ns per loop
在这两种情况下,.T
方法的速度都比包装器快约2倍,比使用.transpose()
的速度快一点,这是为什么呢?有没有使用np.transpose
更好的用例?
In both cases the .T
method about 2x faster than the wrapper and a bit faster than using .transpose()
why is this? Is there a use case where np.transpose
would be better?
推荐答案
一个原因可能是np.transpose(a)
只是在内部调用a.transpose()
,而a.transpose()
更直接.在源中,您有:
One reason might be that np.transpose(a)
just calls a.transpose()
internally, while a.transpose()
is more direct. In the source you have:
def transpose(a, axes=None):
return _wrapfunc(a, 'transpose', axes)
_wrapfunc
依次只是:
def _wrapfunc(obj, method, *args, **kwds):
try:
return getattr(obj, method)(*args, **kwds)
except (AttributeError, TypeError):
return _wrapit(obj, method, *args, **kwds)
在这种情况下,它映射到getattr(a, 'transpose')
.许多模块级函数使用_wrapfunc
访问方法,通常是ndarray
类或第一个arg的类.
This maps to getattr(a, 'transpose')
in this case. _wrapfunc
is used by many of the module-level functions to access methods, usually of the ndarray
class or whatever is the class of the first arg.
(注意:.T
与.transpose()
相同,除了如果数组具有< 2维,则返回该数组.)
(Note: .T
is the same as .transpose()
, except that the array is returned if it has <2 dimensions.)
这篇关于Numpy移调功能可加快速度和使用案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!