张量的运算是深度学习的基本操作,深度学习框架的重要功能之一就是支持张量的定义与运算。
1. 张量的数据类型
数据pytorch类型CPU上的张量GPU上的张量32位浮点数torch.float32
torch.floattorch.FloatTensortorch.cuda.FloatTensor64位浮点数torch.float64
torch.doubletorch.DoubleTensortorch.cuda.DoubleTensor16位浮点数torch.float16
torch.halftorch.HalfTensortorch.cuda.HalfTensor8位无符号整数torch.uint8torch.ByteTensortorch.cuda.ByteTensor8位带符号整数torch.int8torch.CharTensortorch.cuda.CharTensor16位带符号整数torch.int16
torch.shorttorch.ShortTensortorch.cuda.ShortTensor32位带符号整数torch.int32
torch.inttorch.IntTensortorch.cuda.IntTensor64位带符号整数torch.int64
torch.longtorch.LongTensortorch.cuda.LongTensor布尔型rorch.booltorch.BoolTensortorch.cuda.BoolTensor
2. python列表和numpy数组转为python张量
2.1 转换python列表为python张量
t = torch.tensor([1, 2, 3, 4], dtype=torch.float32)
print(t)
print(t.dtype)
2.2 转换numpy数组为python张量
arr = np.array([1, 2, 3, 4])
t = torch.tensor(t)
print(t)
print(t.dtype)
3. 张量的创建方式
3.1 通过torch.tensor函数创建张量
该方法类似于numpy中的array方法,可以指定数据类型。例子如2.1所示。
3.2 通过pytorch内置的函数创建张量
同样类似于numpy中的数据创建,可以指定张量形状或数据类型。
t1 = torch.rand(3, 3)
print(t1)
print('=' * 50)
t2 = torch.randn(2, 3, 4)
print(t2)
print('=' * 50)
t3 = torch.zeros(2, 3)
print(t3)
print('=' * 50)
t4 = torch.ones(2, 2)
print(t4)
print('=' * 50)
t5 = torch.eye(2, 2)
print(t5)
print('=' * 50)
t6 = torch.randint(0, 100, (3, 3))
print(t6)
3.3 通过已知张量创建现状相同的张量
形状相同,但元素可能不一样。
t = torch.randn(3, 3)
print(t)
t_like = torch.zeros_like(t)
print(t_like)
3.4 通过已知张量创建形状不同但数据类型相同的张量
已知张量的数据类型,创建一个形状不同但数据类型相同的新张量。此方法较少使用
t = torch.rand(1, 3)
print(t)
t_new = t.new_zeros(3, 3)
print(t_new)
3. 和张量维度相关的方法
pytorch张量形状相关的一些函数。
t = torch.randn(3, 4, 5)
print(t.ndimension())
print(t.nelement())
print(t.size())
print(t.shape)
print('=' * 50)
t2 = torch.randn(12)
print(t2.view(3, 4))
print(t2.view(-1, 3))
print(t2.data_ptr())
print(t2.view(3, 4).transpose(0, 1).data_ptr())
print(t2.view(3, 4).transpose(0, 1).contiguous().data_ptr())
4. 张量的索引和切片
pytorch张量支持类似numpy的索引(Indexing)和切片(Slicing)操作。
t = torch.randn(3, 4, 5)
print(t)
print(t[1, 2, 3])
print(t[:, 1:-1, 2:4])
t[1, 2, 3] = 0.9999
print(t > 0)
print(t[t>0])
总结,pytorch的张量基本操作与numpy非常类似。
Original: https://blog.csdn.net/m0_45827246/article/details/122203780
Author: 饕餮&化骨龙
Title: pytorch中张量的创建和维度的操作
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/761620/
转载文章受原作者版权保护。转载请注明原作者出处!