各种数值数都可以称为张量。
torch.Tensor([1, 2, 3])
torch.Tensor([[1., -1.], [1., -1.]])
torch.Tensor(np.arange(12).reshape(3, 4))
torch.Tensor(np.array([[]1, 2, 3], [4, 5, 6]))
注意:这里括号内都表示的是shape
torch.empty([3, 4])
torch.ones([3, 4])
torch.zeros([3, 4])
torch.rand([3, 4]) # 创建3行4列的随机值的tensor,区间是[0, 1]
torch.randint(low=0, high=10, size=[3, 4])
torch.randn([3, 4])
shapesizeitem()是将一个张量的值 以一个python数字形式返回,但该方法只能包含一个元素的张量
对于包含多个元素的张量,可以考虑tolist()方法。
tensor.item()
tensor.tolist()
tensor.numopy()
tensor.size()
类似于numpy中的reshape,是一种浅拷贝。
tensor.view(3, 4)
tensor.dim()
tensor.max()
tensor.t()
tensor.transpose()
tensor.permute() # 可以指定维度
也是用: ,是和numpy的操作一样的。
tensor[0, :, :]
tensor.dtype
CUDA 是一种NVIDIA退出的通用并行计算架构,该架构能够使GPU解决复杂的计算问题。
print(torch.cuda.is_available())
接收一个字符串
torch.device("cpu")
torch.device("gpu") # 如果有几块GPU,则可以指定使用第几块
torch.device("cuda:0")
torch.device("cuda")
a = torch.zero([2, 3])
a.to(device)
>> tensor([[0, 0, 0], [0, 0, 0]], device="cuda:0")