오늘까지만 이론 바짝 공부하고 내일부터 실전으로 들어가야지!
학습시간 09:00~03:00(당일18H/누적1165H)
키워드 요약
| 모델명 | 핵심 아이디어 | 주요 특징 | 장점 | 단점 |
|---|---|---|---|---|
| Word2Vec | 주변 단어를 통해 단어를 예측 (예측 기반) | CBOW, Skip-gram, Negative Sampling | 단어 간 의미적/문법적 관계 표현 우수, 비교적 빠른 학습 | OOV 문제, 단어를 원자 단위로 취급 |
| FastText | 단어를 문자 n-gram의 합으로 표현 | Subword information | OOV 및 희귀 단어 처리 가능, 형태소 정보 반영 | 모델 크기가 큼, 계산 비용 증가 |
| GloVe | 전체 말뭉치의 단어 동시 등장 통계 활용 (카운트 기반) | Co-occurrence Matrix, 목적 함수 | 전체 통계 정보를 활용하여 학습이 빠름, 단어 유추 성능 우수 | OOV 문제, 동시 등장 행렬의 메모리 부담 |
| Vanilla RNN | 이전 시점의 출력을 현재 시점의 입력으로 사용 (순환 구조) | Hidden State () | 구조가 간단함, 기본적인 시퀀스 패턴 학습 가능 | 장기 의존성 문제 (그래디언트 소실/폭주) |
| LSTM | 셀 상태와 3개의 게이트(Forget, Input, Output)로 정보 흐름 제어 | Cell State, Forget/Input/Output Gates | 장기 의존성 문제 해결, 복잡한 시퀀스 패턴 학습 | 구조 복잡, 파라미터 수 많음, 계산 비용 높음 |
| GRU | LSTM을 간소화한 모델. 2개의 게이트(Reset, Update) 사용 | Reset Gate, Update Gate | LSTM보다 파라미터가 적고 계산 효율이 높음, 대등한 성능 | LSTM보다 정교한 제어는 어려움 |

A. 핵심 구조
[the, cat, __, on, the, mat]에서 sat을 예측.sat을 통해 [the, cat, on, the, mat]을 예측.B. 학습 최적화 기법
C. 특징
D. 코드 예시
from gensim.models import Word2Vec
sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
['this', 'is', 'the', 'second', 'sentence'],
['yet', 'another', 'sentence'],
['one', 'more', 'sentence'],
['and', 'the', 'final', 'sentence']]
model = Word2Vec(sentences, vector_size=100, window=5, min_count=1, workers=4, sg=1)
vector = model.wv['sentence']
print(vector)
similar_words = model.wv.most_similar('sentence', topn=3)
print(similar_words)

A. 핵심 구조
apple이라는 단어를 3-gram으로 분해하면 <ap, app, ppl, ple, le> 와 같은 부분 문자열로 구성됨. ( <와 >는 단어의 시작과 끝을 표시)B. 특징
running, runner는 run이라는 n-gram을 공유).C. 코드 예시
from gensim.models import FastText
sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'fasttext'],
['this', 'is', 'the', 'second', 'sentence'],
['yet', 'another', 'sentence'],
['one', 'more', 'sentence'],
['and', 'the', 'final', 'sentence']]
model = FastText(sentences, vector_size=100, window=5, min_count=1, workers=4, sg=1)
vector = model.wv['sentence']
print(vector)
oov_vector = model.wv['fasttextual']
print(oov_vector)

A. 핵심 구조
B. 특징
C. 코드 예시
# Pre-trained GloVe 로딩
import torch
import torchtext.vocab as vocab
glove = vocab.GloVe(name='6B', dim=100)
vector = glove.get_vecs_by_tokens(['king', 'man', 'woman'], lower_case_except_case_sensitive=True)
king_vec, man_vec, woman_vec = vector[0], vector[1], vector[2]
queen_vec = king_vec - man_vec + woman_vec
cos = torch.nn.CosineSimilarity(dim=0)
similarities = []
for i, token in enumerate(glove.itos):
if i % 10000 == 0:
print(f"Processing... {i}/{len(glove.itos)}")
token_vec = glove.vectors[i]
similarity = cos(queen_vec, token_vec)
similarities.append((token, similarity.item()))
similarities.sort(key=lambda x: x[1], reverse=True)
print(similarities[:5])

A. 핵심 구조
B. 특징
C. 코드 예시
import torch
import torch.nn as nn
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class VanillaRNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(VanillaRNN, self).__init__()
self.hidden_size = hidden_size
self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(1, x.size(0), self.hidden_size).to(x.device)
out, _ = self.rnn(x, h0)
out = self.fc(out[:, -1, :])
return out
input_size = 10
hidden_size = 20
output_size = 5
seq_length = 15
batch_size = 3
model = VanillaRNN(input_size, hidden_size, output_size).to(device)
input_tensor = torch.randn(batch_size, seq_length, input_size).to(device)
output = model(input_tensor)
print(output.shape)

A. 핵심 구조
B. 정보 흐름
C. 특징
D. 코드 예시
import torch
import torch.nn as nn
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class LSTMModel(nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_layers):
super(LSTMModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
out, _ = self.lstm(x, (h0, c0))
out = self.fc(out[:, -1, :])
return out
input_size = 10
hidden_size = 20
output_size = 5
num_layers = 2
seq_length = 15
batch_size = 3
model = LSTMModel(input_size, hidden_size, output_size, num_layers).to(device)
input_tensor = torch.randn(batch_size, seq_length, input_size).to(device)
output = model(input_tensor)
print(output.shape)

A. 핵심 구조
B. 정보 흐름
C. 특징
D. 코드 예시
import torch
import torch.nn as nn
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class GRUModel(nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_layers):
super(GRUModel, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.gru = nn.GRU(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device)
out, _ = self.gru(x, h0)
out = self.fc(out[:, -1, :])
return out
input_size = 10
hidden_size = 20
output_size = 5
num_layers = 2
seq_length = 15
batch_size = 3
model = GRUModel(input_size, hidden_size, output_size, num_layers).to(device)
input_tensor = torch.randn(batch_size, seq_length, input_size).to(device)
output = model(input_tensor)
print(output.shape)