pytorch中tensor张量数据类型的转化方式
2020-02-13 11:32
851 查看
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]])
以上这篇pytorch中tensor张量数据类型的转化方式就是小编分享给大家的全部内容了,希望能给大家一个参考
您可能感兴趣的文章:
相关文章推荐
- 计算机底层数据的处理方式(汇编后将所有数据都转化为补码二进制数据,所有类型信息都会消失)
- 关于C语言中数据类型的转化方式
- Java技术-将java中Map类型数据转化为json数据并以Ajax形式返回
- c语言数据类型、存取方式、类型转换
- JS数据类型判断方式及优缺点、String常用方法
- 将表单序列化类型的数据转化成对象的处理(允许对象中包含对象)
- sas数据读取详解:SAS读取小工具,读取数值类型的注意事项,lrecl选项,四种读取数据方式以及数据指针的位置、读取mess data的、infile语句及其选项(dsd dlm missover truncover obs firstobs)、proc import、自定义缺失值
- go数据类型之结构体(用户自定义类型两种方式)
- matlab纠错---数据类型转化
- 转:C#调用C++的DLL搜集整理的所有数据类型转换方式
- VC Afx全局函数 数据类型 字符串转化函数
- 数据类型转换三种方式
- Java各种数据类型之间的转化
- js数据类型int和string转化
- c 与 c++ 的几个类型转化方式存在的差异
- Oracle 数据类型及存储方式(六)
- 浅谈进制转化与JAVA数据类型
- JS中检测数据类型的四种方式及每个方式的优缺点
- C#调用C++的DLL搜集整理的所有数据类型转换方式
- symbian基本数据类型转化汇集(一)