当前位置:网站首页>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 Part 1: memory and garbage collection part 14 -- garbage collector
- Find the number of combinations (the strongest optimization)
- JVM Part 1: memory and garbage collection part 3 - runtime data area - overview and threads
- Event filter
- JVM Part 1: memory and garbage collection part 6 -- runtime data area local method & local method stack
- SQL数据库→约束→设计→多表查询→事务
- Integrate SSM
- Typescript details
- Select user stories | the false positive rate of hole state in jushuitan is almost 0. How to do this?
- B1030 perfect sequence
猜你喜欢

String class

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

集合框架的使用

Detailed description of polymorphism

Li Kou achieved the second largest result

辗转相除法

OFDM 16 lecture 2-ofdm and the DFT

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

JVM Part 1: memory and garbage collection part 12 -- stringtable

How to sinicize the JMeter interface?
随机推荐
集合框架的使用
枚举类实现单例模式
B1026 program running time
简化JDBC的MyBits框架
Test basis 5
How does the TCP server handle multiple client connections on one port (one-to-one or one to many)
B1022 a+b in d-ary
Idea remote debugging
Introduction to dynamic memory functions (malloc free calloc realloc)
ERROR! MySQL is not running, but PID file exists
JDBC API 详解
JVM上篇:内存与垃圾回收篇九--运行时数据区-对象的实例化,内存布局与访问定位
Event Summary - common summary
JVM上篇:内存与垃圾回收篇七--运行时数据区-堆
JVM上篇:内存与垃圾回收篇二--类加载子系统
[CSAPP] Application of bit vectors | encoding and byte ordering
《Robust and Precise Vehicle Localization based on Multi-sensor Fusionin Diverse City Scenes》翻译
2021 OWASP top 6-10 collection
Derivation and explanation of PBR physical illumination calculation formula
Static and final keyword learning demo exercise