python - PyTorch 复制张量的首选方式

标签 python pytorch copy tensor

似乎有几种方法可以在 PyTorch 中创建张量的副本,包括

y = tensor.new_tensor(x) #a

y = x.clone().detach() #b

y = torch.empty_like(x).copy_(x) #c

y = torch.tensor(x) #d
根据执行 a 时收到的 UserWarning,

b 明显优于 add。为什么它是首选?表现?我认为它的可读性较差。

有什么理由支持/反对使用c吗?

最佳答案

TL;DR

使用.clone().detach()(或者最好使用.detach().clone())

If you first detach the tensor and then clone it, the computation path is not copied, the other way around it is copied and then abandoned. Thus, .detach().clone() is very slightly more efficient.-- pytorch forums

因为它的作用稍微快一些并且明确。

<小时/>

使用perflot ,我绘制了复制 pytorch 张量的各种方法的时间。

y = tensor.new_tensor(x) # method a

y = x.clone().detach() # method b

y = torch.empty_like(x).copy_(x) # method c

y = torch.tensor(x) # method d

y = x.detach().clone() # method e

x轴是创建张量的维度,y轴显示时间。该图是线性比例的。您可以清楚地看到,与其他三种方法相比,tensor()new_tensor() 需要更多时间。

enter image description here

注意:在多次运行中,我注意到在 b、c、e 中,任何方法的时间都可以是最低的。 a和d也是同样的情况。但是,方法 b、c、e 的计时始终低于 a 和 d。

import torch
import perfplot

perfplot.show(
    setup=lambda n: torch.randn(n),
    kernels=[
        lambda a: a.new_tensor(a),
        lambda a: a.clone().detach(),
        lambda a: torch.empty_like(a).copy_(a),
        lambda a: torch.tensor(a),
        lambda a: a.detach().clone(),
    ],
    labels=["new_tensor()", "clone().detach()", "empty_like().copy()", "tensor()", "detach().clone()"],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
    logx=False,
    logy=False,
    title='Timing comparison for copying a pytorch tensor',
)

关于python - PyTorch 复制张量的首选方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55266154/

相关文章:

python - torch.argmax 如何为 4 维工作

Pytorch-为什么 “accumulating”是.gradient的默认模式?

windows - 备份配置文件

javascript - 将具有特定 id 的 div 复制到具有相关 id 的目标

linux - 在 Linux 上快速连接多个文件

python , Pandas 。从累积值转换为增量

python - 通过交换特定元素生成列表的排列

python - 在 Miniconda 上安装 Jupyter Notebook

python - json.loads() 失败

python - PyTorch:传递 numpy 数组以进行权重初始化