转载自:(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)是做数组的深拷贝

更多相关文章

  1. python 中 字符串转换为数组,字典或表达式
  2. 具有1位条目的numpy布尔数组
  3. 在Python中搜索一个并行数组
  4. 将2d数组数据视为定义形状的像素——是否可能创建内部和表面?
  5. 从字典中创建NumPy数组的最佳方法是什么?
  6. c++与python关于二维数组的数据传递问题,刚注册没有分,以后一定补
  7. 对numpy数组的每n个元素求平均值
  8. [置顶] Python + C/C++ 嵌入式编程(1):多维数组Numpy.Array(
  9. Python根据第一项从2d数组中删除元素

随机推荐

  1. 一个不容错过的Spring Cloud实战项目!
  2. Spring Data Redis 最佳实践!
  3. 使用Redis+AOP优化权限管理功能,这波操作
  4. 能不能好好写简历?
  5. Github标星25K+Star,SpringBoot实战电商项
  6. 在Docker容器中部署整套基于Spring Cloud
  7. Docker环境下秒建Redis集群,连SpringBoot
  8. 什么是消息队列?
  9. 函数
  10. Nginx的这些妙用,你肯定有不知道的!