pytorch Tensor

134 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

pytorch Tensor

参考文档

Pytorch 之 Tensor 属性与操作

Pytorch中支持的tensor的数据类型及它们的相互转换

三种类型转换函数

PyTorch 深度学习:60分钟快速入门

数据类型的具体介绍和使用(好)

多GPU运行

numpy和tensor

  • numpy和torch tensor互通,可互转,共享潜在内存,即改变其中一个,另一个也会改变

    • # torch 转 numpy
      a = torch.ones(5)
      b = a.numpy()
      # numpy 转 torch
      a = torch.Tensor(b)
      data = torch.from_numpy(data)
      
  • 转换路径

    numpy--->torch tensor--->torch cuda tensor

tensor转cuda

import numpy as np
​
data = ('A', 'd', 'v')
data = np.array(data)
​
data = torch.ones((3, 5))
print(data)
# data = torch.from_numpy(data)
data.to("cuda")
TypeError: can't convert np.ndarray of type numpy.str_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.

*可知能转tensor的类型只有:*float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.

查看tensorType

import torch
​
x = torch.ones((3, 5))
print(x)
​
print('type(x): ', type(x))
print('x.dtype: ', x.dtype)
print('x.device:', x.device)
​
x.to("cuda") # note:这里必须使用一个变量接收,因为不是改变原数据x,正确写法如下:
x = x.to("cuda")
print('type(x): ', type(x))
print('x.dtype: ', x.dtype)
print('x.device:', x.device)
tensor([[1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.]])
# cpu上
type(x):  <class 'torch.Tensor'>
x.dtype:  torch.float32
x.device: cpu
# gpu上
type(x):  <class 'torch.Tensor'>
x.dtype:  torch.float32
x.device: cuda:0

总结:

  • type()函数是查看变量的类型,即属于什么class
  • var.dtype是查看该tensor中数据的类型
  • var.device是查看变量在哪个设备上

Tensor的cuda类型和gpu类型

前提:即在tensor从cpu转到gpu上时,通过查看其dtype可以发现,他的dtype没有变化,都是torch.xxxx,与预想中会自动转成torch.cuda.xxxx不符,即与设想自动转换成cuda数据类型不一致。

常用写法

y = y.to(device=device, dtype=torch.float32)
t_l = t.long()
t_f = t.float()