torch 和 numpy 中 flatten() 降维操作



简洁版:
都是降维展开操作。不同在于:

  • numpy n d a r r a y . f l a t t e n ( ) ndarray.flatten() ndarray.flatten()
    只能返回一维数组。参数是字符串,可设置按行或按列展开。
  • torch t o r c h . f l a t t e n ( i n p u t , s t a r t d i m = 0 , e n d d i m = − 1 ) → T e n s o r torch.flatten(input, start_dim=0, end_dim=- 1) → Tensor torch.flatten(input,startdim=0,enddim=1)Tensor
    可以返回高维张量,可以指定开始、结束展开的维度,即部分展开。参数是维度


详细版:
叙述了numpytorch 中常见的关于 高维数组 展开操作的一些函数。

  • numpy
    • flatten():展成一维,产生数据副本
    • ravel() :展成一维,不产生副本(修改会改变原数据)
    • squeeze() :压缩维数为 1 的维度
  • torch
    • flatten():展成低维张量(可以不是一维),产生数据副本
    • squeeze() :降维, 压缩维数为 1 的维度
    • unsqueeze() :增加维数为 1 的维度

1. numpy 展平操作

1.1 ndarray.flatten()

  • 适用于numpy对象
    flatten是numpy.ndarray.flatten的一个函数,即返回一个折叠成一维的数组。

Parameters:
ndarray.flatten(order=‘C’) Return a copy of the array collapsed into one dimension. order : {‘C’, ‘F’, ‘A’, ‘K’}, optional:

  • ‘C’ means to flatten in row-major (C-style) order.
  • ‘F’ means to flatten in column-major (Fortran- style) order.
  • ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise.
  • ‘K’ means to flatten a in the order the elements occur in memory.
    The default is ‘C’.
  • 举例:
    参数是 str , ‘C’: 按行展开, ’F‘: 按列展开
>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> a.flatten('C')
array([1, 2, 3, 4, 5, 6])
>>> a.flatten('F')
array([1, 4, 2, 5, 3, 6])

python 中 list 展开:
list,使用列表表达式。

参考资料:Python中flatten( ),matrix.A用法说明


1.2 ndarray.ravel()

n d a r r a y . f l a t t e n ( ) ndarray.flatten() ndarray.flatten() n d a r r a y . r a v e l ( ) ndarray.ravel() ndarray.ravel() 都是对向量的展平操作,区别在于:

  • n d a r r a y . f l a t t e n ( ) ndarray.flatten() ndarray.flatten() : 返回原数组副本
  • n d a r r a y . r a v e l ( ) ndarray.ravel() ndarray.ravel(): 不返回原数组副本
>>> a.flatten()[0] = -1
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> a.ravel()[0] = -1
>>> a
array([[-1,  2,  3],
       [ 4,  5,  6]])

1.3 ndarray.squeeze()

n d a r r a y . s q u e e z e ( d i m = a ) ndarray.squeeze(dim = a) ndarray.squeeze(dim=a): 对维数为1的维数降维,, 可以指定维数

>>> b = np.array([[[1],[2]]])
>>> b
array([[[1],
        [2]]])
>>> b.shape
(1, 2, 1)
>>> b.squeeze()
array([1, 2])
>>> b.squeeze(0)
array([[1],
       [2]])
>>> b.squeeze(2)
array([[1, 2]])


2. torch 展平操作

2.1 torch.flatten()

t o r c h . f l a t t e n ( i n p u t , s t a r t d i m = 0 , e n d d i m = − 1 ) → T e n s o r torch.flatten(input, start_dim=0, end_dim=- 1) → Tensor torch.flatten(input,startdim=0,enddim=1)Tensor

可以指定开始、结束展开的维度。
如从 dim = 1 开始, shape: (2, 2, 2) -> (2, 4)

>>> t = torch.tensor([[[1, 2],
...                    [3, 4]],
...                   [[5, 6],
...                    [7, 8]]])
>>> torch.flatten(t)
tensor([1, 2, 3, 4, 5, 6, 7, 8])
>>> torch.flatten(t, start_dim=1)
tensor([[1, 2, 3, 4],
        [5, 6, 7, 8]])

官方文档:TORCH.FLATTEN


2.2 torch.squeeze() 和 torch.unsqueeze()

  • torch 中也提供 squeeze 函数, 同 numpy

torch.squeeze(input, dim=None) → Tensor(官方文档)

>>> x = torch.zeros(2, 1, 2, 1, 2)
>>> x.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x)         # 压缩维数为 1 的维度
>>> y.size()
torch.Size([2, 2, 2])
>>> y = torch.squeeze(x, 0)     #  压缩维度 0, 0 维不为 1
>>> y.size()
torch.Size([2, 1, 2, 1, 2])
>>> y = torch.squeeze(x, 1)     # 压缩维度 1,  1 维为 1
>>> y.size()
torch.Size([2, 2, 1, 2])
  • 此外, torch 中还提供了 torch.unsqueeze,扩充维度

t o r c h . u n s q u e e z e ( i n p u t , d i m ) → T e n s o r torch.unsqueeze(input, dim) → Tensor torch.unsqueeze(input,dim)Tensor(官方文档)

>>> x = torch.tensor([1, 2, 3, 4])
>>> torch.unsqueeze(x, 0)
tensor([[ 1,  2,  3,  4]])
>>> torch.unsqueeze(x, 1)
tensor([[ 1],
        [ 2],
        [ 3],
        [ 4]])
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python,.flatten()是一个函数,用于将多维数组压平成一维数组。它在torchnumpy都有不同的用法。 在torch,.flatten()函数可以用于将tensor压平成一维。例如,如果有一个shape为(2, 2, 3, 3)的tensor x,那么通过x.flatten()可以得到一个shape为(36,)的一维tensor b。此外,还可以通过指定参数来改变压平的方式,例如x.flatten(0)可以将tensor按照第一个维度压平,得到shape为(4, 3, 3)的tensor c,x.flatten(1)可以将tensor按照第二个维度压平,得到shape为(2, 6, 3)的tensor d。,x.flatten('F')会得到。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [torch.flatten、np.flatten 详解](https://blog.csdn.net/qq_28949847/article/details/128568723)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Pythonflatten( ),matrix.A用法说明](https://download.csdn.net/download/weixin_38499336/12850013)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值