자연어 처리에서 사용하는 대표적인 딥러닝 모델
DNN (Deep Neural Network)
가장 기본적인 딥러닝 모델 여러개의 은닉층을 가진 인공신경망, 여러층을 거쳐 특징을 추출한 후 결과를 예측한다. NLP에서 문장을 벡터로 변환한뒤 분류하는데 많이 사용된다.
import torch
import torch.nn as nn
class DNN(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Sequential(
nn.Linear(100, 64),
nn.ReLU(),
nn.Linear(64,32),
nn.ReLU(),
nn.Linear(32,2)
)
def forward(self,x):
return self.fc(x)
model = DNN()
x = torch.randn(5,100)
print(model(x))
https://standout.tistory.com/1537
딥러닝: Deep Neural Network (DNN), Convolutional Neural Network (CNN), Recurrent Neural Network (RNN)
딥러닝 (Deep Learning)이미지 인식, 자연어 처리, 음성 인식 등인공 신경망을 여러 층(layer)으로 쌓아서 구성한 모델다층 구조로 인해 복잡한 데이터 패턴을 자동으로 학습특성 추출
standout.tistory.com
CNN (Convolutional Neural Network)
합성곱, 이미치 처리를 위한 모델이지만 NLP에도 많이 사용된다 .문장에서 n-gram특징을 추출하는 역할을 한다.
빠르고 병렬처리가 가능하지만 긴 문맥을 이해하기 어렵다.
import torch
import torch.nn as nn
conv = nn.Conv1d(
in_channels=100,
out_channels=128,
kernel_size=3
)
x = torch.randn(32,100,50)
y = conv(x)
print(y.shape)
https://standout.tistory.com/1744
CNN 이란?: CNN Concolutional Neural Network 합성곱 신경망, 이미지의 특징을 자동으로 찾자!
CNN Concolutional Neural Network 합성곱 신경망이미지, 영상, 패턴인식에 사용된다. 기존 신경망은 이미지 처리에 비효율적이었다 .고양이 사진을 숫자로 펼치면 수십만개 픽셀이 되고 일반신경망은 파
standout.tistory.com
RNN (Recurrent Neural Network)
문장을 순서대로 읽는다. 긴 문장을 잘 기억하지못하고 이를 vanishing gradient 문제라고 한다.
import torch
import torch.nn as nn
rnn = nn.RNN(
input_size=100,
hidden_size=64,
batch_first=True
)
x = torch.randn(32,20,100)
output, hidden = rnn(x)
print(output.shape)
https://standout.tistory.com/1537
딥러닝: Deep Neural Network (DNN), Convolutional Neural Network (CNN), Recurrent Neural Network (RNN)
딥러닝 (Deep Learning)이미지 인식, 자연어 처리, 음성 인식 등인공 신경망을 여러 층(layer)으로 쌓아서 구성한 모델다층 구조로 인해 복잡한 데이터 패턴을 자동으로 학습특성 추출
standout.tistory.com
LSTM (Long Short-Term Memory)
RNN을 개선한 모델. 긴 문장을 기억하기 위해 Cell State를 추가함.
Forget Gate(필요 없는 정보를 삭제), Input Gate(새로운 정보를 저장), Output Gate(출력 결정)
긴 문장을 학습 가능하다 연산량이 많다는 단점이 있다.
import torch
import torch.nn as nn
lstm = nn.LSTM(
input_size=100,
hidden_size=128,
batch_first=True
)
x = torch.randn(16,30,100)
output,(h,c)=lstm(x)
print(output.shape)
https://standout.tistory.com/1842
RNN 순환신경망의 한 종류, LSTM이란?: 장기 의존성 문제를 해결하기 위해 개발된 딥러닝 모델
LSTM(Long Short-Term Memory)RNN(Recurrent Neural Network, 순환 신경망)의 한 종류장기 의존성(Long-Term Dependency) 문제를 해결하기 위해 개발된 딥러닝 모델from tensorflow.keras.models import Sequentialfrom tensorflow.keras.laye
standout.tistory.com
GRU (Gated Recurrent Unit)
Cell State를 제거해 Gate를 2개만 사용한다. Reset Gate, Update Gate
LSTM 보다 빠르고 성능도 거의 비슷하다.
import torch
import torch.nn as nn
gru = nn.GRU(
input_size=100,
hidden_size=128,
batch_first=True
)
x = torch.randn(32,20,100)
output,h=gru(x)
print(output.shape)
https://standout.tistory.com/1842
RNN 순환신경망의 한 종류, LSTM이란?: 장기 의존성 문제를 해결하기 위해 개발된 딥러닝 모델
LSTM(Long Short-Term Memory)RNN(Recurrent Neural Network, 순환 신경망)의 한 종류장기 의존성(Long-Term Dependency) 문제를 해결하기 위해 개발된 딥러닝 모델from tensorflow.keras.models import Sequentialfrom tensorflow.keras.laye
standout.tistory.com
Seq2Seq (Sequence to Sequence)
입력을 다른 문장으로 변환하는 모델, 번역모델
Encoder가 문장을 압축하고 Decoder가 새로운 문장을 생성한다. 문장이 길어질수록 Context Vector 하나로는 부족하다는 문제점이 있다 .
import torch.nn as nn
encoder = nn.LSTM(100,256)
decoder = nn.LSTM(100,256)
print("Seq2Seq")
https://standout.tistory.com/1844
입력과 출력의 길이가 달라도 처리할 수 있는 모델 Seq2Seq , 정보 병목(Information Bottleneck) (feat. Atte
Seq2Seq (Sequence to Sequence) 입력 시퀀스(Sequence)를 다른 출력 시퀀스로 변환하는 딥러닝 모델이다. 순서가 있는 데이터를 입력받아, 또 다른 순서가 있는 데이터를 출력하는 모델주로 LSTM나 GRU기반으
standout.tistory.com
Attention
Seq2Seq 문제를 해결하기 위한 기술로 Decoder가 필요한 Encoder 정보를 선택해서 봐 긴문장이 처리가능하다.
import torch
import torch.nn.functional as F
Q=torch.randn(2,4)
K=torch.randn(3,4)
score=torch.matmul(Q,K.T)
attention=F.softmax(score,dim=1)
print(attention)
https://standout.tistory.com/1844
입력과 출력의 길이가 달라도 처리할 수 있는 모델 Seq2Seq , 정보 병목(Information Bottleneck) (feat. Atte
Seq2Seq (Sequence to Sequence) 입력 시퀀스(Sequence)를 다른 출력 시퀀스로 변환하는 딥러닝 모델이다. 순서가 있는 데이터를 입력받아, 또 다른 순서가 있는 데이터를 출력하는 모델주로 LSTM나 GRU기반으
standout.tistory.com
Transformer
RNN을 완전히 제거한 모델. Attention만 사용한다 . 논문 Attention is All You Need.
병렬처리가 가능하고 매우빠르고 긴문장을 처리할 수 있다. 메모리 사용량이 많다.
import torch
import torch.nn as nn
transformer = nn.Transformer(
d_model=512,
nhead=8,
num_encoder_layers=6,
num_decoder_layers=6
)
src = torch.rand(10,32,512)
tgt = torch.rand(20,32,512)
out = transformer(src,tgt)
print(out.shape)
https://standout.tistory.com/1846
Attention 메커니즘만을 이용하여 문장을 처리하는 딥러닝 모델 Transformer (feat.Self-Attention, Multi-Head A
Transformer란? Attention 메커니즘만을 이용하여 문장을 처리하는 딥러닝 모델기존의 RNN, LSTM, GRU는 단어를 순서대로 처리했지만, Transformer는 모든 단어를 동시에 처리(병렬 처리)할 수 있도록 설계되
standout.tistory.com
BERT (Bidirectional Encoder Representations from Transformers)
Transformer의 Encoder만 사용하는 사전학습(Pre-trained) 언어 모델
양방향(Bidirectional)으로 문맥을 이해하여 단어의 의미를 파악한다.즉 앞뒤 문맥을 모두 활용해 의미를 구분한다.
감정 분석, 문장 분류, 개체명 인식(NER), 질의응답(QA)에 사용한다.
from transformers import BertTokenizer, BertModel
# 토크나이저와 모델 불러오기
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
model = BertModel.from_pretrained("bert-base-uncased")
text = "I love natural language processing."
# 토큰화
inputs = tokenizer(text, return_tensors="pt")
# BERT 실행
outputs = model(**inputs)
print(outputs.last_hidden_state.shape)
torch.Size([1, 8, 768])
https://standout.tistory.com/1847
앞 뒤를 모두 참고하는 Bidirectional 모델 BERT ,특수 토큰 CLS와 SEP , 두가지 학습방법 MLM, NSP (feat. Tra
BERT (Bidirectional Encoder Representations from Transformers) Transformer의 Encoder만을 사용하여 문장의 의미를 양방향(Bidirectional)으로 이해하는 사전학습(Pre-trained) 언어 모델이다.https://standout.tistory.com/1846 Attenti
standout.tistory.com
GPT (Generative Pre-trained Transformer)
Transformer의 Decoder만 사용하는 사전학습 생성형 언어 모델
이전 단어들을 바탕으로 다음 단어를 예측하며 자연스러운 문장을 생성한다.
단방향(Autoregressive) 예측으로 문장 생성에 특화되어 BERT와 반대된다. 대규모 데이터 사전학습 후 다양한 생성 작업 수행한다.
챗봇, 문서작성, 코드생성, 번역, 요약에 사용된다 .
from transformers import GPT2Tokenizer, GPT2LMHeadModel
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")
prompt = "Artificial Intelligence is"
inputs = tokenizer(prompt, return_tensors="pt")
outputs = model.generate(
**inputs,
max_length=30
)
result = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(result)