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数据类型不一致。