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

目录

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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

清纯世纪

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

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

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

打赏作者

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

抵扣说明:

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

余额充值