当前位置:网站首页>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])
边栏推荐
- String class
- Introduction to Web Framework
- 弹球小游戏
- 抽卡程序模拟
- Could not autowire. No beans of ‘userMapper‘ type found.
- Bean's life cycle & dependency injection * dependency auto assembly
- Detailed explanation of pointer constant and constant pointer
- LeetCode刷题之322 Coin Change
- JVM Part 1: memory and garbage collection part 11 -- execution engine
- Test basis 5
猜你喜欢

Sunyanfang, co-founder of WeiMiao: take compliance as the first essence and become the "regular army" of financial and business education

Install pyGame

JVM Part 1: memory and garbage collection part 9 - runtime data area - object instantiation, memory layout and access location

Li Kou achieved the second largest result

How to store the startprocessinstancebykey method in acticiti in the variable table

2021 OWASP top 6-10 collection

B1021 个位数统计

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

Another skill is to earn 30000 yuan a month+

Svn usage details
随机推荐
Set static IP for raspberry pie
ssm框架整合
LeetCode之6 ZigZag Conversion
[acwing] solution to the 61st weekly match
辗转相除法
JVM Part 1: memory and garbage collection part 10 - runtime data area - direct memory
34. Analyze flexible.js
34. 分析flexible.js
B1029 旧键盘
ERROR! MySQL is not running, but PID file exists
B1027 打印沙漏
整合SSM
35. Scroll
树莓派rtmp推流本地摄像头图像
Demo of throttling function -- regular expression matching
JVM上篇:内存与垃圾回收篇十四--垃圾回收器
精选用户故事|洞态在聚水潭的误报率几乎为0,如何做到?
传智教育|软件测试工程师未来的发展方向有哪些?
Install pyGame
How to test the payment process?