目录
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)
本文详细介绍了在NumPy和PyTorch中如何进行数组操作,包括使用np.expand_dims()和np.squeeze()在NumPy中增加或减少数组维度,以及torch.unsqueeze()和torch.squeeze()在PyTorch中的应用。同时,展示了数组的垂直、水平和深度组合方法,以及在PyTorch中通过view()改变数组维度。这些操作对于理解和操作多维数据至关重要。

1040

被折叠的 条评论
为什么被折叠?



