# einops 张量操作

10/21 09:29

pip install einops

from einops import rearrange, reduce, repeat # 按给出的模式重组张量

output_tensor = rearrange(input_tensor, 't b c -> b c t') # 结合重组（rearrange）和reduction操作

output_tensor = reduce(input_tensor, 'b c (h h2) (w w2) -> b h w c', 'mean', h2=2, w2=2) # 沿着某一维复制

output_tensor = repeat(input_tensor, 'h w -> h w c', c=3)

``````y = x.view(x.shape[0], -1) # x: (batch, 256, 19, 19)
y = rearrange(x, 'b c h w -> b (c h w)')
``````
•

``````y = x.view(x.shape[0], -1) # x: (batch, 256, 19, 19)
y = rearrange(x, 'b c h w -> b (c h w)', c=256, h=19, w=19)``````

### 更多的检查

``````y = x.view(x.shape[0], -1) # x: (batch, 256, 19, 19)
y = rearrange(x, 'b c h w -> b (c h w)')
``````
• 1
• 2

``````y = x.view(x.shape[0], -1) # x: (batch, 256, 19, 19)
y = rearrange(x, 'b c h w -> b (c h w)', c=256, h=19, w=19)
``````
• 1
• 2

### 对输出的严格定义

``````# depth-to-space
rearrange(x, 'b c (h h2) (w w2) -> b (c h2 w2) h w', h2=2, w2=2)
rearrange(x, 'b c (h h2) (w w2) -> b (h2 w2 c) h w', h2=2, w2=2)
``````
• 1
• 2
• 3

### 一致性

``````reduce(x, 'b c (x dx) -> b c x', 'max', dx=2)
reduce(x, 'b c (x dx) (y dy) -> b c x y', 'max', dx=2, dy=3)
reduce(x, 'b c (x dx) (y dy) (z dz)-> b c x y z', 'max', dx=2, dy=3, dz=4)
``````
• 1
• 2
• 3

``````rearrange(x, 'b c h (w w2) -> b c (h w2) w', w2=2)
``````
• 1

### 与具体框架无关的行为表现

``````y = x.flatten() # 或者 flatten(x)
``````
• 1

• 在numpy, cupy, chainer, pytorch中: `(60,)`
• 在keras, tensorflow.layers, mxnet 和 gluon中: `(3, 20)`

### 与框架使用的具体术语无关

``````np.tile(image, (1, 2))    # 在numpy中
image.repeat(1, 2)        # pytorch的repeat ≈ numpy的tile
``````
• 1
• 2

0
0 收藏

0 评论
0 收藏
0