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

파이썬(Python)으로 텍스트 데이터를 차원 벡터로 임베딩하는 방법

TensorFlow는 구글(Google)에서 제공하는 머신러닝 프레임워크입니다. 오픈소스 프레임워크로, 파이썬과 함께 사용하여 알고리즘 구현, 딥러닝 애플리케이션 개발 등 다양한 작업을 수행할 수 있으며, 연구 목적과 실제 프로덕션 환경 모두에서 활용됩니다.

Keras는 ONEIROS(Open-ended Neuro-Electronic Intelligent Robot Operating System) 프로젝트의 연구 과정에서 개발되었습니다. Keras는 파이썬으로 작성된 딥러닝 API로, 머신러닝 문제 해결에 도움을 주는 생산적인 인터페이스를 갖춘 고수준(high-level) API입니다. TensorFlow 프레임워크 위에서 동작하며, 빠른 실험을 지원하도록 설계되었습니다. 또한 머신러닝 솔루션을 개발하고 캡슐화하는 데 필수적인 추상화 계층과 빌딩 블록을 제공합니다.

Keras는 이미 TensorFlow 패키지에 포함되어 있으며, 아래 코드 한 줄로 손쉽게 불러올 수 있습니다.

import tensorflow
from tensorflow import keras

Keras 함수형 API란?

Keras의 함수형 API(Functional API)를 사용하면 순차형(Sequential) API로 만든 모델보다 훨씬 유연한 모델을 구축할 수 있습니다. 함수형 API는 비선형(non-linear) 토폴로지를 가진 모델을 다룰 수 있고, 레이어를 공유하거나 여러 개의 입력과 출력을 처리할 수도 있습니다. 일반적으로 딥러닝 모델은 여러 층으로 구성된 방향성 비순환 그래프(DAG, Directed Acyclic Graph) 형태를 띠며, 함수형 API는 바로 이 그래프 구조의 레이어를 손쉽게 만들어 줍니다.

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

다음은 제목(title)의 모든 단어를 64차원 벡터로 임베딩하는 코드 예제입니다.

예제 코드

print("Number of unique issue tags")
num_tags = 12
print("Size of vocabulary while preprocessing text data")
num_words = 10000
print("Number of classes for predictions")
num_classes = 4

title_input = keras.Input(
    shape=(None,), name="title"
)
print("Variable length int sequence")
body_input = keras.Input(shape=(None,), name="body")
tags_input = keras.Input(
    shape=(num_tags,), name="tags"
)
print("Embed every word in the title to a 64-dimensional vector")
title_features = layers.Embedding(num_words, 64)(title_input)
print("Embed every word into a 64-dimensional vector")
body_features = layers.Embedding(num_words, 64)(body_input)
print("Reduce sequence of embedded words into single 128-dimensional vector")
title_features = layers.LSTM(128)(title_features)
print("Reduce sequence of embedded words into single 132-dimensional vector")
body_features = layers.LSTM(32)(body_features)
print("Merge available features into a single vector by concatenating it")
x = layers.concatenate([title_features, body_features, tags_input])
print("Use logistic regression to predict the features")
priority_pred = layers.Dense(1, name="priority")(x)
department_pred = layers.Dense(num_classes, name="class")(x)
print("Instantiate a model that predicts priority and class")
model = keras.Model(
    inputs=[title_input, body_input, tags_input],
    outputs=[priority_pred, department_pred],
)

코드 출처: https://www.tensorflow.org/guide/keras/functional

실행 결과

Number of unique issue tags
Size of vocabulary while preprocessing text data
Number of classes for predictions
Variable length int sequence
Embed every word in the title to a 64-dimensional vector
Embed every word into a 64-dimensional vector
Reduce sequence of embedded words into single 128-dimensional vector
Reduce sequence of embedded words into single 132-dimensional vector
Merge available features into a single vector by concatenating it
Use logistic regression to predict the features
Instantiate a model that predicts priority and class

코드 설명

  • 다중 입력·다중 출력 지원: 이 예제에서는 제목(title), 본문(body), 태그(tags) 세 가지 입력을 받아 우선순위(priority)와 부서(class) 두 가지 출력을 예측합니다. 함수형 API는 이처럼 여러 입력과 출력을 동시에 처리할 수 있습니다.
  • 임베딩 레이어: layers.Embedding(num_words, 64)를 통해 어휘 크기 10,000개의 단어를 각각 64차원 밀집 벡터(dense vector)로 변환합니다. 이 과정에서 텍스트 데이터가 신경망이 학습할 수 있는 수치 벡터 형태로 변환됩니다.
  • LSTM 레이어: 임베딩된 단어 시퀀스를 LSTM 레이어에 통과시켜 하나의 고정 길이 벡터로 압축합니다. 제목 특징은 128차원, 본문 특징은 32차원 벡터로 축소됩니다.
  • 특징 결합: layers.concatenate를 사용해 제목 특징, 본문 특징, 태그 입력을 하나의 벡터로 병합합니다.
  • 예측 레이어: 병합된 특징 벡터를 Dense 레이어에 통과시켜 로지스틱 회귀 방식으로 우선순위와 부서를 예측합니다.
  • 함수형 API의 필요성: 이처럼 복잡한 다중 입출력 구조는 순차형(Sequential) API로는 구현할 수 없으며, 반드시 함수형 API를 사용해야 합니다.