【PyTorch】张量超详细介绍(数据类型、生成、操作、计算)

本文详细介绍PyTorch中张量的基本概念、数据类型、生成方法、操作与计算等内容,帮助读者快速掌握张量的使用技巧。
该文章已生成可运行项目,

主要内容

一、张量的数据类型、默认类型、类型转换。
二、张量的生成:torch.tensor()、torch.Tensor()、张量和NumPy数据互相转换、随机数生成张量、函数生成等。
三、张量操作:改变张量的形状、获取张量中的元素、拼接和拆分等。
四、张量计算:比较大小、基本运算、统计相关计算等。


目录

一、简介

数学中
标量:单独的数
向量:一行或一列数组
矩阵:二维数组
张量:维度超过2的数组

PyTorch中
张量(Tensor)是一种数据结构,可以是一个标量、一个向量、一个矩阵,甚至是更高维度的数组。

所以PyTorch中的张量(Tensor)和Numpy中的数组(ndarray)非常相似。

二、张量的数据类型

2.1 数据类型

Torch定义了七种CPU tensor类型和八种GPU tensor类型:

Data type CPU tensor GPU tensor
32-bit floating point torch.FloatTensor torch.cuda.FloatTensor
64-bit floating point torch.DoubleTensor torch.cuda.DoubleTensor
16-bit floating point N/A torch.cuda.HalfTensor
8-bit integer (unsigned) torch.ByteTensor torch.cuda.ByteTensor
8-bit integer (signed) torch.CharTensor torch.cuda.CharTensor
16-bit integer (signed) torch.ShortTensor torch.cuda.ShortTensor
32-bit integer (signed) torch.IntTensor torch.cuda.IntTensor
64-bit integer (signed) torch.LongTensor torch.cuda.LongTensor

2.2 类型转换

在torch中默认的数据类型是32位浮点型(torch.FlaotTensor)

默认情况下,torch.Tensor就是torch.FlaotTensor
设置默认的数据类型:torch.set_default_tensor_type()
查看和设置张量数据类型:torch.tensor([1.2, 3.4]).dtype

(1)张量的数据类型

print(torch.tensor([1.2, 3.4]).dtype)

>>>torch.float32

(2)设置默认类型

torch.set_default_tensor_type(torch.DoubleTensor)
print(torch.tensor([1.2, 3.4]).dtype)

>>>torch.float64

(3)数据类型转换

a = torch.tensor([1.2, 3.4])
print("a.dtype:", a.dtype)
print("a.long():", a.long().dtype)
print("a.int():", a.int().dtype)
print("a.float():", a.float().dtype)

>>>a.dtype: torch.float32
>>>a.long(): torch.int64
>>>a.int(): torch.int32
>>>a.float(): torch.float32

三、张量的生成

3.1 torch.tensor()生成

Python的列表或序列可以通过torch.tensor()函数构造张量。

(1)将Python的列表转化为张量

A = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
print(A)

>>>tensor([[1., 2.],
           [3., 4.]])

(2)查看维度和元素数量:

A = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
print(A)
print("A的维度:", A.shape)  # 查看维度
print("A的维度:", A.size())  # 查看维度
print("A的元素数量:", A.numel())  # 查看元素数量

>>>tensor([[1., 2.],
           [3., 4.]])
>>>A的维度: torch.Size([2, 2])
>>>A的维度: torch.Size([2, 2])
>>>A的元素数量: 4

(3)指定元素类型、是否计算梯度

B = torch.tensor((1, 2, 3), dtype=torch.float32, requires_grad=True)
print(B)

>>>tensor([1., 2., 3.], requires_grad=True)

(4)计算 s u m ( B 2 ) sum(B^2) sum(B2)在每个元素上的梯度

B = torch.tensor((1, 2, 3), dtype=torch.float32, requires_grad=True)
print(B)
Y = B.pow(2).sum()
print(Y)
Y.backward()
print(B.grad)

>>>tensor([1., 2., 3.], requires_grad=True)
>>>tensor(14., grad_fn=<SumBackward0>)
>>>tensor([2., 4., 6.])

输出结果为每个位置上的梯度—— 2 × B 2\times B 2×B,注意:只有浮点型才能计算梯度,其他类型计算梯度时会报错。

3.2 torch.Tensor()生成

(1)将list转化为张量

将list转化为张量,与torch.tensor()相同:

C = torch.Tensor([1.0, 2.0])
print(C)

>>>tensor([1., 2.])

(2)根据维数生成特定尺寸张量

D = torch.Tensor(2,3)
print(D)

>>>tensor([[0.0000e+00, 0.0000e+00, 4.2039e-45],
           [0.0000e+00, 1.4013e-45, 0.0000e+00]])

