np.stack函数详细解析

最关键的问题, 如何确定stack之后的数组维度?

The stacked array has one more dimension than the input arrays.

源码中有一code
result_ndim = arrays[0].ndim + 1         # 这就是增加了一个维度

a 是3*4的矩阵
b 也是3*4的矩阵
因为合并之后增了一个维度,所以合并之后的矩阵的shape应该是
(x,x,x)
如果axis=0, 那么就在第0个位置放入,也就变成(2,x,x), 而原来的矩阵就是(3,4)
所以最后的矩阵就是(2,3,4)

如果axis=1, 那么就在第1个位置放入,也就变成(x,2,x), 而原来的矩阵就是(3,4)
所以最后的矩阵就是(3,2,4)

如果axis=2, 那么就在第2个位置放入,也就变成(x, x,2 ), 而原来的矩阵就是(3,4)
所以最后的矩阵就是(3,4, 2)

例子在下边  !

np.stack 完整的源码

    arrays = [asanyarray(arr) for arr in arrays]
    if not arrays:
        raise ValueError('need at least one array to stack')
        
	# 确保每个矩阵的维度都是一样的
    shapes = set(arr.shape for arr in arrays)
    if len(shapes) != 1:
        raise ValueError('all input arrays must have the same shape')

    result_ndim = arrays[0].ndim + 1
    axis = normalize_axis_index(axis, result_ndim)

    sl = (slice(None),) * axis + (_nx.newaxis,)
    expanded_arrays = [arr[sl] for arr in arrays]
    return _nx.concatenate(expanded_arrays, axis=axis, out=out)
一般来说,有三个维度的矩阵, 
axis =0 代表矩阵
axis = 1 代表行
axis = 2 代表元素

e.g.    a and b都是3*4的矩阵
>>> print(a)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

>>> print(b)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
 
  # 矩阵级别的合并,相当于两个矩阵叠在了一起,本身每个矩阵形状没有发生变化
>>> np.stack((a,b),axis=0)      
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]]])

# 行级别的合并, 每个矩阵发生变化
>>> np.stack((a,b), axis=1)
array([[[ 0,  1,  2,  3],
        [ 0,  1,  2,  3]],

       [[ 4,  5,  6,  7],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [ 8,  9, 10, 11]]])

# 元素级别的合并,每个矩阵发生变化
>>> np.stack((a,b), axis=2)
array([[[ 0,  0],
        [ 1,  1],
        [ 2,  2],
        [ 3,  3]],

       [[ 4,  4],
        [ 5,  5],
        [ 6,  6],
        [ 7,  7]],

       [[ 8,  8],
        [ 9,  9],
        [10, 10],
        [11, 11]]])

猜你喜欢

转载自blog.csdn.net/weixin_36149892/article/details/86657030
今日推荐