加入收藏 | 设为首页 | 会员中心 | 我要投稿 驾考网 (https://www.jiakaowang.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

Pytorch如何实现List和Tensor的转化 要关注哪些问题

发布时间:2023-06-14 11:08:34 所属栏目:语言 来源:
导读:这篇主要是介绍“Pytorch如何实现List和Tensor的转化,要注意哪些问题”的内容了,下文有实例供大家参考,对大家了解操作过程或相关知识有一定的帮助,而且实用性强,希望这篇文章能帮助大家解决Pytorch如

这篇主要是介绍“Pytorch如何实现List和Tensor的转化,要注意哪些问题”的内容了,下文有实例供大家参考,对大家了解操作过程或相关知识有一定的帮助,而且实用性强,希望这篇文章能帮助大家解决Pytorch如何实现List和Tensor的转化,要注意哪些问题的问题,下面我们一起来了解看看吧。

一、List Tensor转Tensor (torch.cat)

高维tensor

二、List Tensor转Tensor (torch.stack)

持续更新一些常用的Tensor操作,比如List,Numpy,Tensor之间的转换,Tensor的拼接,维度的变换等操作。

其它Tensor操作如 einsum等见:待更新。

用到两个函数:

torch.cat

torch.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.]]])

这篇关于“Pytorch如何实现List和Tensor的转化,要注意哪些问题”的文章就介绍到这了,更多相关的内容,小编将为大家输出更多高质量的实用文章!

(编辑:驾考网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章