【问题标题】:Removing tensors for optimising a for loop in python删除张量以优化 python 中的 for 循环
【发布时间】:2020-06-09 09:01:07
【问题描述】:

我正在处理我正在尝试优化的大型代码。 您在下面看到的代码部分是一个以张量返回编码的 for 循环。如何在不使用张量的情况下将这些数字输出到常规列表中?

def _make_batches(self, lines):
        tokens = [self._tokenize(line) for line in lines]
        lengths = np.array([t.numel() for t in tokens])
        indices = np.argsort(-lengths, kind=self.sort_kind)  # pylint: disable=invalid-unary-operand-type

        def batch(tokens, lengths, indices):
            toks = tokens[0].new_full((len(tokens), tokens[0].shape[0]),
                                      self.pad_index)
            for i in range(len(tokens)):
                toks[i, -tokens[i].shape[0]:] = tokens[i]
            return Batch(srcs=None,
                         tokens=toks,
                         lengths=torch.LongTensor(lengths)), indices

        batch_tokens, batch_lengths, batch_indices = [], [], []
        ntokens = nsentences = 0
        for i in indices:
            if nsentences > 0 and ((self.max_tokens is not None
                                    and ntokens + lengths[i] > self.max_tokens)
                                   or (self.max_sentences is not None
                                       and nsentences == self.max_sentences)):
                yield batch(batch_tokens, batch_lengths, batch_indices)
                ntokens = nsentences = 0
                batch_tokens, batch_lengths, batch_indices = [], [], []
            batch_tokens.append(tokens[i])
            batch_lengths.append(lengths[i])
            batch_indices.append(i)
            ntokens += tokens[i].shape[0]
            nsentences += 1
        if nsentences > 0:
            yield batch(batch_tokens, batch_lengths, batch_indices)

我是这样称呼这个函数的:

if __name__ == '__main__':
    s = SentenceEncoder("data/model.pt")
    input = [args.string_enc]
    make_batches = s._make_batches
    print([batch[1] for batch, indexes in make_batches(input)])

输出是:

[tensor([[29733, 20720,     2]])]

想要的输出是:

[29733, 20720,     2]

【问题讨论】:

    标签: python for-loop pytorch tensor


    【解决方案1】:

    你是说这个吗?

    a=[torch.tensor([[29733, 20720,     2]])]
    b=a[0].squeeze(0).tolist()
    print(b)
    

    【讨论】:

    • 谢谢!不,我的意思是首先避免将数字放入张量,因为它的计算成本很高,因为我们有很多用于这个循环的数据。
    猜你喜欢
    • 2015-04-15
    • 2020-11-07
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2021-12-20
    • 2017-01-17
    • 2016-10-25
    相关资源
    最近更新 更多