pytorch实现Tensor变量之间的转换
作者:zhe_csdn 时间:2023-06-28 15:41:31
系统默认是torch.FloatTensor类型
data = torch.Tensor(2,3)是一个2*3的张量,类型为FloatTensor
data.cuda()就转换为GPU的张量类型,torch.cuda.FloatTensor类型
(1) CPU或GPU之间的张量转换
在Tensor后加long(), int(), double(),float(),byte()等函数就能将Tensor进行类型转换type()函数,
data为Tensor数据类型,data.type()为给出data的类型,
如果使用data.type(torch.FloatTensor)则强制转换为torch.FloatTensor类型张量
(2) CPU张量转化成GPU张量
data.cuda()
(3) GPU张量转化成CPU张量
data.cpu()
(4) Variable变量转换成普通的Tensor
Variable是一个Wrapper,装在里面的data是tensor,如果Var是Variable变量,使用Var.data获得Tensor变量
(5) Tensor与numpy array之间的转换
Tensor->numpy 使用data.numpy(),data为Tensor变量
Numpy->Tensor 使用torch.from_numpy(data),data为numpy变量
(6) 分别获取张量和数组的尺寸,注意size的使用
torch 张量
获取张量的尺寸 a.size()
numpy 数组
获取数组的尺寸 b.shape
获取数组中元素的个数: b.size (这里和张量中的属性的size的含义不同)
(7) 升维和降维的问题
unsqueeze(N)升维到第N维
squeeze(N)降维第N维
需要做如下操作:
x = x.unsqueeze(0) 假如x=(3,1080,1920) 操作后 x = (1,3,1080,1920)
降维也是做同样的操作
来源:https://blog.csdn.net/zhe_csdn/article/details/93655053
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python就将所有的英文单词首字母变成大写
Dreamwaver 常见问答解答
SQL SERVER 的SQL语句优化方式小结
Python工程师面试题 与Python Web相关
SQL server 定时自动备份数据库的图文方法
![](https://img.aspxhome.com/file/2023/5/110985_0s.jpg)
python统计RGB图片某像素的个数案例
![](https://img.aspxhome.com/file/2023/3/77683_0s.jpg)
Python中偏函数用法示例
python中sklearn的pipeline模块实例详解
![](https://img.aspxhome.com/file/2023/6/80406_0s.png)
使用Python-OpenCV向图片添加噪声的实现(高斯噪声、椒盐噪声)
vue上传图片组件编写代码
![](https://img.aspxhome.com/file/2023/2/126542_0s.jpg)
Go语言实现牛顿法求平方根函数的案例
![](https://img.aspxhome.com/file/2023/5/107355_0s.jpg)
一文理解MySQL数据库的约束与表的设计
![](https://img.aspxhome.com/file/2023/2/70372_0s.png)
js获取checkbox值的方法
Python 实现绘制子图及子图刻度的变换等问题
![](https://img.aspxhome.com/file/2023/3/117473_0s.png)
Python闭包与闭包陷阱举例详解
![](https://img.aspxhome.com/file/2023/6/115716_0s.png)
Python中的进程操作模块(multiprocess.process)
PHP注释语法规范与命名规范详解篇
关于多元线性回归分析——Python&SPSS
![](https://img.aspxhome.com/file/2023/0/67230_0s.jpg)
无阻塞加载脚本分析[全]
django的分页器Paginator 从django中导入类
![](https://img.aspxhome.com/file/2023/9/102809_0s.png)