天天日报丨Pytorch实现List Tensor转Tensor,reshape拼接等操作
【资料图】
目录
一、List Tensor转Tensor (torch.cat)高维tensor二、List Tensor转Tensor (torch.stack)持续更新一些常用的Tensor操作,比如List,Numpy,Tensor之间的转换,Tensor的拼接,维度的变换等操作。
其它Tensor操作如 einsum等见:待更新。
用到两个函数:
torch.cattorch.stack一、List Tensor转Tensor (torch.cat)
// An highlighted block
>>> t1 = torch.FloatTensor([[1,2],[5,6]])
>>> t2 = torch.FloatTensor([[3,4],[7,8]])
>>> l = []
>>> l.append(t1)
>>> l.append(t2)
>>> ta = torch.cat(l,dim=0)
>>> ta = torch.cat(l,dim=0).reshape(2,2,2)
>>> tb = torch.cat(l,dim=1).reshape(2,2,2)
>>> ta
tensor([[[1., 2.],
[5., 6.]],
[[3., 4.],
[7., 8.]]])
>>> tb
tensor([[[1., 2.],
[3., 4.]],
[[5., 6.],
[7., 8.]]])高维tensor
** 如果理解了2D to 3DTensor,以此类推,不难理解3D to 4D,看下面代码即可明白:**
>>> t1 = torch.range(1,8).reshape(2,2,2)
>>> t2 = torch.range(11,18).reshape(2,2,2)
>>> l = []
>>> l.append(t1)
>>> l.append(t2)
>>> torch.cat(l,dim=2).reshape(2,2,2,2)
tensor([[[[ 1., 2.],
[11., 12.]],
[[ 3., 4.],
[13., 14.]]],
[[[ 5., 6.],
[15., 16.]],
[[ 7., 8.],
[17., 18.]]]])
>>> torch.cat(l,dim=1).reshape(2,2,2,2)
tensor([[[[ 1., 2.],
[ 3., 4.]],
[[11., 12.],
[13., 14.]]],
[[[ 5., 6.],
[ 7., 8.]],
[[15., 16.],
[17., 18.]]]])
>>> torch.cat(l,dim=0).reshape(2,2,2,2)
tensor([[[[ 1., 2.],
[ 3., 4.]],
[[ 5., 6.],
[ 7., 8.]]],
[[[11., 12.],
[13., 14.]],
[[15., 16.],
[17., 18.]]]])二、List Tensor转Tensor (torch.stack)
代码:
import torch t1 = torch.FloatTensor([[1,2],[5,6]]) t2 = torch.FloatTensor([[3,4],[7,8]]) l = [t1, t2] t3 = torch.stack(l, dim=2) print(t3.shape) print(t3) ## output: ## torch.Size([2, 2, 2]) ## tensor([[[1., 3.], ## [2., 4.]], ## [[5., 7.], ## [6., 8.]]])
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
X 关闭
X 关闭
- 15G资费不大降!三大运营商谁提供的5G网速最快?中国信通院给出答案
- 2联想拯救者Y70发布最新预告:售价2970元起 迄今最便宜的骁龙8+旗舰
- 3亚马逊开始大规模推广掌纹支付技术 顾客可使用“挥手付”结账
- 4现代和起亚上半年出口20万辆新能源汽车同比增长30.6%
- 5如何让居民5分钟使用到各种设施?沙特“线性城市”来了
- 6AMD实现连续8个季度的增长 季度营收首次突破60亿美元利润更是翻倍
- 7转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 8充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 9好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 10名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?

