Numpy和Pytorch中数据类型的转换

数据类型的转换

  1. numpy:numpy中的数据类型详见:https://numpy.org/doc/stable/reference/arrays.dtypes.html
    可以直接用astype()对其进行转换

  2. 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(torch.double)
print(tensor.dtype,tensor_long.dtype,tensor_double.dtype)
#>>> torch.float32 torch.int64 torch.float64

存储位置的转换

  • CPU → \rightarrow GPU: tensor.cuda()
  • GPU → \rightarrow CPU: tensor.cpu()

括号里面可以有设备序号的参数,也可以用to(),一般如下:

DEVICE = torch.device('cuda' if torch.cuda.is_available else 'cpu')
tensor.to(DEVICE)

与numpy,torch中数据的转换

  • torch → \rightarrow numpy: tensor.numpy()

  • numpy → \rightarrow torch: torch.Tensor(arr)torch.tensor(arr)或者torch.from_numpy()

    NOTE:GPU中的数据不能直接转换为numpy中的数据,要先转化成CPU上的数据。torch.Tensor(arr)得到的数据类型是torch.float32也就是单精度数据,会改变原始数据类型,这种类型在神经网络计算中比较常见,而其他两种不会。

举例2:

arr = tensor.numpy()
arr_double = arr.astype(np.float64)
tensor_T = tensor.Tensor(arr_doubel)
tensor_t = tensor.tensor(arr_double)
tensor_n = tensor.from_numpy(arr_double)
print(arr.dtype,arr_double.dtype,tensor_T.dtype,tensor_t.dtype,tensor_n.dtype)
#>>> float32 float64 torch.float32 torch.float64 torch.float64

torch中损失函数对于不同数据类型的要求

损失函数的用法参见:https://pytorch.org/docs/stable/nn.html#loss-functions,这里只说数据类型。

  • torch.nn.CrossEntropyLoss:计算过程中的数据都是torch.float32,但是target的数据类型是torch.long,也就是长整型,因为要转换为one-hot向量;
  • torch.nn.BCELoss:用于二分类情况,一般搭配nn.Sigmoid()类使用,这里的target类型是torch.flaot32也就是默认类型;

举例:(来源官网)

>>> loss = nn.CrossEntropyLoss()
>>> input = torch.randn(3, 5, requires_grad=True)
>>> target = torch.empty(3, dtype=torch.long).random_(5)
>>> output = loss(input, target)
>>> output.backward()

>>> m = nn.Sigmoid()
>>> loss = nn.BCELoss()
>>> input = torch.randn(3, requires_grad=True)
>>> target = torch.empty(3).random_(2)
>>> output = loss(m(input), target)
>>> output.backward()

猜你喜欢

转载自blog.csdn.net/Huang_Fj/article/details/120798943