텍스트 분류를 위한 전이 학습

PyTorch로 배우는 텍스트 딥러닝

Shubham Jain

Instructor

전이 학습이란?

 

전이 학습

  • 한 작업의 지식을 관련 작업에 활용

 

  • 시간 절약
  • 전문성 공유
  • 대량 데이터 필요 감소

 

  • 영어 교사가 역사 수업을 가르치기 시작함
PyTorch로 배우는 텍스트 딥러닝

전이 학습의 메커니즘

전이 학습 I

PyTorch로 배우는 텍스트 딥러닝

전이 학습의 메커니즘

전이 학습 II

PyTorch로 배우는 텍스트 딥러닝

전이 학습의 메커니즘

전이 학습 II

PyTorch로 배우는 텍스트 딥러닝

전이 학습의 메커니즘

전이 학습 III

PyTorch로 배우는 텍스트 딥러닝

사전 학습 모델: BERT

  • 트랜스포머 기반 양방향 인코더 표현(BERT)

Bert 감성 분석

  • 언어 모델링으로 학습됨
  • 다층 트랜스포머
  • 대규모 텍스트로 사전 학습
PyTorch로 배우는 텍스트 딥러닝

실습: BERT 구현

texts = ["I love this!", 
         "This is terrible.", 
         "Amazing experience!", 
         "Not my cup of tea."]
labels = [1, 0, 1, 0]

import torch from transformers import BertTokenizer, BertForSequenceClassification
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)
inputs = tokenizer(texts, padding=True, truncation=True, return_tensors="pt", max_length=32) inputs["labels"] = torch.tensor(labels)
PyTorch로 배우는 텍스트 딥러닝

BERT 미세 조정

optimizer = torch.optim.AdamW(model.parameters(), lr=0.00001)
model.train()

for epoch in range(1): outputs = model(**inputs)
loss = outputs.loss loss.backward()
optimizer.step() optimizer.zero_grad()
print(f"Epoch: {epoch+1}, Loss: {loss.item()}")
Epoch: 1, Loss: 0.7061821222305298
PyTorch로 배우는 텍스트 딥러닝

새 텍스트 평가

text = "I had an awesome day!"
input_eval = tokenizer(text, return_tensors="pt", truncation=True, 
                       padding=True, max_length=128)

outputs_eval = model(**input_eval)
predictions = torch.nn.functional.softmax(outputs_eval.logits, dim=-1)
predicted_label = 'positive' if torch.argmax(predictions) > 0 else 'negative' print(f"Text: {text}\nSentiment: {predicted_label}")
Text: I had an awesome day!
Sentiment: positive
PyTorch로 배우는 텍스트 딥러닝

Lass uns üben!

PyTorch로 배우는 텍스트 딥러닝

Preparing Video For Download...