TensorFlow란 무엇인가?
TensorFlow는 구글(Google)이 제공하는 오픈소스 머신러닝 프레임워크입니다. Python과 함께 사용되어 각종 알고리즘, 딥러닝 애플리케이션 등을 구현할 수 있으며, 연구 목적과 실제 서비스(프로덕션) 환경 모두에서 폭넓게 활용됩니다. 복잡한 수학 연산을 빠르게 처리할 수 있도록 다양한 최적화 기법을 내장하고 있다는 점이 큰 강점입니다.
TensorFlow는 NumPy와 다차원 배열을 기반으로 동작하며, 이 다차원 배열을 '텐서(tensor)'라고 부릅니다. 이 프레임워크는 심층 신경망(deep neural network) 구현을 지원하고, 뛰어난 확장성을 갖추고 있으며 다양한 인기 데이터셋을 함께 제공합니다. GPU 연산을 활용해 리소스 관리를 자동화하고, 방대한 머신러닝 라이브러리와 충실한 문서화·커뮤니티 지원도 갖추고 있습니다. 덕분에 딥러닝 모델을 실행하고 학습시킨 뒤, 데이터셋의 특성을 예측하는 애플리케이션까지 손쉽게 만들 수 있습니다.
TensorFlow 설치하기
Windows 환경에서는 아래 명령어 한 줄로 'tensorflow' 패키지를 설치할 수 있습니다.
pip install tensorflow
텐서(Tensor)란?
텐서는 TensorFlow의 핵심 데이터 구조입니다. '데이터 흐름 그래프(Data Flow Graph)'라고 불리는 플로우 다이어그램에서 노드 사이의 엣지(edge)를 연결하는 역할을 하며, 실체는 다차원 배열 또는 리스트에 해당합니다.
이 글의 예제 코드는 Google Colaboratory(Colab)에서 실행되었습니다. Google Colab은 브라우저에서 바로 Python 코드를 실행할 수 있는 환경으로, 별도의 설정 없이 GPU까지 무료로 사용할 수 있으며 Jupyter Notebook을 기반으로 만들어졌습니다.
예제: Stack Overflow 질문 텍스트 벡터화
Stack Overflow 질문 데이터셋의 텍스트를 벡터화하는 코드 스니펫은 다음과 같습니다. 여기서 binary_vectorize_text와 int_vectorize_text는 앞 단계에서 구성한 TextVectorization 레이어를 감싼 함수입니다.
print("The vectorize function is defined")
def int_vectorize_text(text, label):
text = tf.expand_dims(text, -1)
return int_vectorize_layer(text), label
print(" A batch of the dataset is retrieved")
text_batch, label_batch = next(iter(raw_train_ds))
first_question, first_label = text_batch[0], label_batch[0]
print("Question is : ", first_question)
print("Label is : ", first_label)
print("'binary' vectorized question is :",
binary_vectorize_text(first_question, first_label)[0])
print("'int' vectorized question is :",
int_vectorize_text(first_question, first_label)[0])
코드 출처 − https://www.tensorflow.org/tutorials/load_data/text
실행 결과
The vectorize function is defined
A batch of the dataset is retrieved
Question is : tf.Tensor(b'"function expected error in blank for dynamically created check box
when it is clicked i want to grab the attribute value.it is working in ie 8,9,10 but not working in ie
11,chrome shows function expected error..<input type=checkbox checked=\'checked\'
id=\'symptomfailurecodeid\' tabindex=\'54\' style=\'cursor:pointer;\' onclick=chkclickevt(this);
failurecodeid=""1"" >...function chkclickevt(obj) { .
alert(obj.attributes(""failurecodeid""));.}"\n', shape=(), dtype=string)
Label is : tf.Tensor(2, shape=(), dtype=int32)
'binary' vectorized question is : tf.Tensor([[1. 1. 1. ... 0. 0. 0.]], shape=(1, 10000), dtype=float32)
'int' vectorized question is : tf.Tensor(
[[ 37 464 65 7 16 12 879 262 181 448 44 10 6 700
3 46 4 2085 2 473 1 6 156 7 478 1 25 20
156 7 478 1 499 37 464 1 1846 1666 1 1 1 1
1 1 1 1 0 0 0 0 0 0 0 0 0 0
...(중간 0 반복 생략)...
0 0 0 0 0 0 0 0 0 0 0 0]], shape=(1, 250), dtype=int64)
※ 가독성을 위해 'int' 벡터화 결과에서 0이 반복되는 중간 구간은 일부 생략했습니다.
코드 설명
binary 모드는 토큰의 존재 여부만을 표시하는 배열을 반환합니다.
int 모드에서는 모든 토큰이 고유한 정수로 치환됩니다.
int 모드는 토큰의 순서 정보를 그대로 유지한다는 특징이 있습니다.
먼저 벡터화 함수(int_vectorize_text)를 정의합니다.
데이터셋에서 한 개의 샘플(질문)을 가져온 뒤, 'binary' 방식과 'int' 방식으로 각각 벡터화하여 콘솔에 출력합니다.
특정 레이어에서 'get_vocabulary()' 메서드를 호출하면 정수 인덱스에 대응하는 문자열(토큰)을 역으로 조회할 수 있습니다.