PyTorch中矩阵的合并

本文详细介绍了如何在PyTorch中使用unsqueeze()、cat()和vstack/hstack/dstack操作处理张量。通过实例展示了维度合并、视图变化以及堆叠技术,适合理解基础数据操作在深度学习中的应用。
摘要由CSDN通过智能技术生成

第一个中括号表示第一个维度,第二个中括号表示第二个维度,以此类推,对某一维度进行合并则该维个数增加

import torch

a = torch.randn(2, 3)
a = torch.unsqueeze(a, 0)
b = torch.cat((a, a), 0)
c = torch.cat((a, a), 1)
d = torch.cat((a, a), 2)
print(a)
print(b)
print(c)
print(d)

输出为

tensor([[[ 0.4198, -0.6766, -1.1429],
         [ 1.5233, -0.7087, -1.0912]]])
tensor([[[ 0.4198, -0.6766, -1.1429],
         [ 1.5233, -0.7087, -1.0912]],

        [[ 0.4198, -0.6766, -1.1429],
         [ 1.5233, -0.7087, -1.0912]]])
tensor([[[ 0.4198, -0.6766, -1.1429],
         [ 1.5233, -0.7087, -1.0912],
         [ 0.4198, -0.6766, -1.1429],
         [ 1.5233, -0.7087, -1.0912]]])
tensor([[[ 0.4198, -0.6766, -1.1429,  0.4198, -0.6766, -1.1429],
         [ 1.5233, -0.7087, -1.0912,  1.5233, -0.7087, -1.0912]]])
import torch

a = torch.randn(2, 3)
a = torch.unsqueeze(a, 0)
c = torch.vstack((a, a))
b = torch.hstack((a, a))
d = torch.dstack((a, a))
print(a)
print(b)
print(c)
print(d)

# c = torch.vstacd((a, a))
# print(c)

# t = torch.arange(16.0).reshape(2, 2, 4)

# a = torch.tensor([1, 2, 3])
# b = torch.tensor([4, 5, 6])
# c = torch.dstacd((a,b))
# print(c)

输出为:

tensor([[[ 0.1947,  1.2356,  2.2314],
         [-0.7753,  1.6233,  1.1481]]])
tensor([[[ 0.1947,  1.2356,  2.2314],
         [-0.7753,  1.6233,  1.1481],
         [ 0.1947,  1.2356,  2.2314],
         [-0.7753,  1.6233,  1.1481]]])
tensor([[[ 0.1947,  1.2356,  2.2314],
         [-0.7753,  1.6233,  1.1481]],

        [[ 0.1947,  1.2356,  2.2314],
         [-0.7753,  1.6233,  1.1481]]])
tensor([[[ 0.1947,  1.2356,  2.2314,  0.1947,  1.2356,  2.2314],
         [-0.7753,  1.6233,  1.1481, -0.7753,  1.6233,  1.1481]]])
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值