亲宝软件园·资讯

展开

PyTorch中torch.tensor()和torch.to_tensor()的区别

Enzo 想砸电脑 人气:0

前言

在跑模型的时候,遇到如下报错

UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).

网上查了一下,发现将 torch.tensor() 改写成 torch.as_tensor() 就可以避免报错了。

# 如下写法报错
 feature = torch.tensor(image, dtype=torch.float32)
 
# 改为
feature = torch.as_tensor(image, dtype=torch.float32)

然后就又仔细研究了下 torch.as_tensor()torch.tensor() 的区别,在此记录。

1、torch.as_tensor()

new_data = torch.as_tensor(data, dtype=None,device=None)->Tensor

作用:生成一个新的 tensor, 这个新生成的tensor 会根据原数据的实际情况,来决定是进行浅拷贝,还是深拷贝。当然,会优先浅拷贝,浅拷贝会共享内存,并共享 autograd 历史记录。

情况一:数据类型相同 且 device相同,会进行浅拷贝,共享内存

import numpy
import torch

a = numpy.array([1, 2, 3])
t = torch.as_tensor(a)
t[0] = -1

print(a)   # [-1  2  3]
print(a.dtype)   # int64
print(t)   # tensor([-1,  2,  3])
print(t.dtype)   # torch.int64
import numpy
import torch

a = torch.tensor([1, 2, 3], device=torch.device('cuda'))
t = torch.as_tensor(a)
t[0] = -1

print(a)   # tensor([-1,  2,  3], device='cuda:0')
print(t)   # tensor([-1,  2,  3], device='cuda:0')

情况二: 数据类型相同,但是device不同,深拷贝,不再共享内存

import numpy
import torch

import numpy
a = numpy.array([1, 2, 3])
t = torch.as_tensor(a, device=torch.device('cuda'))
t[0] = -1

print(a)   # [1 2 3]
print(a.dtype)   # int64
print(t)   # tensor([-1,  2,  3], device='cuda:0')
print(t.dtype)   # torch.int64

情况三:device相同,但数据类型不同,深拷贝,不再共享内存

import numpy
import torch

a = numpy.array([1, 2, 3])
t = torch.as_tensor(a, dtype=torch.float32)
t[0] = -1

print(a)   # [1 2 3]
print(a.dtype)   # int64
print(t)   # tensor([-1.,  2.,  3.])
print(t.dtype)   # torch.float32

2、torch.tensor()

torch.tensor() 是深拷贝方式。

torch.tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False)

深拷贝:会拷贝 数据类型 和 device,不会记录 autograd 历史 (also known as a “leaf tensor” 叶子tensor)

重点是:

# 原数据类型是:tensor 会发出警告
import numpy
import torch

a = torch.tensor([1, 2, 3], device=torch.device('cuda'))
t = torch.tensor(a)
t[0] = -1

print(a)
print(t)

# 输出:
# tensor([1, 2, 3], device='cuda:0')
# tensor([-1,  2,  3], device='cuda:0')
# /opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:5: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor).
# 原数据类型是:list, tuple, NumPy ndarray, scalar, and other types, 没警告
import torch
import numpy

a =  numpy.array([1, 2, 3])
t = torch.tensor(a) 

b = [1,2,3]
t= torch.tensor(b)

c = (1,2,3)
t= torch.tensor(c)

结论就是:以后尽量用 torch.as_tensor()

总结

加载全部内容

相关教程
猜你喜欢
用户评论