沿轴线的numpy挤压不会起作用

时间:2015-05-06 09:57:25

标签: python numpy

我尝试使用numpy squeeze来移除轴。挤压前的形状是:

(252, 70, 1, 3, 1)

我的脚本行是:

var_u0 = np.squeeze(var_u0,axis=(2,))

但结果挤压了所有矩阵:

var_u0.shape = (252L, 70L, 3L)

当我在命令提示符中执行相同操作时,这件事情很有用......我不明白。

如果有人有想法,坦克!

1 个答案:

答案 0 :(得分:0)

你可以这样做 -

# Random input array
A = np.random.rand(4,3,1,5,1)

# Axis to be removed
rem_axis = 2

# Squeezed output array
A_squeezed = A.reshape(np.delete(A.shape,rem_axis))

此处有whos确认信息 -

In [435]: whos
Variable     Type       Data/Info
---------------------------------
A            ndarray    4x3x1x5x1: 60 elems, type `float64`, 480 bytes
A_squeezed   ndarray    4x3x5x1: 60 elems, type `float64`, 480 bytes

rem_axis = 4whos显示 -

In [438]: whos
Variable     Type       Data/Info
---------------------------------
A            ndarray    4x3x1x5x1: 60 elems, type `float64`, 480 bytes
A_squeezed   ndarray    4x3x1x5: 60 elems, type `float64`, 480 bytes

为了使其更加健壮,您可以引入一个检查以查看要移除的轴是否是单个维度。那么,在这种情况下你可以做 -

# Squeezed output array
if A.shape[rem_axis]!=1:
    print('Error: Specified axis is not singleton.')
    A_squeezed = np.array([]) # Set empty as a sign of failure
         # Change it to any other signal value or keep as A itself
else:
    A_squeezed = A.reshape(np.delete(A.shape,rem_axis))