如何将numpy数组值复制到更高的维度

问题描述 投票:8回答:7

我在2d中有一个(w,h)np数组。我想制作一个值大于1的3d维度,并将其值沿第三维复制。我希望广播会这样做,但事实并非如此。这就是我在做的方式

arr = np.expand_dims(arr, axis=2)
arr = np.concatenate((arr,arr,arr), axis=2)

有更快的方法吗?

python numpy multidimensional-array 3d numpy-ndarray
7个回答
6
投票

你可以向前推动所有的dims,引入一个单独的昏暗/新轴作为最后一个dim来创建一个3D数组,然后沿着那个用np.repeat重复三次,就像这样 -

arr3D = np.repeat(arr[...,None],3,axis=2)

这是使用np.tile的另一种方法 -

arr3D = np.tile(arr[...,None],3)

4
投票

另一种有效的方法:

x_train = np.stack((x_train,) * 3, axis=-1)


2
投票

另一种简单的方法是使用矩阵乘法 - 乘以一个矩阵,这些矩阵基本上会复制新维度的值:

a=np.random.randn(4,4)    #a.shape = (4,4)
a = np.expand_dims(a,-1)  #a.shape = (4,4,1)
a = a*np.ones((1,1,3))
a.shape                   #(4, 4, 3)

1
投票

更好地帮助将灰色a通道矩阵转换为3通道矩阵。

img3 = np.zeros((gray.shape[0],gray.shape[1],3))
img3[:,:,0] = gray
img3[:,:,1] = gray
img3[:,:,2] = gray
fig = plt.figure(figsize = (15,15))
plt.imshow(img3)

0
投票

不确定我是否理解正确,但在这种情况下广播似乎对我有用:

>>> a = numpy.array([[1,2], [3,4]])
>>> c = numpy.zeros((4, 2, 2))
>>> c[0] = a
>>> c[1:] = a+1
>>> c
array([[[ 1.,  2.],
        [ 3.,  4.]],

       [[ 2.,  3.],
        [ 4.,  5.]],

       [[ 2.,  3.],
        [ 4.,  5.]],

       [[ 2.,  3.],
        [ 4.,  5.]]])

0
投票

我建议你使用准系统numpy.concatenate()只是因为下面的代码显示它是所有其他建议答案中最快的:

# sample 2D array to work with
In [51]: arr = np.random.random_sample((12, 34))

# promote the array `arr` to 3D and then concatenate along `axis 2`
In [52]: arr3D = np.concatenate([arr[..., np.newaxis]]*3, axis=2)

# verify for desired shape
In [53]: arr3D.shape
Out[53]: (12, 34, 3)

你可以看到下面的时间来说服自己。 (订购:最好到最差):

In [42]: %timeit -n 100000 np.concatenate([arr[..., np.newaxis]]*3, axis=2)
1.94 µs ± 32.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [43]: %timeit -n 100000 np.repeat(arr[..., np.newaxis], 3, axis=2)
4.38 µs ± 46.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [44]: %timeit -n 100000 np.dstack([arr]*3)
5.1 µs ± 57.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [49]: %timeit -n 100000 np.stack([arr]*3, -1)
5.12 µs ± 125 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [46]: %timeit -n 100000 np.tile(arr[..., np.newaxis], 3)
7.13 µs ± 85.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

话虽如此,如果您正在寻找最短的代码,那么您可以使用:

# wrap your 2D array in an iterable and then multiply it by the needed depth
arr3D = np.dstack([arr]*3)

# verify shape
print(arr3D.shape)
(12, 34, 3)

0
投票

这会奏效。 (我认为这不是推荐的方式:-)但也许这是你认为最接近的方式。)

np.array([img, img, img]).transpose(1,2,0)

只需在任何时候堆叠目标(img)(3),并使通道(3)转到最后一个轴。

© www.soinside.com 2019 - 2024. All rights reserved.