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

TensorFlow를 활용한 Python 기반 Stack Overflow 질문 데이터셋 로드 방법

TensorFlow는 구글(Google)이 제공하는 머신러닝 프레임워크입니다. 오픈소스 프레임워크로, Python과 함께 사용하여 알고리즘, 딥러닝 애플리케이션 등 다양한 작업을 구현할 수 있으며 연구 목적과 상용(프로덕션) 목적 모두에 활용됩니다. 복잡한 수학 연산을 빠르게 수행할 수 있도록 돕는 최적화 기법을 갖추고 있습니다.

이러한 성능은 NumPy와 다차원 배열을 기반으로 하기 때문에 가능합니다. 이 다차원 배열은 '텐서(tensor)'라고도 불립니다. TensorFlow 프레임워크는 심층 신경망(deep neural network) 작업을 지원하며, 뛰어난 확장성을 자랑하고 다양한 인기 데이터셋을 함께 제공합니다. GPU 연산을 활용하고 리소스 관리를 자동화하며, 방대한 머신러닝 라이브러리를 포함하고 있어 문서화와 커뮤니티 지원도 잘 되어 있습니다. 또한 딥러닝 모델을 실행하고 학습시켜, 해당 데이터셋의 특성을 예측하는 애플리케이션을 만들 수 있습니다.

'tensorflow' 패키지는 Windows 환경에서 아래 명령어 한 줄로 설치할 수 있습니다.

pip install tensorflow

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

예제 코드

다음은 Python으로 Stack Overflow 질문 데이터셋을 로드하는 코드입니다.

batch_size = 32
seed = 42
print("학습 파라미터가 정의되었습니다")
raw_train_ds = preprocessing.text_dataset_from_directory(
    train_dir,
    batch_size=batch_size,
    validation_split=0.25,
    subset='training',
    seed=seed)
for text_batch, label_batch in raw_train_ds.take(1):
    for i in range(10):
        print("Question: ", text_batch.numpy()[i][:100], '...')
        print("Label:", label_batch.numpy()[i])

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

실행 결과

학습 파라미터가 정의되었습니다
Found 8000 files belonging to 4 classes.
Using 6000 files for training.
Question: b'"my tester is going to the wrong constructor i am new to programming so if i ask a question that can\' ...'
Label: 1
Question: b'"blank code slow skin detection this code changes the color space to lab and using a threshold finds\' ...'
Label: 3
Question: b'"option and validation in blank i want to add a new option on my system where i want to add two text\' ...'
Label: 1
Question: b'"exception: dynamic sql generation for the updatecommand is not supported against a selectcommand th\' ...'
Label: 0
Question: b'"parameter with question mark and super in blank, i\\\'ve come across a method that is formatted like t\' ...'
Label: 1
Question: b'call two objects wsdl the first time i got a very strange wsdl. ..i would like to call the object (i\' ...'
Label: 0
Question: b'how to correctly make the icon for systemtray in blank using icon sizes of any dimension for systemt\' ...'
Label: 0
Question: b'"is there a way to check a variable that exists in a different script than the original one? i\\\'m try\' ...'
Label: 3
Question: b'"blank control flow i made a number which asks for 2 numbers with blank and responds with the corre\' ...'
Label: 0
Question: b'"credentials cannot be used for ntlm authentication i am getting org.apache.commons.httpclient.auth.\' ...'
Label: 1

코드 설명

  • 디스크에 저장된 데이터를 불러와 학습에 적합한 형태로 준비합니다.
  • 'text_dataset_from_directory' 유틸리티를 사용하여 레이블이 지정된 데이터셋을 생성합니다.
  • 'tf.data'는 입력 파이프라인(input pipeline)을 구축하는 데 사용되는 강력한 도구 모음입니다.
  • 'text_dataset_from_directory' 유틸리티에 디렉터리 구조가 전달됩니다.
  • Stack Overflow 질문 데이터셋은 학습(train) 데이터셋과 테스트(test) 데이터셋으로 나뉩니다.
  • 'validation_split' 옵션을 통해 검증(validation) 세트가 생성됩니다.
  • 레이블은 0, 1, 2, 3 중 하나의 값으로 구성됩니다.