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

原文地址:https://www.cnblogs.com/lqchen/p/12346768.html

时间: 2024-08-30 18:23:32

PyTorch张量类型转换的相关文章

pytorch张量数据索引切片与维度变换操作大全(非常全)

(1-1)pytorch张量数据的索引与切片操作1.对于张量数据的索引操作主要有以下几种方式:a=torch.rand(4,3,28,28):DIM=4的张量数据a(1)a[:2]:取第一个维度的前2个维度数据(不包括2):(2)a[:2,:1,:,:]:取第一个维度的前两个数据,取第2个维度的前1个数据,后两个维度全都取到:(3)a[:2,1:,:,:]:取第一个维度的前两个数据,取第2个维度的第1个索引到最后索引的数据(包含1),后两个维度全都取到:(4)a[:2,-3:]:负号表示第2个维

PyTorch为何如此高效好用?

C/C++中 Python 扩展对象的简介 你可能知道可以借助 C/C++扩展 Python,并开发所谓的「扩展」.PyTorch 的所有繁重工作由 C/C++实现,而不是纯 Python.为了定义 C/C++中一个新的 Python 对象类型,你需要定义如下实例的一个类似结构: // Python object that backs torch.autograd.Variable structTHPVariable{ PyObject_HEAD torch::autograd::Variabl

PyTorch官方中文文档:torch

torch 包 torch 包含了多维张量的数据结构以及基于其上的多种数学操作.另外,它也提供了多种工具,其中一些可以更有效地对张量和任意类型进行序列化. 它有CUDA 的对应实现,可以在NVIDIA GPU上进行张量运算(计算能力>=2.0). http://www.aibbt.com/a/pytorch/ 张量 Tensors torch.is_tensor[source] torch.is_tensor(obj) 如果obj 是一个pytorch张量,则返回True 参数: obj (Ob

【PyTorch v1.1.0文档研习】60分钟快速上手

阅读文档:使用 PyTorch 进行深度学习:60分钟快速入门. 本教程的目标是: 总体上理解 PyTorch 的张量库和神经网络 训练一个小的神经网络来进行图像分类 PyTorch 是个啥? 这是基于 Python 的科学计算包,其目标是: 替换 NumPy,发挥 GPU 的作用 一个提供最大灵活性和速度的深度学习研究平台 起步 PyTorch 中的 Tensor 类似于 NumPy 中的 ndarray(这一点类似于 TensorFlow),只不过张量可以充分利用 GPU 来进行加速计算.

PyTorch基础-torch

一.张量数据类型 1.1 pytorch与python数据类型对比 python pytorch Int IntTensor of size() float FloatTensor of size() Int array IntTensor of size [d1,d2,-] Float array FloatTensor of size [d1,d2,-] string ont-hot or Embedding(Word2Vec,glove) 由于PyTorch不是一个完备的语言库,它是面向数

tfboys——tensorflow模块学习(四)

tensorflow功能函数 tf.abs 计算张量的绝对值 abs ( x , name = None ) 定义在:tensorflow/python/ops/math_ops.py. 参考指南:数学>基本数学函数 计算张量的绝对值. 给定一个实数的张量 x,该操作返回一个包含每个元素的绝对值的张量 x.例如,如果 x 是输入元素,y 是输出元素,则此操作将计算\\(y = | x | \\). ARGS: x:一个类型为 float32,float64,int32,或 int64 的 Ten

More Effective C++

条款一:指针与引用的区别 指针与引用看上去完全不同(指针用操作符'*'和'->',引用使用操作符'.'),但是它们似乎有相同的功能.指针与引用都是让你间接引用其他对象.你如何决定在什么时候使用指针,在什么时候使用引用呢? 首先,要认识到在任何情况下都不能用指向空值的引用.一个引用必须总是指向某些对象.因此如果你使用一个变量并让它指向一个对象,但是该变量在某些时候也可能不指向任何对象,这时你应该把变量声明为指针,因为这样你可以赋空值给该变量.相反,如果变量肯定指向一个对象,例如你的设计不允许变量为

【colab pytorch】张量操作

1.在pytorch中,有以下9种张量类型 2.查看张量的基本信息 tensor=torch.randn(3,4,5) print(tensor.size()) print(tensor.type()) print(tensor.dim()) torch.Size([3, 4, 5]) torch.FloatTensor 3 3.命名张量 张量命名是一个非常有用的方法,这样可以方便地使用维度的名字来做索引或其他操作,大大提高了可读性.易用性,防止出错. # 在PyTorch 1.3之前,需要使用

『PyTorch』第二弹_张量

参考:http://www.jianshu.com/p/5ae644748f21# 几个数学概念: 标量(Scalar)是只有大小,没有方向的量,如1,2,3等 向量(Vector)是有大小和方向的量,其实就是一串数字,如(1,2) 矩阵(Matrix)是好几个向量拍成一排合并而成的一堆数字,如[1,2;3,4] 其实标量,向量,矩阵它们三个也是张量,标量是零维的张量,向量是一维的张量,矩阵是二维的张量,除此之外,张量不仅可以是三维的,还可以是四维的.五维的... 一点小注意: 1.由于torc