TensorFlow는 구글(Google)에서 제공하는 머신러닝 프레임워크입니다. 오픈소스로 공개되어 있으며, Python과 함께 사용하여 다양한 알고리즘, 딥러닝 애플리케이션 등을 구현할 수 있습니다. 연구 목적뿐만 아니라 실제 프로덕션 환경에서도 널리 활용됩니다.
'tensorflow' 패키지는 Windows 환경에서 아래 명령어 한 줄로 간단히 설치할 수 있습니다.
pip install tensorflow
텐서(Tensor)는 TensorFlow에서 사용하는 핵심 데이터 구조입니다. 플로우 다이어그램(flow diagram)의 엣지(edge)를 연결하는 역할을 하며, 이 다이어그램은 '데이터 플로우 그래프(Data flow graph)'라고 불립니다. 텐서는 쉽게 말해 다차원 배열 또는 리스트라고 할 수 있습니다.
이 글의 코드는 Google Colaboratory에서 실행합니다. Google Colab 또는 Colaboratory는 브라우저에서 바로 Python 코드를 실행할 수 있도록 도와주며, 별도의 설정 없이 GPU(그래픽 처리 장치)에 무료로 접근할 수 있다는 장점이 있습니다. Colaboratory는 Jupyter Notebook을 기반으로 만들어졌습니다.
예제 코드
다음은 코드 스니펫입니다.
print("1234 ---> ", int_vectorize_layer.get_vocabulary()[1289])
print("321 ---> ", int_vectorize_layer.get_vocabulary()[313])
print("Vocabulary size is : {}".format(len(int_vectorize_layer.get_vocabulary())))
print("The text vectorization is applied to the training dataset")
binary_train_ds = raw_train_ds.map(binary_vectorize_text)
print("The text vectorization is applied to the validation dataset")
binary_val_ds = raw_val_ds.map(binary_vectorize_text)
print("The text vectorization is applied to the test dataset")
binary_test_ds = raw_test_ds.map(binary_vectorize_text)
int_train_ds = raw_train_ds.map(int_vectorize_text)
int_val_ds = raw_val_ds.map(int_vectorize_text)
int_test_ds = raw_test_ds.map(int_vectorize_text)코드 출처: https://www.tensorflow.org/tutorials/load_data/text
실행 결과
1234 ---> substring 321 ---> 20 Vocabulary size is : 10000 The text vectorization is applied to the training dataset The text vectorization is applied to the validation dataset The text vectorization is applied to the test dataset
코드 설명
- 출력 결과를 보면, 어휘 사전(vocabulary)에서 인덱스 1289에 해당하는 단어는 'substring'이고, 인덱스 313에 해당하는 단어는 '20'입니다. 전체 어휘 크기는 10,000개입니다.
- 전처리 과정의 마지막 단계로, 'TextVectorization' 레이어가 학습 데이터(training data), 검증 데이터(validation dataset), 그리고 테스트 데이터(test dataset)에 각각 적용됩니다.
- binary_vectorize_text 함수를 사용하면 텍스트를 멀티-핫(multi-hot) 인코딩 방식으로 변환하고, int_vectorize_text 함수를 사용하면 정수 시퀀스 형태로 변환합니다. 두 가지 방식 모두 map 메서드를 통해 데이터셋 전체에 일괄 적용됩니다.