定义Tensor数据类型
Tensor默认的数据类型是torch.float32。让我们来看一个例子:
- 定义一个默认数据类型的tensor
下面展示一些内联代码片
。
x = torch.ones(2, 2)
print(x)
print(x.dtype())
tensor([[1., 1.],
[1., 1.]])
torch.float32
- 当定义一个tensor的时候指定数据类型
# define a tensor with specific data type
x = torch.ones(2, 2, dtype=torch.int8)
print(x)
print(x.dtype())
tensor([[1., 1.],
[1., 1.]], dtype=torch.int8)
torch.int8
改变tensor的数据类型
使用.type方法来改变tensor的数据类型:
- 定义一个torch.uint8类型的tensor:
x = torch.ones(1, dtype=torch.uint8)
print(x.dtype)
torch.uint8
- 改变数据类型
x = x.type(torch.float)
print(x.type)
torch.float32
把tensor转换为numpy数组
- 定义一个tensor
x = torch.rand(2, 2)
print(x)
print(x.dtype)
tensor([[0.8074, 0.5738],
[0.1123, 0.2345]])
torch.float32
- 把tensor转换为numpy数组
y = x.numpy()
print(y)
print(y.dtype)
[[0.8074, 0.5738],
[0.1123, 0.2345]]
dtype('float32')
把numpy数组转换为tensor
- 定义一个numpy数组
import numpy as np
x = np.zeros((2, 2), dtype=np.float32)
print(x)
print(x.dtype)
[[0., 0.],
[0., 0.]]
float32
- 把numpy数组转换为tensor
y = torch.from_numpy(x)
print(y)
print(y.dtype)
tensor([[0., 0.],
[0., 0.]])
torch.float32
在设备之间移动tensor
PyTorch的tensors默认存储在CPU,可以使用GPU来加速。与numpy相比,这是主要的优势。我们可以使用.to方法来实现将tensors移动到CUDA 设备上。
- 在CPU 上定义一个tensor:
x = torch.tensor([1.5, 2])
print(x)
print(x.device)
tensor([1.5, 2.])
cpu
- 定义一个CUDA 设备
# define a cuda/gpu device
if torch.cuda.is_available():
device = torch.device("cuda:0")
- 将tensor移动到CUDA上:
x = x.to(device)
print(x)
print(x.device)
tensor([1.5, 2.], device="cuda:0)
cuda:0
- 我们也可以将CUDA 上的tensor移动到CPU 上:
# define a cpu device
device = torch.device("cpu")
x = x.to(device)
print(x)
print(x.device)
tensor([1.5, 2.])
cpu
- 我们也可以直接在指定的设备上创建tensor:
# define a tensor on device
device = torch.device("cuda:0")
x = torch.ones(2, 2, device=device)
print(x)
tensor([[1., 1.],
[1., 1.], device="cuda:0")