【问题标题】:Copy or Create ZEROS-Tensor复制或创建零张量
【发布时间】:2021-08-11 13:52:13
【问题描述】:

什么是使用torch-tensor的好方法:复制或创建新的张量?速度呢? 目标是在每次调用方法时获得一个具有恒定大小的新零张量

class CopyOrCreateZeros:
    def __init__(self):
        self.fx = torch.zeros((800, 600))
        pass

    def method(self, x):
        """ this method will be used many ofter e.g. in loop """
        # do something

        new_x1 = torch.copy(self.fx)
        new_x2 = torch.clone(self.fx)
        new_x3 = x.new_zeros()
        new_x4 = torch.zeros_like(x)
        new_x5 = torch.zeros()

【问题讨论】:

    标签: pytorch copy new-operator tensor


    【解决方案1】:

    似乎克隆fx 张量是最慢的解决方案,而其他三个(即Tensor.new_zerostorch.zeros_liketorch.zeros)的时间相当:

    • torch.clone:

      %timeit fx.clone()
      1000 loops, best of 5: 277 µs per loop
      
    • torch.Tensor.new_zeros:

      %timeit fx.new_zeros(fx.shape)
      1000 loops, best of 5: 257 µs per loop
      
    • torch.zeros_like:

      %timeit torch.zeros_like(fx)
      1000 loops, best of 5: 258 µs per loop
      
    • torch.zeros:

      %timeit torch.zeros(fx.shape)
      1000 loops, best of 5: 256 µs per loop
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-28
      • 2015-02-18
      • 2019-01-03
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多