Pytorch中的variable, tensor与numpy相互转化
来源:https://blog.csdn.net/m0_37592397/article/details/88327248
1.将numpy矩阵转换为Tensor张量
sub_ts = torch.from_numpy(sub_img) #sub_img为numpy类型
- 1
2.将Tensor张量转化为numpy矩阵
sub_np1 = sub_ts.numpy() #sub_ts为tensor张量
- 1
3.将numpy转换为Variable
sub_va = Variable(torch.from_numpy(sub_img))
- 1
4.将Variable张量转化为numpy
sub_np2 = sub_va.data.numpy()
- 1
- 2
应用实例1
# coding=utf-8
import numpy as np
import torch
"""Pytorch中tensor了解"""def just_try():# Tensor可以认为是一个高维数组,和numpy相似,但tensor可以用GPU加速x = torch.FloatTensor(5, 3) # [torch.FloatTensor of size 5x3],预先分配空间print('x: {}'.format(x))print('x.size(): {}'.format(x.size())) # torch.Size([5, 3], torch.Size是tuple对象的子类,支持tuple的所有操作y_tensor_gpu = x.cuda() # 转化为在GPU上的tensorprint('y_tensor_gpu: {}'.format(y_tensor_gpu))def multiple_add():x = torch.FloatTensor(3, 2)y = torch.FloatTensor(3, 2)# 第一种加法result_1 = x + y# 第二种加法result_2 = torch.add(x, y)# 第三种加法result_3 = torch.FloatTensor(3, 2)torch.add(x, y, out=result_3)print('result_1: {}'.format(result_1))print('result_1.size():{}'.format(result_1.size()))print('result_2: {}'.format(result_2))print('result_2.size():{}'.format(result_2.size()))print('result_3: {}'.format(result_3))print('result_3.size():{}'.format(result_3.size()))def inplace_operation():x = torch.FloatTensor(3, 2)y = torch.FloatTensor(3, 2)print('original y: {}'.format(y))# 普通加法,不改变原始的y值result_common = y.__add__(x)print('common add, result_common: {}'.format(result_common))print('common add, y: {}'.format(y))# inplace 加法,改变y值y.__iadd__(x)print('inplace add, y: {}'.format(y))def tensor_vs_numpy():"""tensor 和 numpy 之间的联系:return: """y = torch.FloatTensor(3, 2)print('y: {}'.format(y))# tensor的slice操作与numpy类似print('y slice: {}'.format(y[:, 1]))# 技巧: tensor与numpy之间的转换,互操作比较容易且快速,# Tensor不支持的操作,可以先转换为numpy数组处理,之后再转回tensoraa_tensor = torch.ones(3, 2)print('orignal aa_tensor: {}'.format(aa_tensor))# tensor ---> numpybb_numpy = aa_tensor.numpy() # Note: tensor和numpy之间共享内存,所以他们之间的转换很快,同时也意味着如果其中一个变了,# 另外一个也会随之改变print('bb_numpy: {}'.format(bb_numpy))# numpy ---> tensorcc_tensor = torch.from_numpy(bb_numpy)print('cc_tensor: {}'.format(cc_tensor))bb_numpy += 1print('after adding one, bb_numpy: {}'.format(bb_numpy))print('after adding one, aa_tensor: {}'.format(aa_tensor))print('after adding one, cc_tensor: {}'.format(cc_tensor))if __name__ == '__main__':just_try()print("********************")multiple_add()print("********************")inplace_operation()print("********************")tensor_vs_numpy()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
运行结果
x: tensor([[ 8.4735e-01, 4.5852e-41, 1.4709e-28],[ 3.0645e-41, 9.5032e-04, 4.5852e-41],[ 2.5129e-39, 4.5852e-41, -4.3164e-02],[ 4.5850e-41, 2.6068e-39, 4.5852e-41],[ 3.0926e+00, 4.5852e-41, 2.5129e-39]])
x.size(): torch.Size([5, 3])
y_tensor_gpu: tensor([[ 8.4735e-01, 4.5852e-41, 1.4709e-28],[ 3.0645e-41, 9.5032e-04, 4.5852e-41],[ 2.5129e-39, 4.5852e-41, -4.3164e-02],[ 4.5850e-41, 2.6068e-39, 4.5852e-41],[ 3.0926e+00, 4.5852e-41, 2.5129e-39]], device='cuda:0')
********************
result_1: tensor([[8.4734e-01, 7.6497e-41],[2.3627e-29, 3.0672e-41],[2.2296e-29, 3.0645e-41]])
result_1.size():torch.Size([3, 2])
result_2: tensor([[8.4734e-01, 7.6497e-41],[2.3627e-29, 3.0672e-41],[2.2296e-29, 3.0645e-41]])
result_2.size():torch.Size([3, 2])
result_3: tensor([[8.4734e-01, 7.6497e-41],[2.3627e-29, 3.0672e-41],[2.2296e-29, 3.0645e-41]])
result_3.size():torch.Size([3, 2])
********************
original y: tensor([[1.4718e-28, 3.0645e-41],[2.3627e-29, 3.0672e-41],[2.2296e-29, 3.0645e-41]])
common add, result_common: tensor([[1.7051e-28, 6.1290e-41],[4.7253e-29, 6.1343e-41],[4.4592e-29, 6.1290e-41]])
common add, y: tensor([[1.4718e-28, 3.0645e-41],[2.3627e-29, 3.0672e-41],[2.2296e-29, 3.0645e-41]])
inplace add, y: tensor([[1.7051e-28, 6.1290e-41],[4.7253e-29, 6.1343e-41],[4.4592e-29, 6.1290e-41]])
********************
y: tensor([[1.4718e-28, 3.0645e-41],[4.7253e-29, 6.1343e-41],[4.4592e-29, 6.1290e-41]])
y slice: tensor([3.0645e-41, 6.1343e-41, 6.1290e-41])
orignal aa_tensor: tensor([[1., 1.],[1., 1.],[1., 1.]])
bb_numpy: [[1. 1.][1. 1.][1. 1.]]
cc_tensor: tensor([[1., 1.],[1., 1.],[1., 1.]])
after adding one, bb_numpy: [[2. 2.][2. 2.][2. 2.]]
after adding one, aa_tensor: tensor([[2., 2.],[2., 2.],[2., 2.]])
after adding one, cc_tensor: tensor([[2., 2.],[2., 2.],[2., 2.]])
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
应用实例2
# coding=utf-8
import numpy as np
import torch
from torch.autograd import Variable"""pytorch中Variable了解"""
"""
Variable是Pytorch中autograd自动微分模块的核心。
它封装了Tensor,支持几乎所有的tensor操作。
主要包含如下3个属性:
1. data: 保存Variable所包含的Tensor
2. grad: 保存data对应的梯度,grad也是一个Variable,而不是一个Tensor,和data的形状一样
3. grad_fn: 指向一个Function对象,这个Function用来反向传播计算输入的梯度
"""def about_variable():x = Variable(torch.ones(3, 2), requires_grad=True)y = x.detach().numpy()z = torch.from_numpy(y)print('x: {}'.format(x))print('***************')print('y: {}'.format(y))print('***************')print('z: {}'.format(z))print('***************')print('x.data: {}'.format(x.data))print('***************')print('x.grad: {}'.format(x.grad))# Variable和Tensor具有几乎一致的接口aa_variable = Variable(torch.ones(3, 2))print('torch.cos(aa_variable): {}'.format(torch.cos(aa_variable)))print('torch.cos(aa_variable.data): {}'.format(torch.cos(aa_variable.data)))if __name__ == '__main__':about_variable()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
运行结果
x: tensor([[1., 1.],[1., 1.],[1., 1.]], requires_grad=True)
***************
y: [[1. 1.][1. 1.][1. 1.]]
***************
z: tensor([[1., 1.],[1., 1.],[1., 1.]])
***************
x.data: tensor([[1., 1.],[1., 1.],[1., 1.]])
***************
x.grad: None
torch.cos(aa_variable): tensor([[0.5403, 0.5403],[0.5403, 0.5403],[0.5403, 0.5403]])
torch.cos(aa_variable.data): tensor([[0.5403, 0.5403],[0.5403, 0.5403],[0.5403, 0.5403]])
Pytorch中的variable, tensor与numpy相互转化相关推荐
- Pytorch中的variable, tensor与numpy相互转化的方法
来源:https://blog.csdn.net/pengge0433/article/details/79459679 在使用pytorch作为深度学习的框架时,经常会遇到变量variable.张量 ...
- PyTorch中的Variable类型
1 前言 今天在学习PyTorch~ 之前在莫烦的教程中看到了Variable类型的变量,后来看PyTorch的<Deep Learning with PyTorch: A 60 Minute ...
- Pytorch中的Variable
Pytorch中的Variable pytorch两个基本对象:Tensor(张量)和Variable(变量) 其中,tensor不能反向传播,variable可以反向传播. Varibale包含三个 ...
- pytorch 中的数据类型,tensor的创建
pytorch中的数据类型 import torcha=torch.randn(2,3) b=a.type() print(b)#检验是否是该数据类型 print(isinstance(a,torch ...
- pytorch中的Variable()
参考链接:https://www.cnblogs.com/hellcat/p/8439055.html 函数简介 torch.autograd.Variable是Autograd的核心类,它封装了Te ...
- pytorch中的torch.tensor.repeat以及torch.tensor.expand用法
文章目录 torch.tensor.expand torch.tensor.repeat torch.tensor.expand 先看招 import torch x = torch.tensor([ ...
- Pytorch中的 torch.Tensor() 和 torch.tensor() 的区别
直接在搜索引擎里进行搜索,可以看到官方文档中两者对应的页面: 分别点击进去,第一个链接解释了什么是 torch.Tensor: torch.Tensor 是一个包含单一数据类型元素的多维矩阵(数组). ...
- pytorch中的Variable还有必要使用吗?
pytorch1.6文档 Variable 早在在pytorch0.4已经不需要了 tensor就支持autograd了 所以见到 data=Variable(data) 这样的用法请大胆删除Va ...
- PyTorch中Variable变量与torch.autograd.Variable
一.了解Variable 顾名思义,Variable就是 变量 的意思.实质上也就是可以变化的量,区别于int变量,它是一种可以变化的变量,这正好就符合了反向传播,参数更新的属性. 具体来说,在pyt ...
最新文章
- 微信小程序绑定数据以及自定义指令
- ThoughtWorks微服务架构交流心得
- C primer plus -- Chapter 2
- Sqoop 同步数据到mysql, Can't parse input data: '\N'
- 016_泛型常见通配符
- Ubuntu15.04如何添加163源
- Java连接mysql出现SQL异常,MySQL 这样连接为何出现这样的异常
- Gzip,BZip2,Lzo,Snappy比较
- angularJs为什么在近几年风头一时无二?
- Cocos2dx--------内存管理
- Jmeter(十九) 后置处理器JSON Extractor 提取json的多个值
- 思科(Cisco)路由器常用命令总结
- 怎么把程序下载到stc15w201s_STC15W201S系列
- Android开发之移动互联网周刊第二期
- 举例Halcon,简述数字图像处理之Blob分析和纹理分析texture_laws
- 极品婆媳龙争虎斗---终极PK王者之战(10)
- php中可以给class添加click,jQuery addClass()方法添加class
- 由I2C data信号低电平不到0,再思考I2C及GPIO
- everything用于移动硬盘资料管理(二):离线搜索全部移动硬盘
- 发送ajax请求接收json数据,ajax接收到的json数据是空的
热门文章
- 利用python对微信云数据库_如何用python看看女神的微信百度云里面有啥?
- stata中计算公式命令_#stata中哪个命令和stats命令等价#stata中计算命令
- 01_ClickHouse概述,速度,分布式架构,列式存储,数据压缩,DBMS功能,有限支持DELETE、UPDATE功能,高吞吐写入功能,分布式计算,向量化执行引擎、架构、大数据处理架构
- 表的插入、更新、删除、合并操作_19_通过表关联删除记录
- 写好的python如何在其它电脑上运行_如何在另一个文件中运行一个python文件?
- ResNet 残差、退化等细节解读
- backlight misc驱动范例 及应用程序范例
- OpenCV图像的加载、显示
- asp.net mvc的初学
- Navicat 安装+连接