Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

TensorFlow와 Python으로 길이가 같은 여러 문자열을 인코딩하는 방법

길이가 같은 여러 문자열을 인코딩할 때는 tf.Tensor를 입력값으로 사용하면 됩니다. 하지만 길이가 서로 다른 여러 문자열을 인코딩해야 한다면 tf.RaggedTensor를 입력으로 사용해야 합니다. 또한, 패딩(padded) 또는 희소(sparse) 형식으로 저장된 여러 문자열을 담고 있는 텐서가 있다면, unicode_encode 메서드를 호출하기 전에 반드시 이를 tf.RaggedTensor로 변환해 주어야 합니다.

유니코드 문자열의 표현과 조작

이 글에서는 Python으로 유니코드 문자열을 표현하고, 유니코드 등가 연산(Unicode equivalents)을 활용해 이를 조작하는 방법을 살펴봅니다. 먼저 표준 문자열 연산에 대응하는 유니코드 연산을 사용하여, 문자 체계(script) 감지를 기준으로 유니코드 문자열을 토큰 단위로 분리합니다.

실행 환경: Google Colaboratory

아래 코드는 Google Colaboratory에서 실행했습니다. Google Colab은 브라우저만으로 Python 코드를 실행할 수 있게 지원하며, 별도의 설정이 필요 없고 GPU(그래픽 처리 장치)도 무료로 사용할 수 있습니다. Colaboratory는 Jupyter Notebook을 기반으로 구축되었습니다.

print("When encoding multiple strings of same lengths, tf.Tensor is used as input")
tf.strings.unicode_encode([[99, 97, 116], [100, 111, 103], [99, 111, 119]], output_encoding='UTF-8')
print("When encoding multiple strings with varying length, a tf.RaggedTensor should be used as input:")
tf.strings.unicode_encode(batch_chars_ragged, output_encoding='UTF-8')
print("If there is a tensor with multiple strings in padded/sparse format, convert it to a tf.RaggedTensor before calling unicode_encode")
tf.strings.unicode_encode(
    tf.RaggedTensor.from_sparse(batch_chars_sparse),
    output_encoding='UTF-8')
tf.strings.unicode_encode(
    tf.RaggedTensor.from_tensor(batch_chars_padded, padding=-1),
    output_encoding='UTF-8')

코드 출처: https://www.tensorflow.org/tutorials/load_data/unicode

출력 결과

When encoding multiple strings of same lengths, tf.Tensor is used as input
When encoding multiple strings with varying length, a tf.RaggedTensor should be used as input:
If there is a tensor with multiple strings in padded/sparse format, convert it to a tf.RaggedTensor before calling unicode_encode

핵심 정리

  • 길이가 같은 여러 문자열을 인코딩할 때는 tf.Tensor를 입력으로 사용할 수 있습니다.
  • 길이가 제각각인 여러 문자열을 인코딩할 때는 tf.RaggedTensor를 입력으로 사용해야 합니다.
  • 패딩/희소 형식의 여러 문자열이 담긴 텐서는 unicode_encode를 호출하기 전에 반드시 tf.RaggedTensor로 변환해야 합니다.