为什么我们要在pytorch中使用to()方法?

Las*_*tK7 7 python pytorch

这个方法我已经见过很多次了。这样做的目的和好处是什么?

pro*_*sti 9

为什么我们要在pytorch中使用to(device)方法?

torch.Tensor.to是多用途方法。

不仅可以进行类型转换,还可以进行 CPU 到 GPU 张量移动以及 GPU 到 CPU 张量移动:

tensor = torch.randn(2, 2)  
print(tensor)
tensor = tensor.to(torch.float64) 
print(tensor) #dtype=torch.float64
tensor = tensor.to("cuda") 
print(tensor) #device='cuda:0', dtype=torch.float64)
tensor = tensor.to("cpu") 
print(tensor) #dtype=torch.float64
tensor = tensor.to(torch.float32) 
print(tensor) # won't print dtype=torch.float32 since it is by default
Run Code Online (Sandbox Code Playgroud)

由于CPU和GPU是不同种类的存储器,因此它们必须有一种通信方式。这就是为什么我们有to("cuda"),并且to("cpu")我们调用张量。

通常当您加载训练数据集(图像)时:

  • 您可以从 URL 下载它们(例如 MNIST http://deeplearning.net/data/mnist/mnist.pkl.gz
  • 打开它们的包装
  • 将它们转换为 numpy 数组
  • 将 numpy 数组转换为张量(因为这很快)
  • 将它们移至 GPU 进行训练。to("cuda")

您可以像这样创建张量并将它们移动到 GPU。

torch.zeros(1000).to("cuda")
Run Code Online (Sandbox Code Playgroud)

但有一个技巧,有时你甚至可以将它们直接加载到 GPU,而不会弄乱 CPU。

torch.zeros(1000, device="gpu")
Run Code Online (Sandbox Code Playgroud)

  • “将 numpy 数组转换为张量(因为这很快)”,其他方法可能会更慢。 (3认同)