(3)xxx_likes()——生成与指定张量维数相同、性质相似的张量

E = torch.Tensor([[1.0, 2.0], [3.0, 4.0]])
print(E)
print(torch.zeros_like(E))  # 零张量
print(torch.ones_like(E))  # 单位张量
print(torch.rand_like(E))  # 随机张量

>>>tensor([[1., 2.],
           [3., 4.]])
>>>tensor([[0., 0.],
           [0., 0.]])
>>>tensor([[1., 1.],
           [1., 1.]])
>>>tensor([[0.5060, 0.8078],
           [0.0232, 0.1987]])

(4)new_xxx()——生成与指定张量性质相似的张量

F = torch.tensor([2, 3], dtype=torch.float16, requires_grad=True)
print(F)
print(F.new_tensor([[1, 2], [3, 4]]))   # 新张量
print(F.new_full((3, 3), fill_value=1))   # 3*3使用fill_value填充张量
print(F.new_zeros((3, 3)))  # 3*3的全0张量
print(F.new_empty((3, 3)))  # 3*3的空张量
print(F.new_ones((3, 3)))  # 3*3的全1张量

>>>tensor([2., 3.], dtype=torch.float16, requires_grad=True)
>>>tensor([[1., 2.],
           [3., 4.]], dtype=torch.float16)
>>>tensor([[1., 1., 1.],
           [1., 1., 1.],
           [1., 1., 1.]], dtype=torch.float16)
>>>tensor([[0., 0., 0.],
           [0., 0., 0.],
           [0., 0., 0.]], dtype=torch.float16)
>>>tensor([[0., 0., 0.],
           [0., 0., 0.],
           [0., 0., 0.]], dtype=torch.float16)
>>>tensor([[1., 1., 1.],
           [1., 1., 1.],
           [1., 1., 1.]], dtype=torch.float16)

3.3 张量和NumPy数据互相转换

(1)利用NumPy数组生成tensor

Gnp = np.ones((3, 3))
GTensor1 = torch.as_tensor(Gnp)
GTensor2 = torch.from_numpy(Gnp)
print(GTensor1)
print(GTensor2)

>>>tensor([[1., 1., 1.],
           [1., 1., 1.],
           [1., 1., 1.]], dtype=torch.float64)
>>>tensor([[1., 1., 1.],
           [1., 1., 1.],
           [1., 1., 1.]], dtype=torch.float64)       

此时tensor的数据类型为float64,因为Numpy生成的数组默认就是64位浮点型数组。

(2)tensor转化为numpy数组

HTensor = torch.Tensor(2, 3)
Hnp = HTensor.numpy()
print(Hnp)

>>>[[7.826805e-03 7.826805e-03 1.261169e-44]
    [0.000000e+00 1.401298e-45 0.000000e+00]]

3.4 随机数生成张量

生成随机数前,可以使用torch.manual_seed()函数,指定随机数种子,保证生成的随机数可以重复出现。

(1)torch.normal——正太分布:

torch.manual_seed(111)
print(torch.normal(mean=0.0, std=torch.tensor(1.0)))  # 均值为0,标准差为1
print(torch.normal(mean=0.0, std=torch.arange(1, 5.0)))  # 均值为0,标准差分别为1、2、3、4

>>>tensor(-0.1222)
>>>tensor([-0.7573,  2.0832,  0.9908,  2.1260])
torch.manual_seed(111)
# 均值分别为1、2、3、4,标准差分别为1、2、3、4
print(torch.normal(mean=torch.arange(1, 5.0), std=torch.arange(1, 5.0)))  

>>>tensor([0.8778, 0.4855, 6.1248, 5.3211])
torch.manual_seed(111)
print(torch.rand(3, 4))  # 均值为0,标准差为1的3*4张量 

>>>tensor([[0.7156, 0.9140, 0.2819, 0.2581],
           [0.6311, 0.6001, 0.9312, 0.2153],
           [0.6033, 0.7328, 0.1857, 0.5101]])

(2)生成维度相同的随机张量

# 生成和其他张量尺寸相同的随机数张量
torch.manual_seed(111)
I = torch.ones(2, 3)
print(torch.rand_like(I))

>>>tensor([[0.7156, 0.9140, 0.2819],
           [0.2581, 0.6311, 0.6001]])
# 生成服从标准正太分布的随机数张量
J = torch.randn(3, 3)
print(J)
print(torch.rand_like(J))
>>>tensor([[-1.7776,  0.5832, -0.2682],
           [ 0.0241, -1.3542
本文章已经生成可运行项目
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

望天边星宿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值