greatsangho의 이야기

다시 훑어보는 Pytorch 및 자연어 처리 기초 본문

프로그래밍/SK AI 캠프

다시 훑어보는 Pytorch 및 자연어 처리 기초

greatsangho 2024. 11. 24. 23:49

파이토치 라이브러리 불러오기

import pytorch

파이토치에는 tensor라는 자료형이 있다. 텐서플로에서의 constant와 대응된다.

# 파이토치
import torch
torch.tensor([1,2,3])

# 텐서플로
import tensorflow as tf
tf.constant([1,2,3])

파이토치는 딥러닝 모델 구조를 한번에 정의할 수 있는 torch.nn.Sequential이 있다.

model = torch.nn.Sequential(
    torch.nn.Linear(10,5),
    torch.nn.ReLU(),
    torch.nn.Linear(5,2),
)

GPU 사용 여부는 torch.cuda.is_available()을 활용한다. 모델이나 텐서를 cuda에서 연산을 하도록 정할 수 있다.

device = 'cuda' if torch.cuda.is_available() else 'cpu'
tensor = tensor.to(device)

미분은 y = wx 형태의 식이 있을 때, tensor x에 대해 requires_grad = True를 설정하여 변수로 지정하고, y.backward() 단계에서 식을 미분한다. x.grad에서 x를 대입한 결과를 얻는다.

x = torch.tensor(1., requires_grad=True)
y = x * 2
y.backward()
print(x.grad)

파이토치 이미지용 라이브러리

import torchvision

파이토치 텍스트 처리용 라이브러리

import torchtext

파이토치 오디오 처리용 라이브러리

import torchaudio

 

Class를 이용한 모듈화

Class SampleModule(torch.nn.Module):
  def __init__(self):
    super(sampleModule, self).__init__()
    # 레이어 초기화
    
  def forward(self, x):
    # x에 대한 연산
    return x
    
# 레이어 적용하기
model.add_module('sampleModule', SampleModule())

 

NLP(Natural language processing)

  - Word Embedding : 단어를 벡터로 저장

    - Word2Vec

    - GloVe

Text mining

Information retrieval

RNN(LSTM, GRU), Transformer(attention module, transformer models), Self-Supervised Learning(BERT, GPT and 전이학습, 입력 단어의 일부를 가리고 이를 학습하는 과정임)

 

강력한 GPU 및 데이터가 뒷바침 되어야 가능함

 

텍스트 마이닝

  - Bag-of-Words : 새로운 단어들에 대한 사전을 만든다. 중복된 단어를 제거하고 저장함. 카테고리로 나타낼 수 있음

  - One-hot vector : 이렇게 사전에 저장한 단어에 대해 해당하는 단어는 1, 나머지는 0으로 표시함, 유클리드 거리는 sqrd(2), 내적값은 0으로 고정되어 단어간 관계가 독립적임

  - Naive Bayes Classifier : c_MAP = argmax P(c|d) = argmax( P(d|c) P(c) / P(d) ) = argmax P(d|c) P(c) 로 나타내어진다.여기서 문서 d가 클래스 c들에 속할 확률이므로 문서 d는 고정된 상태에서 이루어지므로 argmax P(d|c) P(c)와 같이 된다. P(d|c)는 c가 고정일 때 문서 d가 나타날 확률이고, d 는 단어에 대한 동시사건으로 표현이고 결과적으로 각각의 단어가 나타날 확률에 대한 클래스의 곱의 합과 같아진다.

 

RNN(Recurrent Neural Network)
  - input vector x
  - hidden state h
  - output vector y
  - time step t

  - Forward propagation
  - Backward propagation
  - Chain Rule
  - Gradient Vanishing/Exploding
  - Long-Term-Dependency

  - LSTM : Long Short-Term Memory
  - cell state vector
  - hidden state vector
  - GRU : Gated Recurrent Unit

 

Seq2Seq Model : RNN에서 many-to-many에 해당하는 모델임. 입력과 출력이 모두 출력이며, 입력을 모두 받은 후 출력을 진행함.
  - 인코더(Encoder)
  - 디코더(Decoder)
  - Attention

  - Attention score
  - Attention distribution (Attention vector)
  - Teacher forcing

 

Positional Encoding : 순서를 구별할 수 있는 유니크한 상수벡터를 더해주는 것
  - 주기함수(Sine, Cosine)

 

LLM

BERT

GPT

  - Byte pair encoding : sub word 수준의 토크나이저 사용
  - zero-shot: 아무 예시도 없이 태스크 수행
  - ont-shot: 하나의 예시를 보여주고 태스크 수행
  - few-shot: 몇 개의 예시를 보여주고 태스크 수행

ALBERT : BERT를 경량화 함

  - Factorized Embedding Parameterization : 임베팅 차원을 줄여 모델의 크기를 줄임
  - Sentence Order Prediction
  - Cross-layer Parameter Sharing : 파라미터를 공유함

ELECTRA(Efficiently Learning an Encoder that Classifies Token Replacements Accurately) : 인코더에 효율적인 학습법 적용

  - Generator: [MASK]된 토큰을 예측
  - Discriminator: 토큰별로 Generator에 의해 예측된 토큰인지 실제 단어인지를 예측

  - GAN과 유사한 방식으로 자연어를 생성하고, 토큰의 참/거짓을 판단하며 학습

 

https://dacon.io/edu/130

 

파이토치로 딥러닝 시작하기: 상

 

dacon.io

https://www.boostcourse.org/ai330

 

자연어 처리의 모든 것

부스트코스 무료 강의

www.boostcourse.org

반응형