下面是一個使用NumPy的強大功能broadcasting
一個量化的方法 -
def multiplication_table_vectorized(n):
base = np.arange(n)+1
return base[:,None]*base
運行測試 -
In [33]: n = 100
In [34]: np.allclose(multiplication_table(n),multiplication_table_vectorized(n))
Out[34]: True
In [35]: %timeit multiplication_table(n)
100 loops, best of 3: 10.1 ms per loop
In [36]: %timeit multiplication_table_vectorized(n)
10000 loops, best of 3: 58.9 µs per loop
解釋 -
讓我們以玩具爲例來解釋這裏的東西。
In [72]: n = 4 # Small n for toy example
In [73]: base = np.arange(n)+1 # Same as original: "base = list(range(1, n+1))"
In [74]: base # Checkback
Out[74]: array([1, 2, 3, 4])
In [75]: base[:,None] # Major thing happening as we extend base to a 2D array
# with all elements "pushed" as rows (axis=0) and thus
# creating a singleton dimension along columns (axis=1)
Out[75]:
array([[1],
[2],
[3],
[4]])
In [76]: base[:,None]*base # Broadcasting happens as elementwise multiplications
# take place between 2D extended version of 'base'
# and original 'base'. This is our desired output.
# To visualize a broadcasting :
# |--------->
# |
# |
# |
# V
Out[76]:
array([[ 1, 2, 3, 4],
[ 2, 4, 6, 8],
[ 3, 6, 9, 12],
[ 4, 8, 12, 16]])
有關broadcasting
更多信息和示例,沒有什麼比official docs
更好。 Broadcasting
是可用於NumPy
的最佳矢量化工具之一,允許進行這種自動擴展。
感謝,這正是我一直在尋找。你能解釋一下這個回報如何運作嗎?我知道讓這個基地成爲一個ndarray,但我對如何填充返回/數學工作感到困惑。 –
@TASCSolutions查看添加的評論是否有助於理解那裏發生了什麼。 – Divakar
是的,我現在看得很清楚:我需要對我的整數進行排序,所以numpy可以使用它,基數[:,無]替換我的循環以獲得垂直行,然後進行廣播和基礎數學。 –