当前位置:网站首页>pytorch 数据类型 和 numpy 数据 相互转化
pytorch 数据类型 和 numpy 数据 相互转化
2022-07-27 05:01:00 【CharlesLC的博客】
tensor to numpy
tensor数据在cpu上:
如果tensor数据在cpu上,直接使用.numpy()就可以转化。
例子:
注意:torch 和 numpy 转化后 指向地址相同
如果修改原始数据,那么转换后的数据也会修改,例子:

tensor数据在gpu上:
如果tensor数据在gpu上,那么需要将tensor数据先转移到cpu上面,然后在进行转化。
例子
a = torch.randn(2,3,4)
a = a.cuda()
print('type of a ', type(a))
print('device of a', a.device)
b = a.numpy() # 会出错
报错信息:TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
应该将a的数据先转化到 cpu 上面,在进行转化,例子:
a = torch.randn(2,3,4)
a = a.cuda()
print('type of a ', type(a))
print('device of a', a.device)
b = a.cpu().numpy()
print('type of b', type(b))
numpy to tensor
使用torch中的from_numpy() 函数将numpy数据 转换 为 torch上数据,例子:
# numpy to tensor
data_np = np.array([1,2,3,4,5])
print('orgin data_np', data_np)
data_tr = torch.from_numpy(data_np)
print('orgin data_tr',data_tr)
data_np[3] = 11
print('modify data_np', data_np)
print('modify data_tr', data_tr)
numpy数据和torch数据指向同一个地址,修改numpy数据会改变torch上数据,结果如下:
orgin data_np [1 2 3 4 5]
orgin data_tr tensor([1, 2, 3, 4, 5])
modify data_np [ 1 2 3 11 5]
modify data_tr tensor([ 1, 2, 3, 11, 5])
边栏推荐
- Event filter
- 35.滚动 scroll
- 笔记系列k8s编排MySQL容器-有状态的容器创建过程
- B1030 完美数列
- B1026 程序运行时间
- Alphabetic order problem
- JVM Part 1: memory and garbage collection part 14 -- garbage collector
- JVM Part 1: memory and garbage collection -- runtime data area 4 - program counter
- 精选用户故事|洞态在聚水潭的误报率几乎为0,如何做到?
- Li Kou achieved the second largest result
猜你喜欢

Another skill is to earn 30000 yuan a month+

Could not autowire. No beans of ‘userMapper‘ type found.

JVM上篇:内存与垃圾回收篇六--运行时数据区-本地方法&本地方法栈

Tcp server是如何一个端口处理多个客户端连接的(一对一还是一对多)

String class

Critical path principle

探寻通用奥特能平台安全、智能、性能的奥秘!

JVM Part 1: memory and garbage collection -- runtime data area 4 - program counter
![[CSAPP] Application of bit vectors | encoding and byte ordering](/img/96/344936abad90ea156533ff49e74f59.gif)
[CSAPP] Application of bit vectors | encoding and byte ordering

pyside2____1.安装和案列
随机推荐
Machine learning overview
SSM framework integration
mq设置过期时间、优先级、死信队列、延迟队列
Flexible array and common problems
Niuke sword refers to the path in the offer--jz12 matrix
Select user stories | the false positive rate of hole state in jushuitan is almost 0. How to do this?
ERP system brand
ERROR! MySQL is not running, but PID file exists
34. 分析flexible.js
How to sinicize the JMeter interface?
ssm框架整合
JVM上篇:内存与垃圾回收篇六--运行时数据区-本地方法&本地方法栈
JVM上篇:内存与垃圾回收篇二--类加载子系统
Install pyGame
如何快速有效解决数据库连接失败问题
Detailed description of polymorphism
弹球小游戏
1、 MySQL Foundation
JVM Part 1: memory and garbage collection part 3 - runtime data area - overview and threads
JVM上篇:内存与垃圾回收篇十四--垃圾回收器