数据类型的转换
-
numpy:
numpy
中的数据类型详见:https://numpy.org/doc/stable/reference/arrays.dtypes.html
可以直接用astype()
对其进行转换 -
torch:
torch
中的数据类型详见:
https://pytorch.org/docs/stable/tensors.html
对于Tensor
类型的数据,可以直接在其后加上.long()
,.float()
,.double()
,.int()
等。也可以利用.to()
,里面的参数可以是dtype
包含的数据类型,也可以是cpu
或者cuda
。
numpy
中默认的数据类型是float64
,而torch中默认的数据类型是float32
。
举例1:
import numpy as np
arr = np.random.randn(2,2)
arr_float32 = arr.astype(np.float32)
print(arr.dtype, arr_float32.dtype)
#>>> dtype('float64') dtype('float32')
import torch
tensor = torch.randn(2,2)
tensor_long = tensor.long()
tensor_double = tensor.to