Pytorch数据类型与转换(torch.tensor,torch.FloatTensor)
作者:ggbooo 时间:2023-03-31 13:32:36
Pytorch数据类型与转换(torch.tensor,torch.FloatTensor)
之前遇到转为tensor转化为浮点型的问题,今天整理下,我只讲几个我常用的,如果有更好的方法,欢迎补充
一、torch.tensor
1.首先讲下torch.tensor,默认整型数据类型为torch.int64,浮点型为torch.float32
2.这是我认为平常最爱用的转数据类型的方法,可以用dtype去定义数据类型
二、torch.FloatTensor
1.这个函数不要乱用,首先它可以将变量转化为浮点型32位,这里注意此时的变量类型为列表,或数组等,此时参数为单个变量
2.当函数参数为整形时,表示生成矩阵的维度,此时参数可以为多个变量
补充:还有一种方法通过numpy数组定义数据类型,再转化为tensor,这个方法不多讲了。
扩展:Pytorch数据类型转换
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
。
self = torch.LongTensor(3, 5)
# 转换为其他类型
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数据类似pytorch中的tensor, 更重要的是tensor可以使用GPU来加速,并且变成Variable可以实现自动求导的功能,Variable是对Tensor对象的封装。
转载链接:https://www.jianshu.com/p/eb7c6af28922
逻辑值True和False转成0和1. +0
print(y)
print(y+0)
## 输出结果
tensor([ True, False, False, True, True, False, False, True, True, False])
tensor([1, 0, 0, 1, 1, 0, 0, 1, 1, 0])
来源:https://blog.csdn.net/ggbooo/article/details/129025526
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
深入了解Golang官方container/heap用法
基于Python实现一个简易的数据管理系统
![](https://img.aspxhome.com/file/2023/4/92274_0s.png)
使用Python将语音转换为文本的方法
SQL Server开发过程中的的常见问题总结
python 实现批量xls文件转csv文件的方法
浅谈Python中re.match()和re.search()的使用及区别
![](https://img.aspxhome.com/file/2023/9/121659_0s.jpg)
使用 django orm 写 exists 条件过滤实例
一文吃透Go的内置RPC原理
![](https://img.aspxhome.com/file/2023/6/103736_0s.png)
python图像处理基本操作总结(PIL库、Matplotlib及Numpy)
![](https://img.aspxhome.com/file/2023/8/78568_0s.png)
Python基于多线程实现抓取数据存入数据库的方法
MySQL触发器的使用场景及方法实例
vscode调试container中的程序的方法步骤
![](https://img.aspxhome.com/file/2023/8/130898_0s.png)
python实现批量命名照片
![](https://img.aspxhome.com/file/2023/3/77043_0s.png)
如何解决AJAX中跨域访问出现'没有权限'的错误
js与jquery获取父级元素,子级元素,兄弟元素的实现方法
进一步了解Python中的XML 工具
SQLServer 存储过程简介与使用方法
python中property和setter装饰器用法
![](https://img.aspxhome.com/file/2023/6/127026_0s.jpg)
Python使用pickle模块报错EOFError Ran out of input的解决方法
JS实现仿Windows经典风格的选项卡Tab切换代码
![](https://img.aspxhome.com/file/2023/2/56172_0s.png)