本文集成代码文件下载地址:
Debug 预备工作
为了方便我们查看张量数据,我们先编写一个用于输出张量数据的函数ptf_tensor
import torch
import random
import string
def ptf_tensor(t,tag='tensor_'):
salt = ''.join(random.sample(string.ascii_letters + string.digits, 5))
if (tag=='tensor_'):tag=tag+salt
print('\nThe info of {}:\n#############################\n @dims: {}\n @size: {}\n @ele_sum: {}\n @dtype: {}\n @data:\n{}\n#############################\n'.format(tag,t.dim(),t.size(),t.numel(),t.dtype,t))
使用方法:ptf_tensor(张量,张量名字或者其他标记信息)
举例:
t2=torch.tensor([[0,1,2],[3,4,5],[6,7,8]])
ptf_tensor(t2,'common')
会有如下输出:
The info of common:
#############################
@dims: 2
@size: torch.Size([3, 3])
@ele_sum: 9
@dtype: torch.int64
@data:
tensor([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
#############################
张量创建
(1)指定数据
t2=torch.tensor([[0,1,2],[3,4,5],[6,7,8]])
ptf_tensor(t2,'common')
(2)特殊的张量
全0的,对角线是1的(单位矩阵),全部元素都是某个值的…
t=torch.zeros(3,3,1)
ptf_tensor(t,'zeros') # size(3,3,1)
t=torch.full((3,3),5.)
ptf_tensor(t,'full') # size(3,3), All elements are 5.
t=torch.eye(5)
ptf_tensor(t,'eye') # 对角线是1,其余是0 ,单位矩阵
(3)随机张量
指定最小最大值,和默认0-1
## 创建随机的张量:
t=torch.randint(low=0,high=4

本文详述了PyTorch中张量的创建、变形、元素选取及拼接等核心操作,通过实例展示了如何利用张量进行高效的数据处理。
最低0.47元/天 解锁文章
1614

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



