1.DataSet 로드
datasets 라이브러리를 이용해 GLUE 데이터셋 중 하나인 MRPC를 로드한다.
학습(train), 검증(validation), 테스트(test) 데이터가 포함된다.
(문장 유사성 판단 작업에 사용가능)
### 데이터셋 로드
raw_datasets = load_dataset("glue", "mrpc")
2.토크나이저와 모델 로드
토크나이저: bert-base-uncased 체크포인트를 사용하여 문장을 토큰으로 변환한다.
모델: 사전 학습된 bert-base-uncased을 로드하고, 이진 분류를 위한 TFAutoModelForSequenceClassification으로 초기화한다.
옵티마이저: Adam 옵티마이저를 사용하여 학습 속도를 조절한다.
### 토크나이저와 모델 로드
checkpoint = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = TFAutoModelForSequenceClassification.from_pretrained(checkpoint)
optimizer = tf.keras.optimizers.Adam(learning_rate=5e-5)
3.토큰화
map을 사용하여 tokenize_function을 데이터셋에 적용
batched=True로 여러 샘플을 한 번에 처리하여 속도를 향상한다.
### 토큰화 함수
def tokenize_function(example):
return tokenizer(example["sentence1"], example["sentence2"], truncation=True)
### 데이터셋 토큰화
tokenized_datasets = raw_datasets.map(tokenize_function, batched=True)
4.전체코드
from transformers import AutoTokenizer,TFAutoModelForSequenceClassification
import tensorflow as tf
from datasets import load_dataset
### 데이터셋 로드
raw_datasets = load_dataset("glue", "mrpc")
### 토크나이저와 모델 로드
checkpoint = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = TFAutoModelForSequenceClassification.from_pretrained(checkpoint)
optimizer = tf.keras.optimizers.Adam(learning_rate=5e-5)
### 토큰화 함수
def tokenize_function(example):
return tokenizer(example["sentence1"], example["sentence2"], truncation=True)
### 데이터셋 토큰화
tokenized_datasets = raw_datasets.map(tokenize_function, batched=True)
print(tokenized_datasets["train"][0])
결과
{'sentence1': 'Amrozi accused his brother , whom he called " the witness " , of deliberately distorting his evidence .', 'sentence2': 'Referring to him as only " the witness " , Amrozi accused his brother of deliberately distorting his evidence .', 'label': 1, 'idx': 0, 'input_ids': [101, 2572, 3217, 5831, 5496, 2010, 2567, 1010, 3183, 2002, 2170, 1000, 1996, 7409, 1000, 1010, 1997, 9969, 4487, 23809, 3436, 2010, 3350, 1012, 102, 7727, 2000, 2032, 2004, 2069, 1000, 1996, 7409, 1000, 1010, 2572, 3217, 5831, 5496, 2010, 2567, 1997, 9969, 4487, 23809, 3436, 2010, 3350, 1012, 102], 'token_type_ids': [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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
반응형
'AI' 카테고리의 다른 글
[AI] DataSet 용어 (0) | 2025.01.09 |
---|---|
[AI] AutoTokenizer, AutoModel (0) | 2025.01.07 |
[AI] 편향(Bias) (0) | 2025.01.07 |