Deeplizard《Pytorch神经网络高效入门教程》第九集笔记

import torch
import numpy as np
data = np.array([1,2,3])
o1 = torch.Tensor(data)          #类构造函数,数据默认为float32,不能自己设置数据类型
o2 = torch.tensor(data)          #工厂函数,根据输入的数据类型自动匹配
o3 = torch.as_tensor(data)       #工厂函数
o4 = torch.from_numpy(data)      #工厂函数
print(o1)
print(o2)
print(o3)
print(o4)
/*
输出结果:
tensor([1., 2., 3.])
tensor([1, 2, 3], dtype=torch.int32)
tensor([1, 2, 3], dtype=torch.int32)
tensor([1, 2, 3], dtype=torch.int32)
*/

Share Data : torch.as_tensor(), torch.from_numpy() 
//数据在同一个内存空间, 如果我修改data[0] = 0, o3、o4也要改变
//相当于o3、o4、data变量存的是一个地址,它们都指向相同的内存空间
Copy Data : torch.Tensor(), torch.tensor() 
//在内存中重新开辟一片新的空间,将data里的值传给Tensor,修改data[0] = 0, o1、o2不改变

测试代码如下:

import numpy as np
import torch
data = np.array([1,2,3])
o1 = torch.Tensor(data)          
o2 = torch.tensor(data)         
o3 = torch.as_tensor(data)       
o4 = torch.from_numpy(data)
data[0] = 99
print(data)
print(o3)
print(o4)
o3[1] = 100
print(data)
print(o3)
print(o4)
/*
输出如下:
[99  2  3]
tensor([99,  2,  3])
tensor([99,  2,  3])
[ 99 100   3]
tensor([ 99, 100,   3])
tensor([ 99, 100,   3])
*/

Best Options For Creating Tensors In PyTorch
torch.tensor()   //可以根据输入的数据类型创建相应类型的Tensor变量,还可以自己设置数据类型
torch.as_tensor() //它可以接收python中各种数组,但torch.from_numpy()只能接收numpy数组
Tips:
1.Since numpy.ndarray objects are allocated on the CPU, the as_tensor() function must copy the data from the CPU to the GPU when a GPU is being used.
2.The memory sharing of as_tensor() doesn't work with built-in Python data structures like lists.
3.The as_tensor() call requires developer knowledge of the sharing feature. This is necessary so we don't inadvertently make an unwanted change in the underlying data without realizing the change impacts multiple objects.
4.The as_tensor() performance improvement will be greater if there are a lot of back and forth operations between numpy.ndarray objects and tensor objects. However, if there is just a single load operation, there shouldn't be much impact from a performance perspective.
 

猜你喜欢

转载自blog.csdn.net/weixin_43227262/article/details/120412940
今日推荐