einops库中rearrange,reduce和repeat的介绍

用法介绍

einops是一个简洁优雅操作张量的库,并且支持对numpypytorchtensorflow中的张量进行操作,该库最大的优点是函数的使用逻辑清晰明了,其中中常用的三个函数分别是rearrangerepeatreduce

  • rearrange: 用于对张量的维度进行重新变换排序,可用于替换pytorch中的reshapeviewtransposepermute等操作
  • repeat: 用于对张量的某一个维度进行复制,可用于替换pytorch中的repeat
  • reduce: 类似于tensorflow中的reduce操作,可以用于求平均值,最大最小值的同时压缩张量维度

einopsrearrangerepeatreduce的函数细节介绍如下所示

def rearrange(inputs, pattern, **axes_lengths) ⟶ \longrightarrow transform_inputs

  • inputs (tensor): 表示输入的张量
  • pattern (str): 表示张量维度变换的映射关系
  • **axes_lengths: 表示按照指定的规格形式进行变换

def repeat(inputs, pattern, **axes_lengths) ⟶ \longrightarrow transform_inputs

  • inputs (tensor): 表示输入的张量
  • pattern (str): 表示张量按照某个维度复制的映射关系
  • **axes_lengths: 表示按照指定的规格形式进行复制

def reduce(inputs, pattern, reduction, **axes_lengths) ⟶ \longrightarrow transform_inputs

  • inputs (tensor): 表示输入的张量
  • pattern (str): 表示张量执行某种运算做操作后维度变换的映射关系
  • reduction (str): 表示运算操作的类型,分别有’max’‘min’‘sum’‘mean’‘prod’
  • **axes_lengths: 表示按照指定的规格形式进行运算操作

代码示例

einops库中rearrange函数的代码示例如下所示

# suppose we have a set of 32 images in "h w c" format (height-width-channel)
>>> images = [np.random.randn(30, 40, 3) for _ in range(32)]
# stack along first (batch) axis, output is a single array
>>> rearrange(images, 'b h w c -> b h w c').shape
(32, 30, 40, 3)
# concatenate images along height (vertical axis), 960 = 32 * 30
>>> rearrange(images, 'b h w c -> (b h) w c').shape
(960, 40, 3)
# concatenated images along horizontal axis, 1280 = 32 * 40
>>> rearrange(images, 'b h w c -> h (b w) c').shape
(30, 1280, 3)
# reordered axes to "b c h w" format for deep learning
>>> rearrange(images, 'b h w c -> b c h w').shape
(32, 3, 30, 40)
# flattened each image into a vector, 3600 = 30 * 40 * 3
>>> rearrange(images, 'b h w c -> b (c h w)').shape
(32, 3600)
# split each image into 4 smaller (top-left, top-right, bottom-left, bottom-right), 128 = 32 * 2 * 2
>>> rearrange(images, 'b (h1 h) (w1 w) c -> (b h1 w1) h w c', h1=2, w1=2).shape
(128, 15, 20, 3)
# space-to-depth operation
>>> rearrange(images, 'b (h h1) (w w1) c -> b h w (c h1 w1)', h1=2, w1=2).shape
(32, 15, 20, 12)

einops库中repeat函数的代码示例如下所示

# a grayscale image (of shape height x width)
>>> image = np.random.randn(30, 40)
# change it to RGB format by repeating in each channel
>>> repeat(image, 'h w -> h w c', c=3).shape
(30, 40, 3)
# repeat image 2 times along height (vertical axis)
>>> repeat(image, 'h w -> (repeat h) w', repeat=2).shape
(60, 40)
# repeat image 2 time along height and 3 times along width
>>> repeat(image, 'h w -> h (repeat w)', repeat=3).shape
(30, 120)
# convert each pixel to a small square 2x2. Upsample image by 2x
>>> repeat(image, 'h w -> (h h2) (w w2)', h2=2, w2=2).shape
(60, 80)
# pixelate image first by downsampling by 2x, then upsampling
>>> downsampled = reduce(image, '(h h2) (w w2) -> h w', 'mean', h2=2, w2=2)
>>> repeat(downsampled, 'h w -> (h h2) (w w2)', h2=2, w2=2).shape
(30, 40)

einops库中reduce函数的代码示例如下所示

>>> x = np.random.randn(100, 32, 64)
# perform max-reduction on the first axis
>>> y = reduce(x, 't b c -> b c', 'max')
# same as previous, but with clearer axes meaning
>>> y = reduce(x, 'time batch channel -> batch channel', 'max')
>>> x = np.random.randn(10, 20, 30, 40)
# 2d max-pooling with kernel size = 2 * 2 for image processing
>>> y1 = reduce(x, 'b c (h1 h2) (w1 w2) -> b c h1 w1', 'max', h2=2, w2=2)
# if one wants to go back to the original height and width, depth-to-space trick can be applied
>>> y2 = rearrange(y1, 'b (c h2 w2) h1 w1 -> b c (h1 h2) (w1 w2)', h2=2, w2=2)
>>> assert parse_shape(x, 'b _ h w') == parse_shape(y2, 'b _ h w')
# Adaptive 2d max-pooling to 3 * 4 grid
>>> reduce(x, 'b c (h1 h2) (w1 w2) -> b c h1 w1', 'max', h1=3, w1=4).shape
(10, 20, 3, 4)
# Global average pooling
>>> reduce(x, 'b c h w -> b c', 'mean').shape
(10, 20)
# Subtracting mean over batch for each channel
>>> y = x - reduce(x, 'b c h w -> () c () ()', 'mean')
# Subtracting per-image mean for each channel
>>> y = x - reduce(x, 'b c h w -> b c () ()', 'mean')
### Numpy Reshape Rearrange 的区别 Numpy中的`reshape`函数用于改变数组的形状而不改变其数据。这通常涉及调整维度的数量或大小,但保持原始元素顺序不变[^1]。 另一方面,在某些(如TensorFlowPyTorch)中使用的`rearrange`方法不仅能够重置张量的尺寸,还可以更灵活地重新排列这些维度的位置以及应用其他复杂的模式匹配来操作数据结构[^2]。 #### `numpy.reshape` 此功能允许用户通过提供新的shape参数来定义目标维度。如果新形状与原形状兼容,则返回具有相同数据的新视图;如果不兼容则会创建副本并填充必要值以适应请求的形式。 ```python import numpy as np original_array = np.array([[1, 2], [3, 4]]) reshaped_array = original_array.reshape(4,) print(reshaped_array) ``` 输出将是 `[1 2 3 4]` ,这里我们将二维矩阵展平成了一维向量。 #### `rearrange` 对于更加复杂的数据重组需求来说,可以利用第三方包比如`einops`提供的`rearrange`工具。它支持基于字符串表达式的强大语法来进行多样的轴交换、压缩展开等动作: ```python from einops import rearrange input_tensor = np.random.rand(8, 3, 32, 32) transformed_tensor = rearrange(input_tensor,'b c h w -> b (h w) c') ``` 上述例子展示了如何把批量图像特征从 `(batch_size, channels, height, width)` 转换成 `(batch_size, pixels, channels)` 形式,其中像素数量等于高度乘宽度。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

道2024

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值