参考链接:list转tensor的不同方式对比
报错:
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.
结论:
如果 list 中有 ndarrays,则选择 list->ndarrays->tensor 更快;
如果 list 中没有 ndarrays,则选择 list->tensor 更快。
因此修改为:
# 修改前
x_train = torch.Tensor([binary_encode(number) for number in range(101, 1024)]) # 把数转成10位二进制
# 修改后
x_train = torch.Tensor(np.array([binary_encode(number) for number in range(101, 1024)]))
实验对比可以看list转tensor的不同方式对比 。
总结
(1) 对于不含 numpy.ndarrays 的 list而言,list->tensor 明显快于 list->numpy.ndarrays->tensor (1.7s<2.5s);
(2) 对于含有 numpy.ndarrays 的 list而言,list->numpy.ndarrays->tensor 明显快于 list->tensor (18.8s<41.2s)。
若想解决文章开头提示的 userWarning,只需要将含有 ndarrays 的 list 进行 torch.tensor(np.array(list)) 即可。
本文探讨了将包含numpy数组的list转换为PyTorch Tensor的两种方法,指出当list中包含ndarrays时,先转换为numpy数组再转成Tensor速度更快;而若list中无ndarrays,直接转成Tensor更优。实验数据显示,对于不含ndarrays的list,list->tensor比list->numpy->tensor快;对于含ndarrays的list,list->numpy->tensor则显著优于list->tensor。解决UserWarning的最佳实践是使用torch.tensor(np.array(list))。
1万+

被折叠的 条评论
为什么被折叠?



