Pytorch基础:张量Tensor
1. 张量类(Tensor)
张量类(Tensor)是深度学习框架必须提供的基础数据结构,神经网络的前向传播和反向传播都是基于 Tensor 类进行的。Tensor 类应具有以下多方面的功能:
- Tensor 应该具有不同的数值类型,以满足不同的精度需求。
- Tensor 的维度应该可以索引、改变。
- 不同类型的 Tensor 之间应可以相互转换。
- Tensor 应该支持常见的数值计算,比如加、减、乘、除。
- Tensor 的设备应该可以在 CPU 和 GPU 之间切换。
2. 数值类型
数据类型 | CPU | GPU |
---|---|---|
32位浮点数 | torch.FloatTensor | torch.cuda.FloatTensor |
64位浮点数 | torch.DoubleTensor | torch.cuda.DoubleTensor |
8位有符号整型 | torch.CharTensor | torch.cuda.CharTensor |
8位无符号整型 | torch.ByteTensor | torch.cuda.ByteTensor |
布尔类型 | torch.BoolTensor | torch.cuda.BoolTensor |
3. 创建方法
3.1 从内置数据类型创建
>>> import torch
>>>
>>> x1=[1,2,3]
>>> x1_tensor=torch.tensor(x1,dtype=torch.int32)
>>> print(x1_tensor)
tensor([1, 2, 3], dtype=torch.int32)
>>>
>>> x1_tensor2=torch.tensor([4,5,6],dtype=torch.int32)
>>> print(x1_tensor2)
tensor([4, 5, 6], dtype=torch.int32)
>>>
>>>
>>> x2 = torch.Tensor([7,8,9])
>>> print(x2,x2.dtype)
tensor([7., 8., 9.]) torch.float32 //默认为torch.float32类型
>>>
3.2 从numpy创建
>>> import numpy as np
>>> x2_numpy=np.array([1,2,3])
>>> x2.tensor=torch.from_numpy(x2_numpy)
>>> x2_tensor=torch.from_numpy(x2_numpy)
>>> print(x2_tensor)
tensor([1, 2, 3], dtype=torch.int32)
>>>
3.3 从已有Tensor创建新的Tensor
接着上面的,直接复制Tensor,但是新的Tensor与旧Tensor只是形状相同,数值却是使用特定的数值进行填充的。
>>> x3_tensor=torch.ones_like(x2_tensor)
>>> print(x3_tensor)
tensor([1, 1, 1], dtype=torch.int32)
3.4 创建随机值或特定值的Tensor
>>> size=[1,3]
>>> x4_tensor=torch.randn(size)
>>> x5_tensor=torch.zeros(size)
>>> print