여러 개의 유니코드 문자열은 Python의 encode 메서드를 사용하여 UTF-8로 인코딩된 문자열 형태로 손쉽게 표현할 수 있습니다.
함께 읽으면 좋은 글: TensorFlow란 무엇이며, Keras는 어떻게 TensorFlow와 함께 신경망을 구성하는가?
유니코드란 무엇인가?
자연어를 처리하는 딥러닝 모델은 서로 다른 문자 집합을 사용하는 다양한 언어를 다루어야 합니다. 유니코드(Unicode)는 전 세계 거의 모든 언어의 문자를 표현하기 위한 표준 인코딩 체계로, 각 문자는 0부터 0x10FFFF 사이의 고유한 정수 코드 포인트(code point)로 인코딩됩니다. 즉, 유니코드 문자열은 이러한 코드 값이 0개 이상 나열된 시퀀스라고 할 수 있습니다.
이 글에서는 Python으로 유니코드 문자열을 표현하는 방법과, 표준 문자열 연산의 유니코드 버전을 활용해 스크립트 감지를 기반으로 문자열을 토큰 단위로 분리하는 방법까지 살펴봅니다.
Google Colaboratory에서 코드 실행하기
아래 예제 코드는 Google Colaboratory(Colab) 환경에서 실행했습니다. Google Colab은 브라우저에서 별도 설정 없이 바로 Python 코드를 실행할 수 있도록 도와주는 도구로, GPU에 무료로 접근할 수 있으며 Jupyter Notebook을 기반으로 만들어졌습니다.
print("A set of Unicode strings which is represented as a UTF8-encoded string")
batch_utf8 = [s.encode('UTF-8') for s in[u'hÃllo', u'What is the weather tomorrow',u'Göödnight', u'😊']]
batch_chars_ragged = tf.strings.unicode_decode(batch_utf8,
input_encoding='UTF-8')
for sentence_chars in batch_chars_ragged.to_list():
print(sentence_chars)
print("Dense tensor with padding are printed")
batch_chars_padded = batch_chars_ragged.to_tensor(default_value=-1)
print(batch_chars_padded.numpy())
print("Converting to sparse matrix")
batch_chars_sparse = batch_chars_ragged.to_sparse()코드 출처: https://www.tensorflow.org/tutorials/load_data/unicode
실행 결과
A set of Unicode strings which is represented as a UTF8-encoded string
[104, 195, 108, 108, 111]
[87, 104, 97, 116, 32, 105, 115, 32, 116, 104, 101, 32, 119, 101, 97, 116, 104, 101, 114, 32, 116, 111, 109, 111, 114, 114, 111, 119]
[71, 246, 246, 100, 110, 105, 103, 104, 116]
[128522]
Dense tensor with padding are printed
[[ 104 195 108 108 111 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1]
[87 104 97 116 32 105 115 32 116 104
101 32 119 101 97 116 104 101 114 32
116 111 109 111 114 114 111 119]
[71 246 246 100 110 105 103 104 116 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
[128522 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]]
Converting to sparse matrix
코드 설명
- 여러 문자열을 한 번에 디코딩하면 문자열마다 포함된 문자 수가 서로 다를 수 있습니다.
- 이 경우 결과는
tf.RaggedTensor가 되며, 가장 안쪽 차원의 길이는 각 문자열이 가진 문자 수에 따라 달라집니다. tf.RaggedTensor는 그대로 사용할 수도 있고,tf.RaggedTensor.to_tensor메서드를 사용해 패딩(padding)이 적용된 밀집(dense)tf.Tensor로 변환하거나,tf.RaggedTensor.to_sparse메서드를 사용해tf.SparseTensor로 변환할 수도 있습니다.