pytorch学习笔记之tensor的创建与切片

it2025-04-20  18

直接粘贴代码,其中创建tensor的创建方法不全,有需要的查找,每一行为一个创建方法,每行的第二个#号之后print函数内的操作为对tensor的操作,之后为输出结果,最后为操作的粗略解释

import torch # a = torch.randn(3,4) #创建一个3*4的张量,其中元素为随机的正太数 # a = torch.full([2,2],2) #生成2*2,元素值都为2的张量 # b = torch.Tensor(2,2) # a = torch.arange(0,10,1) #tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 不包含10 # a = torch.linspace(0,10,5) #tensor([ 0.0000, 2.5000, 5.0000, 7.5000, 10.0000]) 包含10 # a = torch.logspace(-1,0,10) #tensor([0.1000, 0.1292, 0.1668, 0.2154, 0.2783, 0.3594, 0.4642, 0.5995, 0.7743, # 1.0000]) 10**x # inx = torch.randperm(10) #tensor([0, 4, 1, 8, 6, 7, 9, 5, 3, 2])将0到10不包含10的数随机打散 # a = torch.rand(4,3,28,28) #print(a[0,0].shape) torch.Size([28, 28]) #a = torch.rand(4,3,28,28) #print(a[:2].shape) torch.Size([2, 3, 28, 28])表示第一个维度到2之前的数组 #a = torch.rand(4,3,28,28) #print(a[:2,:1,:,:].shape) torch.Size([2, 1, 28, 28])如果只有一个:没有数字表示选取所有 #a = torch.rand(4,3,28,28) #print(a[:2,-1:,:,:].shape) torch.Size([2, 1, 28, 28]) :前的-1表示从后往前选取 #a = torch.rand(4,3,28,28) #print(a[:,:,0:28:2,:].shape) torch.Size([4, 3, 14, 28]) 表示从0到28之间隔1个选取一个地址+2,隔行采样 #a = torch.rand(4,3,28,28) #print(a[:,:,::2,:].shape) torch.Size([4, 3, 14, 28]) 表示从头开始隔1个选取一个到结尾 #a = torch.rand(4,3,28,28) #print(a.index_select(0,torch.arange(2)).shape) torch.Size([2, 3, 28, 28]) 表示选取第0维的元素个数为2 #a = torch.rand(4,3,28,28) #print(a[...].shape) 其中...表示所有的维度都取 #a = torch.rand(4,3,28,28) #print(a[1,...].shape) torch.Size([3, 28, 28]) 表示第一维选取地址为1的元素,其他维都取 #a = torch.rand(4,3,28,28) #print(a[:,1,...].shape) torch.Size([4, 28, 28]) 表示第二维选地址为1的元素,其他维度都取 """a = torch.randn(3,4) b = a.ge(0.5) #取a中大于0.5的元素为Ture,小于则为False """ """ a = torch.randn(3,4) b = a.ge(0.5) print(torch.masked_select(a,b)) #结果tensor([0.5200, 2.3639, 1.6268]) 选取a中大于0.5的元素组成一个新的张量 """

今天也是元气满满的一天,明天也要加油啊。

最新回复(0)