torch.flatten、np.flatten 详解

超链接:深度学习工作常用方法汇总,矩阵维度变化、图片、视频等操作,包含(torch、numpy、opencv等)


B站视频讲解链接


1. 展平 :flatten

torch版:

x.flatten(n)

将Tensor x展平,默认n为0,也就是将矩阵x展平成一维,
当n>0时,表示前n维不变,之后的维度进行展平处理。

Flatten层用来将输入“压平”,即把多维的输入一维化,常用在从卷积层到全连接层的过渡。Flatten不影响batch的大小。

在这里插入图片描述

torch示例:

import torch
import numpy as np

x = torch.rand((2, 2, 3, 3))
b = x.flatten(0)
c = x.flatten(1)
d = x.flatten(2)
print('x_shape:', x.shape)  # torch.Size([2, 2, 3, 3])
print('b_shape:', b.shape)  # b_shape: torch.Size([36])
print('c_shape:', c.shape)  # c_shape: torch.Size([2, 18])
print('d_shape:', d.shape)  # d_shape: torch.Size([2, 2, 9])

numpy版:

x.flatten()

将矩阵转换为一维,简单理解就是把矩阵拉平拉直(不更改原始数据),np.ravel()返回的是视图,修改会更改原始数据,如同python中的 copy 和 deepcopy的区别。

options order={'C', 'F', 'A', 'K'}

'C': C-style, 行为主要顺序,先从左到右,再从上到下,默认是**'C'**
'F': Fortran-style, 列为主要顺序,先从上到下,再从左到右
'A':如果a是Fortran在内存中连续的,那么'A' 意味着以列主要顺序变平,否则按行排序
'F':按照元素在内存中出现的顺序来拉平a

常用的是前两个

numpy示例:


import numpy as np

x = np.array([[1, 2], [3, 4]])
# 默认为C模式
b = x.flatten()
c = x.flatten('C')
d = x.flatten('F')
print('x_shape:', x.shape)  # (2, 2)
print('b_shape:', b.shape)  # (4,)
print('c_shape:', c.shape)  #
print('d_shape:', d.shape)

print('c:', c)  # c: [1 2 3 4]
print('d:', d)  # d: [1 3 2 4]

猜你喜欢

转载自blog.csdn.net/qq_28949847/article/details/128568723