PyTorch张量类型转换

1 numpy与CUDA之间的转换

1.tensor张量与numpy相互转换

tensor ----->numpy

import torch
a=torch.ones([2,5])

tensor([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
# **********************************
b=a.numpy()

array([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]], dtype=float32)

numpy ----->tensor

import numpy as np
a=np.ones([2,5])

array([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
# **********************************
b=torch.from_numpy(a)

tensor([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]], dtype=torch.float64)

2.tensor张量与list相互转换
tensor—>list

a=torch.ones([1,5])

tensor([[1., 1., 1., 1., 1.]])
# ***********************************
b=a.tolist()

[[1.0, 1.0, 1.0, 1.0, 1.0]]

list—>tensor

a=list(range(1,6))

[1, 2, 3, 4, 5]
# **********************************
b=torch.tensor(a)

tensor([1, 2, 3, 4, 5])

3.tensor张量见类型转换
构建一个新的张量,你要转变成不同的类型只需要根据自己的需求选择即可


tensor = torch.Tensor(3, 5)

# torch.long() 将tensor投射为long类型
newtensor = tensor.long()

# torch.half()将tensor投射为半精度浮点类型
newtensor = tensor.half()

# torch.int()将该tensor投射为int类型
newtensor = tensor.int()

# torch.double()将该tensor投射为double类型
newtensor = tensor.double()

# torch.float()将该tensor投射为float类型
newtensor = tensor.float()

# torch.char()将该tensor投射为char类型
newtensor = tensor.char()

# torch.byte()将该tensor投射为byte类型
newtensor = tensor.byte()

# torch.short()将该tensor投射为short类型
newtensor = tensor.short()

4.type_as() 将张量转换成指定类型张量

>>> a=torch.Tensor(2,5)
>>> a
tensor([[1.9431e-19, 4.8613e+30, 1.4603e-19, 2.0704e-19, 4.7429e+30],
[1.6530e+19, 1.8254e+31, 1.4607e-19, 6.8801e+16, 1.8370e+25]])
>>> b=torch.IntTensor(1,2)
>>> b
tensor([[16843009, 1]], dtype=torch.int32)
>>> a.type_as(b)
tensor([[ 0, -2147483648, 0, 0, -2147483648],
[-2147483648, -2147483648, 0, -2147483648, -2147483648]],
dtype=torch.int32)
>>> a
tensor([[1.9431e-19, 4.8613e+30, 1.4603e-19, 2.0704e-19, 4.7429e+30],
[1.6530e+19, 1.8254e+31, 1.4607e-19, 6.8801e+16, 1.8370e+25]])

1.Pytorch上的数据类型

Pytorch的类型可以分为CPU和GPU上的Tensor, 它们拥有的数据类型是基本上是一样的:
tensor.FloatTensor
tensor.LongTensor
tensor.ByteTensor
tensor.CharTensor
tensor.ShortTensor
tensor.IntTensor
torch.LongTensor
其中torch.Tensor是默认的tensor.FloatTensor的简称。

2.数据类型之间的转换

tensor = torch.Tensor(3, 5)
torch.long() 将tensor投射为long类型:
newtensor = torch.long()
torch.int()将该tensor投射为int类型:
newtensor = torch.int()
torch.double()将该tensor投射为double类型:
newtensor = torch.double()

一般,只要在Tensor后加long(), int(), double(), float(), byte()等函数就能将Tensor的类型进行转换
除此之外,可以使用type()函数,data为Tensor数据类型,data.type()给出data的类型,如果使用data.type(torch.FloatTensor)则强制转换为torch.FloatTensor类型的张量, 如果不知道什么类型,可以使用tensor_1.type_as(tensor_2), 将tensor_1转换成tensor_2。

  1.  
    self = torch.LongTensor(3, 5)
  2.  
    # 转换为其他类型
  3.  
    print self.type(torch.FloatTensor)

3.cuda数据类型,cpu类型和一般的数据类型

如果没有特别说明:tensor是cpu上的变量
使用gpu张量:tensor.cuda()
使用cpu张量:tensor.cpu()
Variable转换成普通的Tensor: variable.data()
Tesnor转换成numpy array的格式:tensor.numpy()

numpy数据转换成Tensor: torch.from_numpy(np_data)
Tensor转换成Variable: Variable(tensor)

Pytorch中的Tensor常用的类型转换函数(inplace操作):

(1)数据类型转换

  在Tensor后加 .long(), .int(), .float(), .double()等即可,也可以用.to()函数进行转换,所有的Tensor类型可参考https://pytorch.org/docs/stable/tensors.html

(2)数据存储位置转换

  CPU张量 ---->  GPU张量,使用data.cuda()

  GPU张量 ----> CPU张量,使用data.cpu()

(3)与numpy数据类型转换

  Tensor---->Numpy  使用 data.numpy(),data为Tensor变量

  Numpy ----> Tensor 使用 torch.from_numpy(data),data为numpy变量

(4)与Python数据类型转换

  Tensor ----> 单个Python数据,使用data.item(),data为Tensor变量且只能为包含单个数据

  Tensor ----> Python list,使用data.tolist(),data为Tensor变量,返回shape相同的可嵌套的list

(5)剥离出一个tensor参与计算,但不参与求导

  Tensor后加 .detach()

  官方解释为:

  Returns a new Tensor, detached from the current graph. The result will never require gradient. Returned Tensor shares the same storage with the original one. In-place modifications on either of them will be seen, and may trigger errors in correctness checks. 

  (以前这个功能用过.data(),但现在不推荐使用了)

2 张量数据类型的转换

Pytorch中tensor的类型

  • Pytorch中定义了8种CPU张量类型和对应的GPU张量类型,CPU类型(如torch.FloatTensor)中间加一个cuda即为GPU类型(如torch.cuda.FloatTensor)
  • torch.Tensor()、torch.rand()、torch.randn() 均默认生成 torch.FloatTensor型
  • 相同数据类型的tensor才能做运算

一个例子:

  • torch.FloatTensor(2,3) #构建一个2*3 Float类型的张量
  • torch.DoubleTensor(2,3) #构建一个2*3 Double类型的张量
  • torch.HalfTensor (2,3) #构建一个2*3 HalfTenso类型的张量
  • torch.ByteTensor(2,3) #构建一个2*3 Byte类型的张量
  • torch.CharTensor(2,3) #构建一个2*3 Char类型的张量
  • torch.ShortTensor(2,3) #构建一个2*3 Short类型的张量
  • torch.IntTensor(2,3) #构建一个2*3 Int类型的张量
  • torch.LongTensor(2,3) #构建一个2*3 Long类型的张量
import torch
print(torch.FloatTensor(2,3).type()) #构建一个2*3 Float类型的张量 print(torch.DoubleTensor(2,3).type()) #构建一个2*3 Double类型的张量 print(torch.HalfTensor (2,3).type()) #构建一个2*3 HalfTenso类型的张量 print(torch.ByteTensor(2,3).type()) #构建一个2*3 Byte类型的张量 print(torch.CharTensor(2,3).type()) #构建一个2*3 Char类型的张量 print(torch.ShortTensor(2,3).type()) #构建一个2*3 Short类型的张量 print(torch.IntTensor(2,3).type()) #构建一个2*3 Int类型的张量 print(torch.LongTensor(2,3).type()) #构建一个2*3 Long类型的张量 torch.FloatTensor torch.DoubleTensor torch.HalfTensor torch.ByteTensor torch.CharTensor torch.ShortTensor torch.IntTensor torch.LongTensor

tensor数据类型转换方法

  • 使用独立的函数如 int(),float()等进行转换
  • 使用torch.type()函数,直接显示输入需要转换的类型
  • 使用type_as()函数,将该tensor转换为另一个tensor的type

使用独立的函数

import torch

tensor = torch.randn(2, 2) print(tensor.type()) # torch.long() 将tensor转换为long类型 long_tensor = tensor.long() print(long_tensor.type()) # torch.half()将tensor转换为半精度浮点类型 half_tensor = tensor.half() print(half_tensor.type()) # torch.int()将该tensor转换为int类型 int_tensor = tensor.int() print(int_tensor.type()) # torch.double()将该tensor转换为double类型 double_tensor = tensor.double() print(double_tensor.type()) # torch.float()将该tensor转换为float类型 float_tensor = tensor.float() print(float_tensor.type()) # torch.char()将该tensor转换为char类型 char_tensor = tensor.char() print(char_tensor.type()) # torch.byte()将该tensor转换为byte类型 byte_tensor = tensor.byte() print(byte_tensor.type()) # torch.short()将该tensor转换为short类型 short_tensor = tensor.short() print(short_tensor.type()) torch.FloatTensor torch.LongTensor torch.HalfTensor torch.IntTensor torch.DoubleTensor torch.FloatTensor torch.CharTensor torch.ByteTensor torch.ShortTensor

使用torch.type()函数

type(new_type=None, async=False)如果未提供new_type,则返回类型,否则将此对象转换为指定的类型。 如果已经是正确的类型,则不会执行且返回原对象,用法如下:

t1 = torch.LongTensor(3, 5) print(t1.type()) # 转换为其他类型 t2=t1.type(torch.FloatTensor) print(t2.type()) torch.LongTensor torch.FloatTensor

使用type_as()函数

  • 这个函数的作用是将该tensor转换为另一个tensor的type,可以同步完成转换CPU类型和GPU类型,如torch.IntTensor-->torch.cuda.floatTendor.
  • 如果张量已经是指定类型,则不会进行转换
t1=torch.Tensor(2,3) t2=torch.IntTensor(3,5) t3=t1.type_as(t2) print(t3.type()) torch.IntTensor

主要参考:

https://blog.csdn.net/qq_40357974/article/details/101697721

https://blog.csdn.net/weixin_40446557/article/details/88221851

https://www.cnblogs.com/sbj123456789/p/10839020.html

https://zhuanlan.zhihu.com/p/64647295

猜你喜欢

转载自www.cnblogs.com/lqchen/p/12346768.html