squeeze関数【numpy】
ndarrayオブジェクトから余分な次元を削除する。
使い方は次の2通りがある。
numpy.squeeze(対象となるndarray)
ndarray.squeeze()
簡単にいうと、shapeで形状を確認したときに長さが1の次元を削除するという感じだ。
(3,1,2,3)
code:python
import numpy
a0 = numpy.array(1)
print('a0:', a0)
print(a0.shape)
a1 = a0.squeeze()
print('a1:', a1)
print(a1.shape)
code:text
a0: 1
()
a1: 1
()
スカラに対しては効果無し。
code:python
import numpy
print('a0 =', a0, a0.shape)
a1 = a0.squeeze()
print('a1 =', a1, a1.shape)
print('b0 =', b0, b0.shape)
b1 = b0.squeeze()
print('b1 =', b1, b1.shape)
print('c0 =', c0, c0.shape)
c1 = c0.squeeze()
print('c1 =', c1, c1.shape)
code:text
a1 = 1 ()
1次元のベクトルa0, b0は変化なし
1×1×3の高次元配列c0は3個の要素からなる1次元ベクトルになる。
code:python
import numpy
a0 = numpy.array(1,2,3],[4,5,6)
print('a0 =', a0, a0.shape)
a1 = a0.squeeze()
print('a1 =', a1, a1.shape)
print('b0 =', b0, b0.shape)
b1 = b0.squeeze()
print('b1 =', b1, b1.shape)
1×2×1×1×1×3行列b0をsqueezeすると2×3行列となる。
code:text
# 場合:
[4 5 6]]] (1, 2, 1, 1, 1, 3) 形状が(3, 1, 2, 1, 3)であればは(3, 2, 3)となる。
code:python
a0 = numpy.array([[[1,2,3,1,2,3]],[[1,2,3,1,2,3]],[[1,2,3,1,2,3]]])
print('a0 =', a0, a0.shape)
a1 = a0.squeeze()
print('a1 =', a1, a1.shape)
code:text
a0 = [[[1 2 3
1 2 3]]
[[1 2 3
1 2 3]]
[[1 2 3
1 2 3]]] (3, 1, 2, 1, 3)