不同数组类型的维度增加与减少方法

目录

1、numpy数组

1)、np.expand_dims()

2)、np.squeeze()

3)、其他方法

4)两个数组的组合

2、PyTorch 数组

1)、torch.squeeze()

2)、torch.unsqueenze()

3)、其他方法

1、numpy数组

使用 np.expand_dims() 为数组增加指定的轴, np.squeeze() 将数组中的轴进行压缩减小维度。

1)、np.expand_dims()

import numpy as np

a = np.random.random((3, 3, 3))
对 a 数组增加 0 维度。shape=(1, 3, 3, 3)
a = np.expand_dims(a, axis=0)
print(a.shape)

2)、np.squeeze()

import numpy as np

a = np.random.random((1, 3, 3, 3))
删除 a 数组的 0 维度。shape=(3, 3, 3)
可以指定维度,也可以不指定,不指定即全部删除维度为 1 的维度
采用 a.squeeze() 也可以
a = np.squeeze(a, axis=0)
print(a.shape)

3)、其他方法

import numpy as np

a = np.random.random((3, 3, 3))
对 a 数组增加 0 维度。shape=(1, 3, 3, 3)
或则 a.reshape((1, 3, 3, 3))
a = np.reshape(a, (1, 3, 3, 3))
print(a.shape)

4)两个数组的组合

  • 垂直组合
import numpy as np

a = np.array([[8,4],[7,4],[1,3]])
b = np.array([[5,8],[7,4],[1,3]])
法一
c = np.concatenate((a,b),axis=0)
法二
d = np.vstack((a,b))
print(c.shape)
print(d.shape)

输出
(6, 2)
(6, 2)
  • 水平组合
import numpy as np

a = np.array([[8,4],[7,4],[1,3]])
b = np.array([[5,8],[7,4],[1,3]])
法一
c = np.concatenate((a,b),axis=1)
法二
d = np.hstack((a,b))
print(c.shape)
print(d.shape)

输出
(3, 4)
(3, 4)
  • ★ 深度组合:沿着纵轴方向组合

该方法组合方式示图:

不同数组类型的维度增加与减少方法
import numpy as np

a = np.array([8,7,1])
b = np.array([5,7,1])

d = np.dstack((a,b))
print(d.shape)

输出
(1, 3, 2)

或者:每一块里面按各自的对应组合

不同数组类型的维度增加与减少方法
import numpy as np

a = np.array([[8,4],[7,4],[1,3]])
b = np.array([[5,8],[7,4],[1,3]])

d = np.dstack((a,b))
print(d.shape)

输出
(3, 2, 2)

2、PyTorch 数组

使用 torch.squeeze() 和 torch.unsqueenze() 函数可以实现数据维度的增加和删除。

1)、torch.unsqueeze()

import torch
a = torch.randn((3, 3, 3))
指定在哪一个维度上增加维度
b = a.unsqueeze(0)
c = a.unsqueeze(1)
print(b.shape)
print(c.shape)

2)、torch.squeeze()

import torch
a = torch.randn((1, 3, 3, 1, 3))
指定删减哪一个维度
注意:若采用 a.squeeze_(0) 则会对原数据进行更改。即,原数据 a 的维度会被更改
b = a.squeeze(0)
c = a.squeeze(3)
print(b.shape)
print(c.shape)

3)、其他方法

import torch
a = torch.randn((1, 3, 3, 1, 3))
与 np.reshape() 类似。可以直接更改维度,但总维度不能变。
b = a.view(3, 3, 3)
print(b.shape)

Original: https://blog.csdn.net/qq_45100200/article/details/121599672
Author: 清纯世纪
Title: 不同数组类型的维度增加与减少方法

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/760958/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球