当前位置:网站首页>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])
边栏推荐
- JVM上篇:内存与垃圾回收篇五--运行时数据区-虚拟机栈
- Event filter
- 内部类与静态内部类区别及举例
- pyside2____ 1. Installation and case listing
- SQL数据库→约束→设计→多表查询→事务
- The interface can automatically generate E and other asynchronous access or restart,
- [Niuke discussion area] Chapter 7: building safe and efficient enterprise services
- Use ngrok for intranet penetration
- 一、MySQL基础
- Bean的生命周期&&依赖注入*依赖自动装配
猜你喜欢

树莓派rtmp推流本地摄像头图像

Detailed description of polymorphism

34. 分析flexible.js

来自“飞人”乔丹的启示!奥尼尔开启的另一个“赛场”

Another skill is to earn 30000 yuan a month+

实用小工具: Kotlin 代码片段

How to test the payment process?

Introduction to dynamic memory functions (malloc free calloc realloc)

Introduction to Web Framework

Differences among left join, inner join and right join
随机推荐
2021 OWASP top 4: unsafe design
JVM上篇:内存与垃圾回收篇十二--StringTable
B1029 旧键盘
pyside2____ 1. Installation and case listing
Basic operation of vim
辗转相除法
mq设置过期时间、优先级、死信队列、延迟队列
mq常见问题
2021 OWASP top 5: security configuration error
Create datasource using Druid connection pool
How to store the startprocessinstancebykey method in acticiti in the variable table
[optical flow] - data format analysis, flowwarp visualization
B1025 反转链表*******
Bean's life cycle & dependency injection * dependency auto assembly
JVM上篇:内存与垃圾回收篇七--运行时数据区-堆
弹球小游戏
1、 MySQL Foundation
Detailed description of binary search tree
Event filter
LocalDateTime和ZonedDateTime