【发布时间】:2017-08-01 14:41:40
【问题描述】:
我在许多不同的地方读到numpy.take 是一种比花哨索引更快的替代方案,例如here 和here。
但是,我发现情况并非如此……完全没有。以下是我在调试期间查看代码时的示例:
knn_idx
Out[2]:
array([ 3290, 5847, 7682, 6957, 22660, 5482, 22661, 10965, 7,
1477, 7681, 3, 17541, 15717, 9139, 1475, 14251, 4400,
7680, 9140, 4758, 22289, 7679, 8407, 20101, 15718, 15716,
8405, 15710, 20829, 22662], dtype=uint32)
%timeit X.take(knn_idx, axis=0)
100 loops, best of 3: 3.14 ms per loop
%timeit X[knn_idx]
The slowest run took 60.61 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.48 µs per loop
X.shape
Out[5]:
(23011, 30)
X.dtype
Out[6]:
dtype('float64')
这表明花式索引要快得多!使用numpy.arange 生成索引我得到了类似的结果:
idx = np.arange(0, len(X), 100)
%timeit X.take(idx, axis=0)
100 loops, best of 3: 3.04 ms per loop
%timeit X[idx]
The slowest run took 9.41 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 20.7 µs per loop
为什么花式索引比现在使用numpy.take 快得多?我遇到了某种极端情况吗?
我通过 Anaconda 使用 Python 3.6,如果相关,这是我的 numpy 信息:
np.__version__
Out[11]:
'1.11.3'
np.__config__.show()
blas_mkl_info:
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:/Users/pbreach/Continuum/Anaconda3\\Library\\lib']
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
include_dirs = ['C:/Users/pbreach/Continuum/Anaconda3\\Library\\include']
blas_opt_info:
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:/Users/pbreach/Continuum/Anaconda3\\Library\\lib']
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
include_dirs = ['C:/Users/pbreach/Continuum/Anaconda3\\Library\\include']
openblas_lapack_info:
NOT AVAILABLE
lapack_mkl_info:
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:/Users/pbreach/Continuum/Anaconda3\\Library\\lib']
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
include_dirs = ['C:/Users/pbreach/Continuum/Anaconda3\\Library\\include']
lapack_opt_info:
libraries = ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll']
library_dirs = ['C:/Users/pbreach/Continuum/Anaconda3\\Library\\lib']
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
include_dirs = ['C:/Users/pbreach/Continuum/Anaconda3\\Library\\include']
【问题讨论】:
标签: python arrays performance numpy indexing