[Tensorflow] 3. Natural Language Processing in TensorFlow (1 week Sequence models and literature) : programming (3)

gunny·2024년 2월 12일
0

[Tensorflow] 3. Natural Language Processing in TensorFlow (1 week Sequence models and literature) : programming (3)

풍자 데이터세트 토큰화 (Sarcasm Dataset)

  • 여기서는 풍자 감지를 위한 뉴스 헤드라인 데이터 세트를 전처리한다.
    여기에는 냉소적인지 여부가 표시된 뉴스 헤드라인이 포함된 데이터를 사용한다.

[1] Download and inspect the dataset

sarcasm 데이터 다운로드

import requests

url = 'https://storage.googleapis.com/tensorflow-1-public/course3/sarcasm.json'
filename = 'sarcasm.json'

response = requests.get(url)

with open(filename, 'wb') as f:
    f.write(response.content)

json 데이터 불러오기

  • 데이터세트는 JSON 파일로 저장되며 Python의 json 모듈을 사용하여 작업공간에 로드할 수 있다. 아래 셀은 JSON 파일을 목록으로 압축 해제한다.
import json

with open('./sarcasm.json', 'r') as f:
    datastore = json.load(f)

print(len(datastore))
print(datastore[0])
print(datastore[20000])

# output

26709
{'article_link': 'https://www.huffingtonpost.com/entry/versace-black-code_us_5861fbefe4b0de3a08f600d5', 'headline': "former versace store clerk sues over secret 'black code' for minority shoppers", 'is_sarcastic': 0}
{'article_link': 'https://www.theonion.com/pediatricians-announce-2011-newborns-are-ugliest-babies-1819572977', 'headline': 'pediatricians announce 2011 newborns are ugliest babies in 30 years', 'is_sarcastic': 1}
  • 목록의 몇 가지 요소를 확인할 수 있다.
    각 요소는 URL 링크가 포함된 사전, 실제 헤드라인, is_sarcastic이라는 라벨로 구성되어 있음을 알 수 있다.
    아래에는 대조되는 라벨이 있는 두 가지 요소가 출력되어 있다.

<is_sarastic = 0> label

{'article_link': 'https://www.huffingtonpost.com/entry/versace-black-code_us_5861fbefe4b0de3a08f600d5', 'headline': "former versace store clerk sues over secret 'black code' for minority shoppers", 'is_sarcastic': 0}

<is_sarastic = 1> label

{'article_link': 'https://www.theonion.com/pediatricians-announce-2011-newborns-are-ugliest-babies-1819572977', 'headline': 'pediatricians announce 2011 newborns are ugliest babies in 30 years', 'is_sarcastic': 1}

데이터셋 만들기

  • 크나이저를 사용할 때 더 쉽게 처리할 수 있도록 모든 URL, 헤드라인 및 라벨을 수집한다. 아래에서는 핸들링할 때 헤드라인만 필요하지만 URL과 라벨도 각자 수집했다.
sentences = []
labels = []
urls = []

for item in datastore:
    sentences.append(item['headline'])
    labels.append(item['is_sarcastic'])
    urls.append(item['article_link'])
    
print("\nsentences : ", sentences[:3])
print("\nlabels : ", labels[:3])
print("\nurls : ", urls[:3])

# outout

sentences :  ["former versace store clerk sues over secret 'black code' for minority shoppers", "the 'roseanne' revival catches up to our thorny political mood, for better and worse", "mom starting to fear son's web series closest thing she will have to grandchild"]

labels :  [0, 0, 1]

urls :  ['https://www.huffingtonpost.com/entry/versace-black-code_us_5861fbefe4b0de3a08f600d5', 'https://www.huffingtonpost.com/entry/roseanne-revival-review_us_5ab3a497e4b054d118e04365', 'https://local.theonion.com/mom-starting-to-fear-son-s-web-series-closest-thing-she-1819576697']

Preprocessing the headlines

  • 문장 목록을 패딩된 시퀀스로 변환할 수 있다.
    word_index 사전을 생성하고 26,709개의 헤드라인 각각에 대해 패딩된 시퀀스 목록을 생성한다.
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences

tokenizer = Tokenizer(oov_token='<OOV>')
tokenizer.fit_on_texts(sentences)

word_index = tokenizer.word_index
print(f"number of words in word_index", {len(word_index)})
print()

sequences = tokenizer.texts_to_sequences(sentences)
padded = pad_sequences(sequences, padding='post')


# output
number of words in word_index {29657}

샘플 데이터로 확인하기

index = 2
print(f"sample headline : {sentences[index]}")
print(f"padded sequence : {padded[index]}")
print()

print(f"shape of padded sequences : {padded.shape}")


# output
sample headline : mom starting to fear son's web series closest thing she will have to grandchild
padded sequence : [  145   838     2   907  1749  2093   582  4719   221   143    39    46
     2 10736     0     0     0     0     0     0     0     0     0     0
     0     0     0     0     0     0     0     0     0     0     0     0
     0     0     0     0]

shape of padded sequences : (26709, 40)
profile
꿈꾸는 것도 개발처럼 깊게

0개의 댓글

관련 채용 정보