当前位置: 首页> 文旅> 旅游 > MindSpore中NumPy变量转换为Tensor张量使用的Tensor.from_numpy()函数到底是深拷贝还是浅拷贝

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

时间:2025/7/11 14:31:45来源:https://blog.csdn.net/qq_75125305/article/details/139998145 浏览次数:0次

在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

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: