x = rearrange(ims, 'b h w c -> b 1 h w 1 c') # functionality of numpy.expand_dims print(x.shape) print(rearrange(x, 'b 1 h w 1 c -> b h w c').shape) # functionality of numpy.squeeze
(6, 1, 96, 96, 1, 3)
(6, 96, 96, 3)
1 2 3 4 5 6 7
# 先将每张图片最大像素值显现出来,让后转化回去,将其余像素填0 x = reduce(ims, 'b h w c -> b () () c', 'max') - ims # 上面的一步没有将维度降下去!!!因为后面与ims进行了计算 # x = reduce(ims, 'b h w c -> b () () c', 'max') 维度变为(6,1,1,3) # x = x - ims 维度变为(6,96,96,3) 利用了广播操作 img = rearrange(x, 'b h w c -> h (b w) c') plt.imshow(img)
Repeating elements
repeat 用于在某个维度上重复,感觉和 np.repeat 差得不多,没有前面的好用
1 2 3
# repeat along a new axis. New axis can be placed anywhere repeat(ims[0], 'h w c -> h new_axis w c', new_axis=5).shape (96, 5, 96, 3)
1 2
# shortcut repeat(ims[0], 'h w c -> h 5 w c').shape
1 2 3
# 同样的repeat中内置了rearrange函数,下面的用法和rearrange一样 img = repeat(ims[0], 'h w c -> h (w repeat) c', repeat=3) plt.imshow(img)
Reduce ⇆ repeat
1 2 3
repeated = repeat(ims, 'b h w c -> b h new_axis w c', new_axis=2) reduced = reduce(repeated, 'b h new_axis w c -> b h w c', 'min') assert numpy.array_equal(ims, reduced)
帮助理解的例子
1 2
img = rearrange(ims, '(b1 b2) h w c -> (h b1) (w b2) c ', b1=2) plt.imshow(img)
rearrange doesn’t change number of elements and covers different numpy functions (like transpose, reshape, stack, concatenate, squeeze and expand_dims)
reduce combines same reordering syntax with reductions (mean, min, max, sum, prod, and any others)
repeat additionally covers repeating and tiling
composition and decomposition of axes are a corner stone, they can and should be used together