본문 바로가기
자연어처리(NLP) & CHAT GPT/NLP

[NLP] Transformer, BERT - 실습

by 11car28z 2023. 8. 10.

Transformer -> BERT/GPT

pip install transformers

 

import pandas as pd
from transformers import BertTokenizer

tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") # Bert-base의 토크나이저

result = tokenizer.tokenize('Here is the sentence I want embeddings for.')
print(result)

#embeddings가 없는 단어라
#-> 기존 단어 집합을 기준으로 쪼개기 = 'em', '##bed', '##ding', '##s'

 

print(tokenizer.vocab['here']) #2182

 

#이 단어는 단어 집합에 없기때문에 ERROR 발생!!!!!
print(tokenizer.vocab['embeddings'])

#'embeddings'을 쪼갠 단어들은 존재한다.
print(tokenizer.vocab['em']) #7861
print(tokenizer.vocab['##bed']) #8270
print(tokenizer.vocab['##ding']) #4667
print(tokenizer.vocab['##s'])# 2015

 

# BERT의 단어 집합을 vocabulary.txt에 저장
with open('vocabulary.txt', 'w') as f:
  for token in tokenizer.vocab.keys():
    f.write(token + '\n')

 

df = pd.read_fwf('vocabulary.txt', header=None)
df

# BERT에서 사용되는 특별 토큰들과 그와 맵핑되는 정수

# [PAD] - 0
# [UNK] - 100
# [CLS] - 101
# [SEP] - 102
# [MASK] - 103

한국어 토큰화 : https://github.com/MrBananaHuman/KorNlpTutorial/blob/main/1_%ED%95%9C%EA%B5%AD%EC%96%B4_tokenizing.ipynb

 

# 포지셔널 인코딩은 사인 함수와 코사인 함수를 사용

BERT


BERT 모델 참고: https://huggingface.co/docs/transformers/model_doc/bert

 

BERT

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

huggingface.co

BERT Fine-Tuning 참고: https://mccormickml.com/2019/07/22/BERT-fine-tuning/

 

BERT Fine-Tuning Tutorial with PyTorch · Chris McCormick

BERT Fine-Tuning Tutorial with PyTorch 22 Jul 2019 By Chris McCormick and Nick Ryan Revised on 3/20/20 - Switched to tokenizer.encode_plus and added validation loss. See Revision History at the end for details. In this tutorial I’ll show you how to use B

mccormickml.com


영어 BERT의 마스크드 언어 모델(Masked Language Model)

1. 마스크드 언어 모델과 토크나이저

#우리가 사용하는 모델과 토크나이저는 항상 맵핑 관계
from transformers import TFBertForMaskedLM
from transformers import AutoTokenizer

 

#[MASK]라고 되어있는 단어를 맞추기 위한 마스크드 언어 모델링을 위한 구조로 BERT를 로드
model = TFBertForMaskedLM.from_pretrained('bert-large-uncased')

#해당 모델이 학습되었을 당시에 사용되었던 토크나이저를 로드
tokenizer = AutoTokenizer.from_pretrained("bert-large-uncased")

2. BERT의 입력

inputs = tokenizer('Soccer is a really fun [MASK].', return_tensors='tf')

 

#토크나이저로 변환된 결과에서 input_ids를 통해 정수 인코딩 결과
print(inputs['input_ids'])

# 현재의 입력은 문장이 두 개가 아니라 한 개이므로 여기서는 문장 길이만큼의 0 시퀀스를 얻습니다.
print(inputs['token_type_ids'])

#현재의 입력에서는 패딩이 없으므로 여기서는 문장 길이만큼의 1 시퀀스를 얻습니다.
#만약 뒤에 패딩이 있었다면 패딩이 시작되는 구간부터는 0의 시퀀스가 나오게 되지만
print(inputs['attention_mask'])

3. [MASK] 토큰 예측하기

from transformers import FillMaskPipeline
pip = FillMaskPipeline(model=model, tokenizer=tokenizer)

 

# [MASK] 자리에 들어가야하는 단어 -> 확률로 출력
pip('Soccer is a really fun [MASK].')

pip("It's very [MASK] today")

 


한국어 BERT의 마스크드 언어 모델(Masked Language Model)

1. 마스크드 언어 모델과 토크나이저

#구글의 한국어 BERT를 우리나라 사람이 Finetuning

 

model = TFBertForMaskedLM.from_pretrained('klue/bert-base', from_pt=True)
tokenizer = AutoTokenizer.from_pretrained("klue/bert-base")

 

2. BERT의 입력

inputs = tokenizer('축구는 정말 재미있는 [MASK]다.', return_tensors='tf')

 

print(inputs['input_ids'])

print(inputs['token_type_ids'])

print(inputs['attention_mask'])

 

3. [MASK] 토큰 예측하기

