MindSpore中NumPy变量转换为Tensor张量使用的Tensor.from_numpy()函数到底是深拷贝还是浅拷贝

在NumPy转换为Tensor使用的Tensor.from_numpy()函数到底是深拷贝还是浅拷贝

使用Tensor()将NumPy变量转换为Tensor变量。

类似数组转换张量的方法

n = np.ones(5)
t = Tensor.from_numpy(n)
print(f"t: {t}", type(t))
np.add(n, 1, out=n)
print(f"n: {n}", type(n))
print(f"t: {t}", type(t))

在这里插入图片描述

至于这里对numpy类型的n加了1后,t为什么也加了一 emmm在英文释义里有那么一句话

Docstring:

Convert numpy array to Tensor.

If the data is not C contiguous, the data will be copied to C contiguous to construct the tensor.

Otherwise, The tensor will be constructed using this numpy array without copy.

意思是说如果numpy数组连续的话将使用原numpy数组来构造张量,也就是浅拷贝,所以导致上面的t中的元素也加了1,因为这个t只是指向了和原来n一样地址的指针,并没有为了创建这个张量而开辟一块内存空间

所以这里的from_numpy是一个浅拷贝吗????我们可以创建一个不连续的numpy数组来测试一下

# 创建一个不连续的 NumPy 数组 'F' 表示按列优先 将 C 转换为不连续的(一维的应该不行)
n_new = np.array([[1, 2], [3, 4]], order='F')
t_new = Tensor.from_numpy(n_new)

print(f"t_new: {t_new}", type(t_new))
print(f"n_new: {n_new}", type(n_new))

np.add(n_new, 1, out=n_new)

print(f"n_new: {n_new}", type(n_new))
print(f"t_new: {t_new}", type(t_new))

在这里插入图片描述

这个时候我们可以发现,此时的from_numpy不是一个浅拷贝,而是一个深拷贝

刚刚好被群里扫盲的大佬推了一个python中探讨深浅拷贝的链接 我那么白吗

https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AbsoluteClownMaster

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值