欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

torch学习——持续补充

程序员文章站 2022-03-03 07:56:29
...

torch和numpy的转换

重点1

torch和numpy互相转换的时候,内存是共享的!因此改一个,必将修改另一个

import numpy as np
a = np.random.rand(4,3)
print(a)
array([[0.53097097, 0.39967826, 0.2925655 ],
       [0.41214625, 0.85092555, 0.88813825],
       [0.74869623, 0.20646449, 0.83864256],
       [0.80688304, 0.89462968, 0.12394582]])
b = torch.from_numpy(a)
print(b)
0.5310  0.3997  0.2926
 0.4121  0.8509  0.8881
 0.7487  0.2065  0.8386
 0.8069  0.8946  0.1239
[torch.DoubleTensor of size 4x3]
b.mul_(2)
print(b)
print(a)
1.0619  0.7994  0.5851
 0.8243  1.7019  1.7763
 1.4974  0.4129  1.6773
 1.6138  1.7893  0.2479
[torch.DoubleTensor of size 4x3]
array([[1.06194194, 0.79935653, 0.58513101],
       [0.8242925 , 1.7018511 , 1.7762765 ],
       [1.49739246, 0.41292898, 1.67728512],
       [1.61376609, 1.78925936, 0.24789164]])

重点2

当一个变量(numpy和torch都是)被重新赋值的时候,其内存会被重新分配!

a=np.random.rand(3,2)
print(id(a))
139997338436912
a=a*2
print(id(a))
139997338438112