from transformers import FillMaskPipeline
pip = FillMaskPipeline(model=model, tokenizer=tokenizer)

 

pip('축구는 정말 재미있는 [MASK]다.')

 

pip('졸릴때는 [MASK]이 최고다.')


 

영어 BERT의 다음 문장 예측(Next Sentence Prediction)

1. 다음 문장 예측 모델과 토크나이저

import tensorflow as tf
from transformers import TFBertForNextSentencePrediction
from transformers import AutoTokenizer

 

model = TFBertForNextSentencePrediction.from_pretrained('bert-base-uncased')
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')

2. BERT의 입력

prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
next_sentence = "pizza is eaten with the use of a knife and fork. In casual settings, however, it is cut into wedges to be eaten while held in the hand."

 

encoding = tokenizer(prompt, next_sentence, return_tensors='tf')

 

print(encoding['input_ids'])

#101과 102는 특별 토큰이라는 점
print(tokenizer.cls_token, ':', tokenizer.cls_token_id) #[CLS] : 101
print(tokenizer.sep_token, ':' , tokenizer.sep_token_id) #[SEP] : 102

 

#수 인코딩 결과를 다시 디코딩
print(tokenizer.decode(encoding['input_ids'][0]))

 

print(encoding['token_type_ids'])

 

3. 다음 문장 예측하기

logits = model(encoding['input_ids'], token_type_ids=encoding['token_type_ids'])[0]
softmax = tf.keras.layers.Softmax()
probs = softmax(logits)
print(probs)

 

print('최종 예측 레이블 :', tf.math.argmax(probs, axis=-1).numpy()) #최종 예측 레이블 : [0]

 

이어지는 두 개의 문장의 레이블은 0.
이어지지 않는 두 개의 문장의 경우에는 레이블을 1

 

# 상관없는 두 개의 문장

prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
next_sentence = "The sky is blue due to the shorter wavelength of blue light."
encoding = tokenizer(prompt, next_sentence, return_tensors='tf')

logits = model(encoding['input_ids'], token_type_ids=encoding['token_type_ids'])[0]

softmax = tf.keras.layers.Softmax()
probs = softmax(logits)
print('최종 예측 레이블 :', tf.math.argmax(probs, axis=-1).numpy())

 


한국어 BERT의 다음 문장 예측(Next Sentence Prediction)

1. 다음 문장 예측 모델과 토크나이저

import tensorflow as tf
from transformers import TFBertForNextSentencePrediction
from transformers import AutoTokenizer

 

model = TFBertForNextSentencePrediction.from_pretrained('klue/bert-base', from_pt=True)
tokenizer = AutoTokenizer.from_pretrained("klue/bert-base")

 

2. 다음 문장 예측하기

두 개의 문장이 학습할때는 모델이 본 적 없는 문장
이 문장으로 모델은 이어지는 것인지 아닌지 확인하려고 학습했던 모델에 넣어본다.
답이 잘 못나온것은 학습이 안되엇다는 것 -> 데이터 부족
학습을 했어도 유사한 문장이 이어지는 문장속에 많이 등장하는 단어들이 있어서
ex) "날씨가 좋은데 영화나 보러갈까?" 같은 문장이 있을 확률이 높다.

 

# 이어지는 두 개의 문장
prompt = "오늘 날씨가 참 덥습니다."
next_sentence = "나의 취미는 영화 감상입니다."
encoding = tokenizer(prompt, next_sentence, return_tensors='tf')

logits = model(encoding['input_ids'], token_type_ids=encoding['token_type_ids'])[0]

softmax = tf.keras.layers.Softmax()
probs = softmax(logits)
print('최종 예측 레이블 :', tf.math.argmax(probs, axis=-1).numpy())

 

# 상관없는 두 개의 문장
prompt = "2002년 월드컵 축구대회는 일본과 공동으로 개최되었던 세계적인 큰 잔치입니다."
next_sentence = "극장가서 로맨스 영화를 보고싶어요"
encoding = tokenizer(prompt, next_sentence, return_tensors='tf')

logits = model(encoding['input_ids'], token_type_ids=encoding['token_type_ids'])[0]

softmax = tf.keras.layers.Softmax()
probs = softmax(logits)
print('최종 예측 레이블 :', tf.math.argmax(probs, axis=-1).numpy())

 

'자연어처리(NLP) & CHAT GPT > NLP' 카테고리의 다른 글

[NLP] BERT+ Fine-tuning, KoBERT - 실습  (2) 2023.08.23
[NLP] GPT, KoGPT - 실습  (0) 2023.08.22
[NLP] BERT  (0) 2023.08.09
[NLP] Seq2Seq - 실습  (0) 2023.08.08
[NLP] Seq2eq에서 BERT까지  (0) 2023.08.07