Python, NumPy, PyTorch를 사용하여 문자열 목록을 PyTorch 텐서로 변환하는 방법
Python, NumPy, PyTorch를 사용하여 문자열 목록을 PyTorch 텐서로 변환하는 방법
개요
방법
torch.from_numpy()
장점:
- 간단하고 직관적
- NumPy 배열을 텐서로 변환하는 데 유용
단점:
- 문자열을 직접 변환하지 못함
- 사전에 문자열을 NumPy 배열로 변환해야 함
예시:
import numpy as np
import torch
# 문자열 목록
strings = ["hello", "world"]
# NumPy 배열로 변환
np_array = np.array(strings)
# 텐서로 변환
tensor = torch.from_numpy(np_array)
print(tensor)
# output: tensor(['hello', 'world'], dtype=torch.str)
torch.Tensor.new_empty() 및 torch.nn.functional.pad()
- 문자열 길이가 다르더라도 동작 가능
- 코드가 더 복잡
- 패딩 값을 지정해야 함
import torch
from torch.nn.functional import pad
# 문자열 목록
strings = ["hello", "world", "how are you"]
# 최대 길이 계산
max_len = max(len(s) for s in strings)
# 텐서 생성
tensor = torch.Tensor.new_empty((len(strings), max_len), dtype=torch.str)
# 패딩
for i, string in enumerate(strings):
tensor[i, :len(string)] = torch.tensor(string)
tensor[i, len(string):] = torch.tensor(" ")
print(tensor)
# output: tensor([['hello', ' '],
# ['world', ' '],
# ['how are you', '']], dtype=torch.str)
torch.nn.utils.rnn.pad_sequence()
- RNN 모델에서 사용하기에 적합
- 패딩 값을 자동으로 설정
- 일반적인 텐서 변환에는 적합하지 않음
import torch
from torch.nn.utils.rnn import pad_sequence
# 문자열 목록
strings = ["hello", "world", "how are you"]
# 텐서 생성
tensor = pad_sequence([torch.tensor(s) for s in strings], batch_first=True)
print(tensor)
# output: tensor([[ 4, 101, 108, 108, 111, 0, 0, 0, 0, 0],
# [ 119, 111, 114, 108, 100, 0, 0, 0, 0, 0],
# [ 8, 119, 111, 114, 32, 97, 114, 101, 32, 121, 111, 117]], dtype=torch.int64)
선택 가이드
- 문자열 길이가 동일하고 간단한 변환을 원하는 경우:
torch.from_numpy()
- 문자열 길이가 다르고 RNN 모델에 사용할 경우:
torch.nn.utils.rnn.pad_sequence()
- 문자열 길이가 다르고 일반적인 텐서 변환을 원하는 경우:
torch.Tensor.new_empty()
및torch.nn.functional.pad()
예제 코드
예시 1: torch.from_numpy()
import numpy as np
import torch
# 문자열 목록
strings = ["hello", "world"]
# NumPy 배열로 변환
np_array = np.array(strings)
# 텐서로 변환
tensor = torch.from_numpy(np_array)
print(tensor)
# output: tensor(['hello', 'world'], dtype=torch.str)
예시 2: torch.Tensor.new_empty()
및 torch.nn.functional.pad()
import torch
from torch.nn.functional import pad
# 문자열 목록
strings = ["hello", "world", "how are you"]
# 최대 길이 계산
max_len = max(len(s) for s in strings)
# 텐서 생성
tensor = torch.Tensor.new_empty((len(strings), max_len), dtype=torch.str)
# 패딩
for i, string in enumerate(strings):
tensor[i, :len(string)] = torch.tensor(string)
tensor[i, len(string):] = torch.tensor(" ")
print(tensor)
# output: tensor([['hello', ' '],
# ['world', ' '],
# ['how are you', '']], dtype=torch.str)
예시 3: torch.nn.utils.rnn.pad_sequence()
import torch
from torch.nn.utils.rnn import pad_sequence
# 문자열 목록
strings = ["hello", "world", "how are you"]
# 텐서 생성
tensor = pad_sequence([torch.tensor(s) for s in strings], batch_first=True)
print(tensor)
# output: tensor([[ 4, 101, 108, 108, 111, 0, 0, 0, 0, 0],
# [ 119, 111, 114, 108, 100, 0, 0, 0, 0, 0],
# [ 8, 119, 111, 114, 32, 97, 114, 101, 32, 121, 111, 117]], dtype=torch.int64)
문자열 목록을 PyTorch 텐서로 변환하는 대체 방법
for 루프 및 torch.cat()
import torch
# 문자열 목록
strings = ["hello", "world"]
# 텐서 리스트 생성
tensors = []
for string in strings:
tensors.append(torch.tensor(string))
# 텐서로 합치기
tensor = torch.cat(tensors)
print(tensor)
# output: tensor(['hello', 'world'], dtype=torch.str)
map() 및 torch.tensor()
import torch
# 문자열 목록
strings = ["hello", "world"]
# 텐서 생성
tensor = torch.tensor(list(map(lambda s: s, strings)))
print(tensor)
# output: tensor(['hello', 'world'], dtype=torch.str)
torch.nn.Embedding
import torch
from torch.nn import Embedding
# 문자열 목록
strings = ["hello", "world"]
# 임베딩 레이어 생성
embedding = Embedding(num_embeddings=len(strings), embedding_dim=10)
# 텐서 생성
tensor = embedding(torch.tensor(list(range(len(strings)))))
print(tensor)
# output: tensor([[ 0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000],
# [ 0.0000, 0.0000, 0.0000, ..., 0.0000, 0.0000, 0.0000]], dtype=torch.float32)
선택 가이드
- 텍스트 임베딩을 사용하고 싶은 경우:
torch.nn.Embedding
python numpy pytorch