numpy中的赋值与copy

numpy中的赋值与copy,第1张

上一个博客中提到pytorch中将tensor a赋值给tensor b,当改变b时a也会改变;或者是将tensor a赋值给ndarray b时,改变b,a也会改变。

同样的在numpy中,使用n2 = n1,当改变n2时,n1也会跟着改变,这时应使用n2=n1.copy();

对于tensor转ndarray,可以使用tensor.clone().numpy()或者tensor.numpy().copy();

对于ndarray转tensor,使用torch.form_numpy()时,修改tensor也会改变 ndarray,使用torch.tensor()则不会改变ndarray,示例如下:

import torch
import numpy as np

a = np.array([1, 2, 3])
b = torch.tensor(a)
b[0] = 3
print(f"ndarray a = {a}")
print(f"tensor b = {b}")


-----------------output--------------------

ndarray a = [1 2 3]
tensor b = tensor([3, 2, 3], dtype=torch.int32)

总结,对于要保留中间值时:

从tensor到tensor需要使用clone()

从tensor到ndarray需要使用copy()

从ndarray到ndarray需要使用copy()

从numpy到tensor使用torch.tensor()

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/867951.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-13
下一篇2022-05-13

发表评论

登录后才能评论

评论列表(0条)

    保存