텍스트 분류 개요

PyTorch로 배우는 텍스트 딥러닝

Shubham Jain

Instructor

텍스트 분류 정의

  • 텍스트에 레이블 부여
  • 단어와 문장에 의미 부여

 

 

머신러닝 분류 유형

  • 비정형 데이터를 구조화하고 체계화
  • 활용:

    • 리뷰의 고객 감성 분석
    • 이메일 스팸 탐지
    • 뉴스 기사에 주제 태그 부여
  • 유형: 이진, 다중 분류, 다중 레이블

PyTorch로 배우는 텍스트 딥러닝

이진 분류

  • 두 범주로 분류
  • 예: 이메일 스팸 탐지
  • 이메일은 '스팸' 또는 '스팸 아님'으로 분류

이진 분류

1 https://storage.googleapis.com/gweb-cloudblog-publish/images/image4_v2LFcq0.max-1200x1200.png
PyTorch로 배우는 텍스트 딥러닝

다중 분류

뉴스 분류

  • 여러 범주로 분류
  • 예: 뉴스 기사는 다음 같은 여러 범주로 분류 가능
    1. 정치
    2. 스포츠
    3. 기술
PyTorch로 배우는 텍스트 딥러닝

다중 레이블 분류

  • 각 텍스트에는 여러 레이블을 할당할 수 있음
  • 예: 은 다중 장르일 수 있음
    • 액션
    • 어드벤처
    • 판타지
PyTorch로 배우는 텍스트 딥러닝

워드 임베딩이란

워드 임베딩 파이프라인

워드 임베딩 예시

  • 이전 인코딩 기법은 좋은 시작점
    • 하지만 특성이 너무 많고 유사 단어를 구분 못함
  • 워드 임베딩은 단어를 수치 벡터로 매핑
  • 의미 관계 예:
    • king과 queen
    • man과 woman
PyTorch로 배우는 텍스트 딥러닝

단어-인덱스 매핑

  • 예:
    • "King" -> 1
    • "Queen" -> 2
  • 컴팩트하고 계산 효율적
  • 파이프라인에서 토크나이즈 다음 단계
PyTorch로 배우는 텍스트 딥러닝

PyTorch에서 워드 임베딩

  • torch.nn.Embedding:
    • 인덱스에서 단어 벡터 생성

 

  • 입력: ['The', 'cat', 'sat', 'on', 'the', 'mat']의 인덱스
Embedding for 'the': tensor([-0.4689,  0.3164, -0.2971, -0.1291,  0.4064])
Embedding for 'cat': tensor([-0.0978, -0.4764,  0.0476,  0.1044, -0.3976])
Embedding for 'sat': tensor([ 0.2731,  0.4431,  0.1275,  0.1434, -0.4721])
PyTorch로 배우는 텍스트 딥러닝

`torch.nn.Embedding` 사용하기

import torch
from torch import nn

words = ["The", "cat", "sat", "on", "the", "mat"] word_to_idx = {word: i for i, word in enumerate(words)}
inputs = torch.LongTensor([word_to_idx[w] for w in words])
embedding = nn.Embedding(num_embeddings=len(words), embedding_dim=10)
output = embedding(inputs)
print(output)
tensor([[ 1.0624,  0.6792,  0.0459,  ... -1.0828, -0.4475,  0.4868],
         ...
         [1.5766,  0.0106,  0.1161,  ...,,  -0.0859, 1.3160,  1.3621])
PyTorch로 배우는 텍스트 딥러닝

파이프라인에서 임베딩 사용

def preprocess_sentences(text):
  # Tokenization
  # Stemming
  ...

# Word to index mapping
class TextDataset(Dataset): def __init__(self, encoded_sentences): self.data = encoded_sentences def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index]
def text_processing_pipeline(text):
    tokens = preprocess_sentences(text)
    dataset = TextDataset(tokens)
    dataloader = DataLoader(dataset, batch_size=2, 
                            shuffle=True)
    return dataloader, vectorizer

text = "Your sample text here." dataloader, vectorizer = text_processing_pipeline(text)
embedding = nn.Embedding(num_embeddings=10, embedding_dim=50) for batch in dataloader: output = embedding(batch) print(output)
PyTorch로 배우는 텍스트 딥러닝

Ayo berlatih!

PyTorch로 배우는 텍스트 딥러닝

Preparing Video For Download...