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

파이썬(Python)으로 일리아드(Illiad) 데이터셋을 훈련용으로 준비하는 방법

TensorFlow란 무엇인가?

TensorFlow는 구글(Google)이 제공하는 대표적인 머신러닝 프레임워크입니다. 오픈소스로 공개되어 있으며, 파이썬(Python)과 함께 사용해 다양한 알고리즘과 딥러닝 애플리케이션을 구현할 수 있습니다. 학술 연구부터 실제 서비스 운영(프로덕션) 환경까지 폭넓게 활용되고 있습니다.

'tensorflow' 패키지는 윈도우(Windows) 환경에서 아래 한 줄의 명령어로 간단히 설치할 수 있습니다.

pip install tensorflow

텐서(Tensor)는 TensorFlow에서 사용되는 핵심 데이터 구조입니다. 텐서는 흐름 다이어그램에서 노드 간의 간(edge)을 연결하는 역할을 하며, 이 다이어그램을 '데이터 플로우 그래프(Data flow graph)'라고 부릅니다. 쉽게 말해 텐서는 다차원 배열 또는 리스트라고 이해하면 됩니다.

일리아드 데이터셋 소개

이번 예제에서는 일리아드(Illiad) 데이터셋을 사용합니다. 이 데이터셋에는 William Cowper, Edward(더비 백작), Samuel Butler 세 사람이 번역한 작품의 텍스트 데이터가 담겨 있습니다. 모델은 한 줄의 텍스트가 주어졌을 때 그것을 누가 번역했는지 식별하도록 훈련됩니다.

사용된 텍스트 파일은 사전에 전처리 과정을 거쳤습니다. 여기에는 문서의 머리말과 꼬리말 제거, 행 번호 삭제, 장(chapter) 제목 정리 등의 작업이 포함됩니다.

아래 코드는 Google Colaboratory 환경에서 실행됩니다. Google Colab은 브라우저에서 바로 파이썬 코드를 실행할 수 있게 해주며, 별도의 설정이 필요 없고 GPU(그래픽 처리 장치)를 무료로 사용할 수 있다는 큰 장점이 있습니다. Colaboratory는 Jupyter Notebook을 기반으로 만들어졌습니다.

예제: 데이터 토큰화하기

텍스트 데이터를 모델 훈련에 사용하려면 먼저 문장을 단어 단위로 나누는 '토큰화(tokenization)' 과정이 필요합니다. 다음은 UnicodeScriptTokenizer를 활용해 데이터셋을 토큰화하는 코드입니다.

print("Prepare the dataset for training")
tokenizer = tf_text.UnicodeScriptTokenizer()
print("Defining a function named 'tokenize' to tokenize the text data")
def tokenize(text, unused_label):
   lower_case = tf_text.case_fold_utf8(text)
   return tokenizer.tokenize(lower_case)
tokenized_ds = all_labeled_data.map(tokenize)
print("Iterate over the dataset and print a few samples")
for text_batch in tokenized_ds.take(6):
   print("Tokens: ", text_batch.numpy())

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

출력 결과

Prepare the dataset for training
Defining a function named 'tokenize' to tokenize the text data
WARNING:tensorflow:From /usr/local/lib/python3.6/distpackages/tensorflow/python/util/dispatch.py:201: batch_gather (from
tensorflow.python.ops.array_ops) is deprecated and will be removed after 2017-10-25.
Instructions for updating:
`tf.batch_gather` is deprecated, please use `tf.gather` with `batch_dims=-1` instead.
Iterate over the dataset and print a few samples
Tokens: [b'but' b'i' b'have' b'now' b'both' b'tasted' b'food' b',' b'and' b'given']
Tokens: [b'all' b'these' b'shall' b'now' b'be' b'thine' b':' b'but' b'if' b'the'
b'gods']
Tokens: [b'their' b'spiry' b'summits' b'waved' b'.' b'there' b',' b'unperceived']
Tokens: [b'"' b'i' b'pray' b'you' b',' b'would' b'you' b'show' b'your' b'love'
b',' b'dear' b'friends' b',']
Tokens: [b'entering' b'beneath' b'the' b'clavicle' b'the' b'point']
Tokens: [b'but' b'grief' b',' b'his' b'father' b'lost' b',' b'awaits' b'him'
b'now' b',']

코드 설명

  • 'tokenize' 함수가 정의됩니다. 이 함수는 데이터셋 내 문장에서 공백을 기준으로 단어를 분리해 토큰화를 수행합니다.

  • 토큰화 전에 case_fold_utf8 메서드를 통해 텍스트를 소문자로 변환하여 대소문자 차이로 인한 중복을 방지합니다.

  • 정의된 함수는 map 메서드를 통해 데이터셋 전체에 일괄 적용됩니다.

  • 마지막으로 take(6)을 사용해 토큰화가 완료된 데이터셋의 샘플 6개를 콘솔에 출력해 결과를 확인합니다.