pytorch中tensor数据和numpy数据转换中注意的一个问题
16lz
2021-01-22
转载自:(pytorch中tensor数据和numpy数据转换中注意的一个问题)[https://blog.csdn.net/nihate/article/details/82791277]
在pytorch中,把numpy.array数据转换到张量tensor数据的常用函数是torch.from_numpy(array)或者torch.Tensor(array),第一种函数更常用。下面通过代码看一下区别:
import numpy as np
import torch
a=np.arange(6,dtype=int).reshape(2,3)
b=torch.from_numpy(a)
c=torch.Tensor(a)
a[0][0]=10
print(a,'\n',b,'\n',c)
[[10 1 2]
[ 3 4 5]]
tensor([[10, 1, 2],
[ 3, 4, 5]], dtype=torch.int32)
tensor([[0., 1., 2.],
[3., 4., 5.]])
c[0][0]=10
print(a,'\n',b,'\n',c)
[[10 1 2]
[ 3 4 5]]
tensor([[10, 1, 2],
[ 3, 4, 5]], dtype=torch.int32)
tensor([[10., 1., 2.],
[ 3., 4., 5.]])
print(b.type())
torch.IntTensor
print(c.type())
torch.FloatTensor
可以看出修改数组a的元素值,张量b的元素值也改变了,但是张量c却不变。修改张量c的元素值,数组a和张量b的元素值都不变。这说明torch.from_numpy(array)是做数组的浅拷贝,torch.Tensor(array)是做数组的深拷贝。
更多相关文章
- python 中 字符串转换为数组,字典或表达式
- 具有1位条目的numpy布尔数组
- 在Python中搜索一个并行数组
- 将2d数组数据视为定义形状的像素——是否可能创建内部和表面?
- 从字典中创建NumPy数组的最佳方法是什么?
- c++与python关于二维数组的数据传递问题,刚注册没有分,以后一定补
- 对numpy数组的每n个元素求平均值
- [置顶] Python + C/C++ 嵌入式编程(1):多维数组Numpy.Array(
- Python根据第一项从2d数组中删除元素