list to torch

Posted 雪靡

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了list to torch相关的知识,希望对你有一定的参考价值。

list to torch

方法一:

直接转换

torch.tensor(pick, dtype=torch.long)

方法二:

numpy转换

pick = numpy.array(pick)
torch.from_numpy(pick).type(torch.LongTensor)

两种方法测试下来,在list长度过大的情况下,间接转换效率高;但在list长度少的情况下,使用直接转换效率高。

测试代码:

import random
import sys
import time
from datetime import datetime

import numpy
import torch

# 有gpu的情况下使用gpu
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')



total_time = 0
"""
测试模式,0表示直接转换,1表示使用numpy转换
"""
test_mode = 1
loop_time = 100
list_size = 64000
if test_mode == 0:

    for _ in range(loop_time):
        pick = [random.randint(0, 10000) for _ in range(list_size)]
        begin_time = time.perf_counter()
        torch.tensor(pick, dtype=torch.long).to(device)
        end_time = time.perf_counter()
        total_time += end_time - begin_time
else:
    for _ in range(loop_time):
        pick = [random.randint(0, 10000) for _ in range(list_size)]
        pick = numpy.array(pick)
        begin_time = time.perf_counter()
        torch.from_numpy(pick).type(torch.LongTensor).to(device)
        end_time = time.perf_counter()
        total_time += end_time - begin_time
print("%.5fms" % (total_time * 1000.0))

以上是关于list to torch的主要内容,如果未能解决你的问题,请参考以下文章

list to torch

Python中 list, numpy.array, torch.Tensor 格式相互转化

torch.tensor() 和 torch.to_tensor() 的区别

关于convert caffe model to torch的一些问题

PyTorch:tensor.cuda() 和 tensor.to(torch.device("cuda:0")) 有啥区别?

报错记录torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 90.00 MiB (GPU 0; 7.93 GiB to