为什么Creating a tensor from a list of numpy.ndarrays is extremely slow

1.问题简介

今天运行一个DQN的代码时出现了如下图的warning:

UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  C:\cb\pytorch_1000000000000\work\torch\csrc\utils\tensor_new.cpp:210.)
  state = torch.tensor([state], dtype=torch.float).to(self.device)

为什么Creating a tensor from a list of numpy.ndarrays is extremely slow

警告说我们创建用一个包含numpy.ndarrays的列表创建tensor太慢了,建议我们转换为tensor之前考虑用numpy.array()将列表转换为一个单独的numpy.ndarry。

所以就想对tensor的转换这部分学习一下。

找到一篇文章:https://zhuanlan.zhihu.com/p/429901066

这篇文章介绍了一下这个问题,但是自己对于代码运行过程中数据类型的变换不是很懂,想弄透彻一点,所以记录一下代码的调试过程中变量类型的变换。

2.实验与结论

先说结论

如果list中没有ndarrays,则选择list->tensor更快。

如果list中有ndarrays,则选择list->ndarrays->tensor更快;

注:为了减小偶然因素的影响,所以将转换的部分运行10遍

2.1 list->tensor(注:list中的元素不含numpy.ndarrays)
import numpy as np
import torch
import time

l = [i for i in range(50000000)]
stime = time.time()
for _ in range(10):
    a = torch.tensor(l)
etime = time.time()
print(f'用时: {etime-stime}s')
用时: 25.838355541229248s

调试过程中的变量记录:

为什么Creating a tensor from a list of numpy.ndarrays is extremely slow
2.2 list->numpy.ndarrays->tensor(注:list中的元素不含numpy.ndarrays)
import numpy as np
import torch
import time

l = [i for i in range(50000000)]
stime = time.time()
for _ in range(10):
    a = torch.tensor(np.array(l))
etime = time.time()
print(f'用时: {etime-stime}s')
用时: 31.836950540542603s

调试过程中的变量记录:

import numpy as np
import torch

l = [1, 2, 3, 4, 5]
a = np.array(l)
b = torch.tensor(a)

为什么Creating a tensor from a list of numpy.ndarrays is extremely slow

结论一:可以看到如果list中的元素不含有numpy.ndarrays时直接将list->tensor更快

2.3 list->tensor(注:list中的元素含numpy.ndarrays)
import numpy as np
import torch
import time

l = [np.ones(1) for i in range(5000000)]
stime = time.time()
torch.tensor(l)
etime = time.time()
print(f'用时: {etime-stime}s')
用时: 3.9938528537750244s

为什么Creating a tensor from a list of numpy.ndarrays is extremely slow

调试过程中的变量记录:

为什么Creating a tensor from a list of numpy.ndarrays is extremely slow
2.4 list->numpy.ndarraays->tensor(注:list中的元素含numpy.ndarrays)
l = [np.ones(1) for i in range(5000000)]
stime = time.time()
a = np.array(l)
b = torch.tensor(a)
etime = time.time()
print(f'用时: {etime-stime}s')

为什么Creating a tensor from a list of numpy.ndarrays is extremely slow
用时: 1.8933970928192139s

调试过程中的变量记录:

为什么Creating a tensor from a list of numpy.ndarrays is extremely slow

结论二:如果list中有ndarrays,则选择list->ndarrays->tensor更快

Original: https://blog.csdn.net/qq_47997583/article/details/124455544
Author: 小帅吖
Title: 为什么Creating a tensor from a list of numpy.ndarrays is extremely slow

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/757294/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球