기계는 거짓말하지 않는다

Pytorch 경고 Creating a tensor from a list of numpy.ndarrays is extremely slow 본문

AI

Pytorch 경고 Creating a tensor from a list of numpy.ndarrays is extremely slow

KillinTime 2024. 7. 18. 19:18
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.

Pytorch에서 List에 다수의 numpy.ndarray가 있을 경우 torch.tensor로 변환하는 경우 발생한다.

이렇게 하면 성능이 저하될 수 있고, List를 단일 numpy.ndarray로 변환 후 tensor로 다시 변환하여야 한다.

import numpy as np
import torch

def convert_to_tensor(list_of_arrays):
    # 리스트를 numpy.ndarray로 변환
    combined_array = np.array(list_of_arrays)
    
    # numpy.ndarray를 torch.Tensor로 변환
    tensor = torch.tensor(combined_array)
    
    return tensor

# numpy.ndarray 리스트
list_of_arrays = [np.random.rand(3, 3) for _ in range(10)]

# 변환
tensor = convert_to_tensor(list_of_arrays)

print(tensor)

 

Comments