下面是與initialization
的方法 -
n = 10
a = np.empty((n,n,n,n,n),dtype=int)
a[...] = np.arange(n)[:,None]
這裏還有一個NumPy strides
基礎的方法 -
r = np.arange(n)
s = r.strides[0]
shp = (n,n,n,n,n)
out = np.lib.index_tricks.as_strided(r, shape=shp, strides=(0,0,0,s,0))
運行測試
途徑 -
# @Eric's soln1
def broadcast_to_based(n): # Creates a read-only array
l_vals = np.arange(n).reshape(1, 1, 1, -1, 1)
return np.broadcast_to(l_vals, (n, n, n, n, n))
# @Eric's soln2
def tile_based(n):
l_vals = np.arange(n).reshape(1, 1, 1, -1, 1)
return np.tile(l_vals, (n, n, n, 1, n))
# @kmichael08's soln
def fromfunc_based(n):
return np.fromfunction(lambda i, j, k, l, m : l, (n, n, n, n, n))
# @Tw UxTLi51Nus's soln
def loop_based(n):
MyArray = np.zeros([n,n,n,n,n],dtype=int)
for l in range(n):
MyArray[:, :, :, l, :] = l
return MyArray
# Proposed-1 in this post
def initialization_based(n):
a = np.empty((n,n,n,n,n),dtype=int)
a[...] = np.arange(n)[:,None]
return a
# Proposed-2 in this post
def strided_based(n):
r = np.arange(n)
s = r.strides[0]
shp = (n,n,n,n,n)
return np.lib.index_tricks.as_strided(r, shape=shp, strides=(0,0,0,s,0))
個
計時 -
In [153]: n = 10
...: %timeit broadcast_to_based(n)
...: %timeit tile_based(n)
...: %timeit fromfunc_based(n)
...: %timeit loop_based(n)
...: %timeit initialization_based(n)
...: %timeit strided_based(n)
...:
100000 loops, best of 3: 4.1 µs per loop
1000 loops, best of 3: 236 µs per loop
1000 loops, best of 3: 645 µs per loop
10000 loops, best of 3: 180 µs per loop
10000 loops, best of 3: 89.1 µs per loop
100000 loops, best of 3: 5.44 µs per loop
In [154]: n = 20
...: %timeit broadcast_to_based(n)
...: %timeit tile_based(n)
...: %timeit fromfunc_based(n)
...: %timeit loop_based(n)
...: %timeit initialization_based(n)
...: %timeit strided_based(n)
...:
100000 loops, best of 3: 4.05 µs per loop
100 loops, best of 3: 8.16 ms per loop
10 loops, best of 3: 24.1 ms per loop
100 loops, best of 3: 6.07 ms per loop
100 loops, best of 3: 2.31 ms per loop
100000 loops, best of 3: 5.48 µs per loop
值得一提的是'np.broadcast_to'創建了一個只讀數組。 – Divakar