栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么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:cbpytorch_1000000000000worktorchcsrcutilstensor_new.cpp:210.)
  state = torch.tensor([state], dtype=torch.float).to(self.device)

警告说我们创建用一个包含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

调试过程中的变量记录:

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)

结论一:可以看到如果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

调试过程中的变量记录:

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')

用时: 1.8933970928192139s

调试过程中的变量记录:

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/844666.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号