SlideShare uma empresa Scribd logo
1 de 38
Baixar para ler offline
빠르게구현하는RNN
18.06.24 김보섭
Contents
Intro
Many to One
Many to Many
Seq2Seq
QnA
2
Intro
진행하기전에.....
슬라이드의 모든 code snippets은 아래의 링크로 다운 받
거나, 아래의 사이트에서 보시면 됩니다.
Download :
http://tagme.to/aisolab/To_quickly_implementin
g_RNN
Click : To quickly implementing RNN.ipynb
3
Intro
먼저 Recurrent Neural Networks의 이론은 알고 있다
고 가정, api를 사용하는 법만 살펴봄
모든 상황은 variable sequence length를 가정, 예를 들
면 아래와 같이..
# 문장의 단어를 RNN에 하나하나씩 넣는다고 하면?
# RNN은 아래처럼 각 문장 별로 단어의 개수만큼 sequence를 처리해야한다.
sentences = [['I', 'feel', 'hungry'],
['tensorflow', 'is', 'very', 'difficult'],
['tensorflow', 'is', 'a', 'framework',
'for','deep','learning'],
['tensorflow', 'is', 'very',
'fast', 'changing']]
4
Intro : Padding
tensor ow에서 variable sequence length를 다루기
위해서는 일단 적당한 길이로 padding을 해야함
왜냐하면 eager mode를 활용하지않는 이상 tensor ow
는 정적인 framework이기 때문
padding을 위한 tensor ow graph를 정의하거나,
python 함수를 정의하여 활용
padding시 적당한 최대 길이를 정해줄 것
5
Intro : Padding
# word dic
word_list = []
for elm in sentences:
word_list += elm
word_list = list(set(word_list))
word_list.sort()
# '<pad>'라는 의미없는 token 추가
word_list = ['<pad>'] + word_list
word_dic = {word : idx for idx,
word in enumerate(word_list)}
6
Intro : Padding
# max_len의 길이에 못미치는 문장은 <pad>로 max_len만큼 padding
def pad_seq(sequences, max_len, dic):
seq_len, seq_indices = [], []
for seq in sequences:
seq_len.append(len(seq))
seq_idx = [dic.get(char) for char in seq]
# 0 is idx of meaningless token "<pad>"
seq_idx += (max_len - len(seq_idx)) * 
[dic.get('<pad>')]
seq_indices.append(seq_idx)
return seq_len, seq_indices
7
Intro : Padding
max_length = 8
sen_len, sen_indices = pad_seq(sequences = sentences,
max_len = max_length,
dic = word_dic)
[3, 4, 7, 5]
[[1, 7, 10, 0, 0, 0, 0, 0],
[13, 11, 14, 5, 0, 0, 0, 0],
[13, 11, 2, 9, 8, 4, 12, 0],
[13, 11, 14, 6, 3, 0, 0, 0]]
8
Intro : Look up
variable sequence를 가지는 input을 RNN의 input으
로 넣을 수 있도록 잘 padding 했는 데...
padding 한 것을 그대로 RNN의 input으로 넣는 게 맞나?
idx 별 뭔가 dense vector (eg. word2vec) 등을 사용해
야함, tf.nn.embedding_lookup을 활용하자!
tf.nn.embedding_lookup(
params,
ids,
partition_strategy='mod',
name=None,
validate_indices=True,
max_norm=None)
9
Intro : Look up
# tf.nn.embedding_lookup의 params, ids arg에 전달하기위한
# placeholder 선언
seq_len = tf.placeholder(dtype = tf.int32, shape = [None])
seq_indices = tf.placeholder(dtype = tf.int32,
shape = [None, max_length])
one_hot = np.eye(len(word_dic)) # 단어 별 one-hot encoding
# embedding vector는 training 안할 것이므로
one_hot = tf.get_variable(name='one_hot',
initializer = one_hot,
trainable = False)
seq_batch = tf.nn.embedding_lookup(params = one_hot,
ids = seq_indices)
10
Intro : Look up
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
tmp = sess.run(seq_batch,
feed_dict = {seq_indices : sen_indices})
print(np.shape(sen_indices))
print(np.shape(tmp))
(4, 8)
(4, 8, 15)
# tf.nn.dynamic_rnn, tf.contrib.seq2seq.TrainingHelper 등에
# 이 shape을 유지하면서 전달되어야함
11
Many to One
eg. 영어 문장의 긍/부정을 평가하는 RNN (with GRU)
Example data
sentences = [['I', 'feel', 'hungry'],
['tensorflow', 'is', 'very', 'difficult'],
['tensorflow', 'is', 'a', 'framework', 'for',
'deep', 'learning'],
['tensorflow', 'is', 'very', 'fast',
'changing']]
label = [[0.,1.], [0.,1.], [1.,0.], [1.,0.]]
13
Example data
sentences의 word들의 idx를 가지고 있는 dictionary
생성
# word dic
word_list = []
for elm in sentences:
word_list += elm
word_list = list(set(word_list))
word_list.sort()
# '<pad>'라는 의미없는 token 추가
word_list = ['<pad>'] + word_list
word_dic = {word : idx for idx,
word in enumerate(word_list)}
14
Example data
dictionary를 이용하여 다음과 같이 전처리
[3, 4, 7, 5]
[[1, 7, 10, 0, 0, 0, 0, 0],
[13, 11, 14, 5, 0, 0, 0, 0],
[13, 11, 2, 9, 8, 4, 12, 0],
[13, 11, 14, 6, 3, 0, 0, 0]]
max_length = 8
sen_len, sen_indices = pad_seq(sequences = sentences, max_len =
dic = word_dic)
pprint(sen_len)
pprint(sen_indices)
15
Simple
tf.nn.dynamic_rnn
cell을 돌릴 때 활용, return 값 중 state만을 활용
sequence_length에 padding 하기전 문장의 길이를 넣어주면 알아서 원 문장
의 sequence만큼 처리
tf.losses.softmax_cross_entropy
일반적인 NN의 loss와 동일
tf.nn.dynamic_rnn(cell, inputs,
sequence_length=None, initial_state=None,
dtype=None, parallel_iterations=None,
swap_memory=False, time_major=False,
scope=None)
16
Stacked
tf.contrib.rnn.MultiRNNCell
Stacking을 위해 활용
tf.contrib.rnn.DropoutWrapper
layer가 깊어지므로, Over tting 방지를 위해 활용
tf.contrib.rnn.MultiRNNCell(cells,
state_is_tuple=True)
17
Bi-directional
tf.nn.bidirectional_dynamic_rnn
fw_cell과 bw_cell을 돌릴 때 활용, return 값 중 output_states만을 활용,
output_states는 fw_cell과 bw_cell의 nal state 값을 갖고 있어서, loss
계산 시 둘을 concatenate해서 활용
tf.nn.bidirectional_dynamic_rnn(cell_fw, cell_bw,
inputs, sequence_length=None,
initial_state_fw=None, initial_state_bw=None,
dtype=None, parallel_iterations=None,
swap_memory=False, time_major=False, scope=None)
18
Stacked Bi-directional
tf.contrib.rnn.stack_bidirectional_dynamic_rnn
각각의 fw_cells, bw_cells (list 형태)를 돌릴 때 활용
return 값 중 output_state_fw, output_state_bw를 concatenate해서 활
용
tf.contrib.rnn.stack_bidirectional_dynamic_rnn(
cells_fw, cells_bw,
inputs, initial_states_fw=None,
initial_states_bw=None, dtype=None,
sequence_length=None,
parallel_iterations=None,
time_major=False,
scope=None)
19
Many to Many
eg. 형태소 분석을 하는 RNN (with GRU)
Example data
sentences = [['I', 'feel', 'hungry'],
['tensorflow', 'is', 'very', 'difficult'],
['tensorflow', 'is', 'a', 'framework', 'for',
'deep', 'learning'],
['tensorflow', 'is', 'very', 'fast',
'changing']]
pos = [['pronoun', 'verb', 'adjective'],
['noun', 'verb', 'adverb', 'adjective'],
['noun', 'verb', 'determiner', 'noun',
'preposition', 'adjective', 'noun'],
['noun', 'verb', 'adverb', 'adjective', 'verb']]
21
Example data
sentences의word들의idx를가지고있는dictionary
생성
pos의 token들의 idx를 가지고 있는 dictionary 생성
# word dic
word_list = []
for elm in sentences:
word_list += elm
word_list = list(set(word_list))
word_list.sort()
word_list = ['<pad>'] + word_list
word_dic = {word : idx for idx, word
in enumerate(word_list)}
22
Example data
sentences의 word들의 idx를 가지고 있는 dictionary
생성
pos의token들의idx를가지고있는dictionary 생성
# pos dic
pos_list = []
for elm in pos:
pos_list += elm
pos_list = list(set(pos_list))
pos_list.sort()
pos_list = ['<pad>'] + pos_list
pos_dic = {pos : idx for idx, pos in enumerate(pos_list)}
23
Example data
dictionary를 이용하여 다음과 같이 전처리
sen_len, sen_indices = pad_seq(sequences = sentences,
max_len = max_length,
dic = word_dic)
_, pos_indices = pad_seq(sequences = pos,
max_len = max_length,
dic = pos_dic)
24
Example data
dictionary를 이용하여 다음과 같이 전처리
pprint(sen_len)
pprint(sen_indices)
[3, 4, 7, 5]
[[1, 7, 10, 0, 0, 0, 0, 0],
[13, 11, 14, 5, 0, 0, 0, 0],
[13, 11, 2, 9, 8, 4, 12, 0],
[13, 11, 14, 6, 3, 0, 0, 0]]
25
Example data
dictionary를 이용하여 다음과 같이 전처리
pprint(pos_indices)
[[6, 7, 1, 0, 0, 0, 0, 0],
[4, 7, 2, 1, 0, 0, 0, 0],
[4, 7, 3, 4, 5, 1, 4, 0],
[4, 7, 2, 1, 7, 0, 0, 0]]
26
Simple
Cell을 사용하는 방식은 Many to One 위 Case와 동일
단 tf.nn.dynamic_rnn의 return 값중 outputs을 활용
tf.contrib.rnn.OutputProjectionWrapper
step마다 classify를 하기위해 활용
tf.sequence_mask
원래 sequence에 대해서만 loss를 계산하기위해 활용
tf.contrib.seq2seq.sequence_loss
tf.sequence_mask의 output을 weights arg에 전달 받음
targets arg에 [None, sequence_length]의 label 전달
27
Stacked
Cell을 사용하는 방식은 Many to One 위 Case와 동일
단 tf.nn.dynamic_rnn의 return 값중 outputs을 활용
tf.contrib.rnn.OutputProjectionWrapper
step마다 classify를 하기위해 활용
tf.sequence_mask
원래 sequence에 대해서만 loss를 계산하기위해 활용
tf.contrib.seq2seq.sequence_loss
tf.sequence_mask의 output을 weights arg에 전달 받음
targets arg에 [None, sequence_length]의 label 전달
28
Bi-directional
Cell을 사용하는 방식은 Many to One 위 Case와 동일
단 tf.nn.bidirectional_dynamic_rnn의 return 값중 outputs을 활용
tf.map_fn
step마다 classify를 하기위해 활용
tf.sequence_mask
원래 sequence에 대해서만 loss를 계산하기위해 활용
tf.contrib.seq2seq.sequence_loss
tf.sequence_mask의 output을 weights arg에 전달 받음
targets arg에 [None, sequence_length]의 label 전달
29
Stacked Bi-directional
Cell을 사용하는 방식은 Many to One 위 Case와 동일
단 tf.contrib.rnn.stack_bidirectional_dynamic_rnn의 return 값중
outputs을 활용
tf.map_fn
step마다 classify를 하기위해 활용
tf.sequence_mask
원래 sequence에 대해서만 loss를 계산하기위해 활용
tf.contrib.seq2seq.sequence_loss
tf.sequence_mask의 output을 weights arg에 전달 받음
targets arg에 [None, sequence_length]의 label 전달
30
Seq2Seq
eg. 문장을 번역하는 RNN (with GRU)
Example data
targets = [['나는', '배가', '고프다'],
['텐서플로우는', '매우', '어렵다'],
['텐서플로우는', '딥러닝을', '위한', '프레임워크이다'],
['텐서플로우는', '매우', '빠르게', '변화한다']]
sources = [['I', 'feel', 'hungry'],
['tensorflow', 'is', 'very', 'difficult'],
['tensorflow', 'is', 'a', 'framework', 'for', 'deep',
['tensorflow', 'is', 'very', 'fast', 'changing']]
32
Example data
sources의word들의idx를가지고있는dictionary 생
성
targets의 word들의 idx를 가지고 있는 dictionary 생성
# word dic for sentences
source_words = []
for elm in sources:
source_words += elm
source_words = list(set(source_words))
source_words.sort()
source_words = ['<pad>'] + source_words
source_dic = {word : idx for idx, word
in enumerate(source_words)}
33
Example data
sources의 word들의 idx를 가지고 있는 dictionary 생성
targets의word들의idx를가지고있는dictionary 생
성
# word dic for translations
target_words = []
for elm in targets:
target_words += elm
target_words = list(set(target_words))
target_words.sort()
# 번역문의 시작과 끝을 알리는 'start', 'end' token 추가
target_words = ['<pad>']+ ['<start>'] + ['<end>'] + 
target_words
target_dic = {word : idx for idx, word
in enumerate(target_words)} 34
바로코드로...
QnA
Reference
https://github.com/aisolab/CS20
https://github.com/HiJiGOO/tf_nmt_tutorial
https://github.com/hccho2/RNN-Tutorial
https://www.tensor ow.org/tutorials/seq2seq
https://github.com/golbin/TensorFlow-
Tutorials/blob/master/10 - RNN/03 - Seq2Seq.py
들어주셔서감사합니다.
  Github : github.com/aisolab
  Blog : aisolab.github.io
  E-mail : bsk0130@gmail.com

Mais conteúdo relacionado

Mais procurados

Chapter 9 - convolutional networks
Chapter 9 - convolutional networksChapter 9 - convolutional networks
Chapter 9 - convolutional networksKyeongUkJang
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기Jongwook Choi
 
3.unsupervised learing(epoch#2)
3.unsupervised learing(epoch#2)3.unsupervised learing(epoch#2)
3.unsupervised learing(epoch#2)Haesun Park
 
python 수학이해하기
python 수학이해하기python 수학이해하기
python 수학이해하기Yong Joon Moon
 
Python Sympy 모듈 이해하기
Python Sympy 모듈 이해하기Python Sympy 모듈 이해하기
Python Sympy 모듈 이해하기Yong Joon Moon
 
Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Yong Joon Moon
 
4.representing data and engineering features
4.representing data and engineering features4.representing data and engineering features
4.representing data and engineering featuresHaesun Park
 
게임프로그래밍입문 3주차
게임프로그래밍입문 3주차게임프로그래밍입문 3주차
게임프로그래밍입문 3주차Yeonah Ki
 
게임프로그래밍입문 5주차
게임프로그래밍입문 5주차게임프로그래밍입문 5주차
게임프로그래밍입문 5주차Yeonah Ki
 
2.supervised learning
2.supervised learning2.supervised learning
2.supervised learningHaesun Park
 
Energy based models and boltzmann machines - v2.0
Energy based models and boltzmann machines - v2.0Energy based models and boltzmann machines - v2.0
Energy based models and boltzmann machines - v2.0Soowan Lee
 
게임프로그래밍입문 4주차
게임프로그래밍입문 4주차게임프로그래밍입문 4주차
게임프로그래밍입문 4주차Yeonah Ki
 
자바 스터디(6기) 1
자바 스터디(6기) 1자바 스터디(6기) 1
자바 스터디(6기) 1Jina Lee
 
4.representing data and engineering features(epoch#2)
4.representing data and engineering features(epoch#2)4.representing data and engineering features(epoch#2)
4.representing data and engineering features(epoch#2)Haesun Park
 
6장 표현식 및 문장
6장 표현식 및 문장6장 표현식 및 문장
6장 표현식 및 문장재정 이
 
파이썬 문자열 이해하기
파이썬 문자열 이해하기파이썬 문자열 이해하기
파이썬 문자열 이해하기Yong Joon Moon
 
사이킷런 최신 변경 사항 스터디
사이킷런 최신 변경 사항 스터디사이킷런 최신 변경 사항 스터디
사이킷런 최신 변경 사항 스터디Haesun Park
 
스칼라와 스파크 영혼의 듀오
스칼라와 스파크 영혼의 듀오스칼라와 스파크 영혼의 듀오
스칼라와 스파크 영혼의 듀오Taeoh Kim
 
2.supervised learning(epoch#2)-1
2.supervised learning(epoch#2)-12.supervised learning(epoch#2)-1
2.supervised learning(epoch#2)-1Haesun Park
 

Mais procurados (20)

Chapter 9 - convolutional networks
Chapter 9 - convolutional networksChapter 9 - convolutional networks
Chapter 9 - convolutional networks
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기
 
3.unsupervised learing(epoch#2)
3.unsupervised learing(epoch#2)3.unsupervised learing(epoch#2)
3.unsupervised learing(epoch#2)
 
python 수학이해하기
python 수학이해하기python 수학이해하기
python 수학이해하기
 
Python Sympy 모듈 이해하기
Python Sympy 모듈 이해하기Python Sympy 모듈 이해하기
Python Sympy 모듈 이해하기
 
Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815
 
4.representing data and engineering features
4.representing data and engineering features4.representing data and engineering features
4.representing data and engineering features
 
게임프로그래밍입문 3주차
게임프로그래밍입문 3주차게임프로그래밍입문 3주차
게임프로그래밍입문 3주차
 
게임프로그래밍입문 5주차
게임프로그래밍입문 5주차게임프로그래밍입문 5주차
게임프로그래밍입문 5주차
 
2.supervised learning
2.supervised learning2.supervised learning
2.supervised learning
 
Energy based models and boltzmann machines - v2.0
Energy based models and boltzmann machines - v2.0Energy based models and boltzmann machines - v2.0
Energy based models and boltzmann machines - v2.0
 
게임프로그래밍입문 4주차
게임프로그래밍입문 4주차게임프로그래밍입문 4주차
게임프로그래밍입문 4주차
 
자바 스터디(6기) 1
자바 스터디(6기) 1자바 스터디(6기) 1
자바 스터디(6기) 1
 
What’s new in c++11
What’s new in c++11What’s new in c++11
What’s new in c++11
 
4.representing data and engineering features(epoch#2)
4.representing data and engineering features(epoch#2)4.representing data and engineering features(epoch#2)
4.representing data and engineering features(epoch#2)
 
6장 표현식 및 문장
6장 표현식 및 문장6장 표현식 및 문장
6장 표현식 및 문장
 
파이썬 문자열 이해하기
파이썬 문자열 이해하기파이썬 문자열 이해하기
파이썬 문자열 이해하기
 
사이킷런 최신 변경 사항 스터디
사이킷런 최신 변경 사항 스터디사이킷런 최신 변경 사항 스터디
사이킷런 최신 변경 사항 스터디
 
스칼라와 스파크 영혼의 듀오
스칼라와 스파크 영혼의 듀오스칼라와 스파크 영혼의 듀오
스칼라와 스파크 영혼의 듀오
 
2.supervised learning(epoch#2)-1
2.supervised learning(epoch#2)-12.supervised learning(epoch#2)-1
2.supervised learning(epoch#2)-1
 

Semelhante a To quickly implementing RNN

Deep learningwithkeras ch3_1
Deep learningwithkeras ch3_1Deep learningwithkeras ch3_1
Deep learningwithkeras ch3_1PartPrime
 
텐서플로우 기초 이해하기
텐서플로우 기초 이해하기 텐서플로우 기초 이해하기
텐서플로우 기초 이해하기 Yong Joon Moon
 
생체 광학 데이터 분석 AI 경진대회 1위 수상작
생체 광학 데이터 분석 AI 경진대회 1위 수상작생체 광학 데이터 분석 AI 경진대회 1위 수상작
생체 광학 데이터 분석 AI 경진대회 1위 수상작DACON AI 데이콘
 
딥러닝을 위한 Tensor flow(skt academy)
딥러닝을 위한 Tensor flow(skt academy)딥러닝을 위한 Tensor flow(skt academy)
딥러닝을 위한 Tensor flow(skt academy)Tae Young Lee
 
Adversarial Attack in Neural Machine Translation
Adversarial Attack in Neural Machine TranslationAdversarial Attack in Neural Machine Translation
Adversarial Attack in Neural Machine TranslationHyunKyu Jeon
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initializationEunjoo Im
 
딥러닝 기본 원리의 이해
딥러닝 기본 원리의 이해딥러닝 기본 원리의 이해
딥러닝 기본 원리의 이해Hee Won Park
 
파이썬을 활용한 챗봇 서비스 개발 3일차
파이썬을 활용한 챗봇 서비스 개발 3일차파이썬을 활용한 챗봇 서비스 개발 3일차
파이썬을 활용한 챗봇 서비스 개발 3일차Taekyung Han
 
이정근_project_로봇비전시스템.pdf
이정근_project_로봇비전시스템.pdf이정근_project_로봇비전시스템.pdf
이정근_project_로봇비전시스템.pdftangtang1026
 
Chapter 10 sequence modeling recurrent and recursive nets
Chapter 10 sequence modeling recurrent and recursive netsChapter 10 sequence modeling recurrent and recursive nets
Chapter 10 sequence modeling recurrent and recursive netsKyeongUkJang
 
이펙티브 C++ (7~9)
이펙티브 C++ (7~9)이펙티브 C++ (7~9)
이펙티브 C++ (7~9)익성 조
 
Ml for 정형데이터
Ml for 정형데이터Ml for 정형데이터
Ml for 정형데이터JEEHYUN PAIK
 
파이썬 스터디 2주차
파이썬 스터디 2주차파이썬 스터디 2주차
파이썬 스터디 2주차Han Sung Kim
 
Deep Learning from scratch 5장 : backpropagation
 Deep Learning from scratch 5장 : backpropagation Deep Learning from scratch 5장 : backpropagation
Deep Learning from scratch 5장 : backpropagationJinSooKim80
 
개발자를 위한 공감세미나 tensor-flow
개발자를 위한 공감세미나 tensor-flow개발자를 위한 공감세미나 tensor-flow
개발자를 위한 공감세미나 tensor-flow양 한빛
 
2.supervised learning(epoch#2)-3
2.supervised learning(epoch#2)-32.supervised learning(epoch#2)-3
2.supervised learning(epoch#2)-3Haesun Park
 
Python3 brief summary
Python3 brief summaryPython3 brief summary
Python3 brief summaryHoChul Shin
 
JMI Techtalk: 강재욱 - Toward tf.keras from tf.estimator - From TensorFlow 2.0 p...
JMI Techtalk: 강재욱 - Toward tf.keras from tf.estimator - From TensorFlow 2.0 p...JMI Techtalk: 강재욱 - Toward tf.keras from tf.estimator - From TensorFlow 2.0 p...
JMI Techtalk: 강재욱 - Toward tf.keras from tf.estimator - From TensorFlow 2.0 p...Lablup Inc.
 

Semelhante a To quickly implementing RNN (20)

Deep learningwithkeras ch3_1
Deep learningwithkeras ch3_1Deep learningwithkeras ch3_1
Deep learningwithkeras ch3_1
 
텐서플로우 기초 이해하기
텐서플로우 기초 이해하기 텐서플로우 기초 이해하기
텐서플로우 기초 이해하기
 
생체 광학 데이터 분석 AI 경진대회 1위 수상작
생체 광학 데이터 분석 AI 경진대회 1위 수상작생체 광학 데이터 분석 AI 경진대회 1위 수상작
생체 광학 데이터 분석 AI 경진대회 1위 수상작
 
딥러닝을 위한 Tensor flow(skt academy)
딥러닝을 위한 Tensor flow(skt academy)딥러닝을 위한 Tensor flow(skt academy)
딥러닝을 위한 Tensor flow(skt academy)
 
Openface
OpenfaceOpenface
Openface
 
Adversarial Attack in Neural Machine Translation
Adversarial Attack in Neural Machine TranslationAdversarial Attack in Neural Machine Translation
Adversarial Attack in Neural Machine Translation
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initialization
 
딥러닝 기본 원리의 이해
딥러닝 기본 원리의 이해딥러닝 기본 원리의 이해
딥러닝 기본 원리의 이해
 
Openface
OpenfaceOpenface
Openface
 
파이썬을 활용한 챗봇 서비스 개발 3일차
파이썬을 활용한 챗봇 서비스 개발 3일차파이썬을 활용한 챗봇 서비스 개발 3일차
파이썬을 활용한 챗봇 서비스 개발 3일차
 
이정근_project_로봇비전시스템.pdf
이정근_project_로봇비전시스템.pdf이정근_project_로봇비전시스템.pdf
이정근_project_로봇비전시스템.pdf
 
Chapter 10 sequence modeling recurrent and recursive nets
Chapter 10 sequence modeling recurrent and recursive netsChapter 10 sequence modeling recurrent and recursive nets
Chapter 10 sequence modeling recurrent and recursive nets
 
이펙티브 C++ (7~9)
이펙티브 C++ (7~9)이펙티브 C++ (7~9)
이펙티브 C++ (7~9)
 
Ml for 정형데이터
Ml for 정형데이터Ml for 정형데이터
Ml for 정형데이터
 
파이썬 스터디 2주차
파이썬 스터디 2주차파이썬 스터디 2주차
파이썬 스터디 2주차
 
Deep Learning from scratch 5장 : backpropagation
 Deep Learning from scratch 5장 : backpropagation Deep Learning from scratch 5장 : backpropagation
Deep Learning from scratch 5장 : backpropagation
 
개발자를 위한 공감세미나 tensor-flow
개발자를 위한 공감세미나 tensor-flow개발자를 위한 공감세미나 tensor-flow
개발자를 위한 공감세미나 tensor-flow
 
2.supervised learning(epoch#2)-3
2.supervised learning(epoch#2)-32.supervised learning(epoch#2)-3
2.supervised learning(epoch#2)-3
 
Python3 brief summary
Python3 brief summaryPython3 brief summary
Python3 brief summary
 
JMI Techtalk: 강재욱 - Toward tf.keras from tf.estimator - From TensorFlow 2.0 p...
JMI Techtalk: 강재욱 - Toward tf.keras from tf.estimator - From TensorFlow 2.0 p...JMI Techtalk: 강재욱 - Toward tf.keras from tf.estimator - From TensorFlow 2.0 p...
JMI Techtalk: 강재욱 - Toward tf.keras from tf.estimator - From TensorFlow 2.0 p...
 

Último

JMP가 걸어온 여정, 새로운 도약 JMP 18!
JMP가 걸어온 여정, 새로운 도약 JMP 18!JMP가 걸어온 여정, 새로운 도약 JMP 18!
JMP가 걸어온 여정, 새로운 도약 JMP 18!JMP Korea
 
JMP 기능의 확장 및 내재화의 핵심 JMP-Python 소개
JMP 기능의 확장 및 내재화의 핵심 JMP-Python 소개JMP 기능의 확장 및 내재화의 핵심 JMP-Python 소개
JMP 기능의 확장 및 내재화의 핵심 JMP-Python 소개JMP Korea
 
(독서광) 인간이 초대한 대형 참사 - 대형 참사가 일어날 때까지 사람들은 무엇을 하고 있었는가?
(독서광) 인간이 초대한 대형 참사 - 대형 참사가 일어날 때까지 사람들은 무엇을 하고 있었는가?(독서광) 인간이 초대한 대형 참사 - 대형 참사가 일어날 때까지 사람들은 무엇을 하고 있었는가?
(독서광) 인간이 초대한 대형 참사 - 대형 참사가 일어날 때까지 사람들은 무엇을 하고 있었는가?Jay Park
 
실험 설계의 평가 방법: Custom Design을 중심으로 반응인자 최적화 및 Criteria 해석
실험 설계의 평가 방법: Custom Design을 중심으로 반응인자 최적화 및 Criteria 해석실험 설계의 평가 방법: Custom Design을 중심으로 반응인자 최적화 및 Criteria 해석
실험 설계의 평가 방법: Custom Design을 중심으로 반응인자 최적화 및 Criteria 해석JMP Korea
 
JMP를 활용한 전자/반도체 산업 Yield Enhancement Methodology
JMP를 활용한 전자/반도체 산업 Yield Enhancement MethodologyJMP를 활용한 전자/반도체 산업 Yield Enhancement Methodology
JMP를 활용한 전자/반도체 산업 Yield Enhancement MethodologyJMP Korea
 
JMP를 활용한 가속열화 분석 사례
JMP를 활용한 가속열화 분석 사례JMP를 활용한 가속열화 분석 사례
JMP를 활용한 가속열화 분석 사례JMP Korea
 
데이터 분석 문제 해결을 위한 나의 JMP 활용법
데이터 분석 문제 해결을 위한 나의 JMP 활용법데이터 분석 문제 해결을 위한 나의 JMP 활용법
데이터 분석 문제 해결을 위한 나의 JMP 활용법JMP Korea
 
공학 관점에서 바라본 JMP 머신러닝 최적화
공학 관점에서 바라본 JMP 머신러닝 최적화공학 관점에서 바라본 JMP 머신러닝 최적화
공학 관점에서 바라본 JMP 머신러닝 최적화JMP Korea
 

Último (8)

JMP가 걸어온 여정, 새로운 도약 JMP 18!
JMP가 걸어온 여정, 새로운 도약 JMP 18!JMP가 걸어온 여정, 새로운 도약 JMP 18!
JMP가 걸어온 여정, 새로운 도약 JMP 18!
 
JMP 기능의 확장 및 내재화의 핵심 JMP-Python 소개
JMP 기능의 확장 및 내재화의 핵심 JMP-Python 소개JMP 기능의 확장 및 내재화의 핵심 JMP-Python 소개
JMP 기능의 확장 및 내재화의 핵심 JMP-Python 소개
 
(독서광) 인간이 초대한 대형 참사 - 대형 참사가 일어날 때까지 사람들은 무엇을 하고 있었는가?
(독서광) 인간이 초대한 대형 참사 - 대형 참사가 일어날 때까지 사람들은 무엇을 하고 있었는가?(독서광) 인간이 초대한 대형 참사 - 대형 참사가 일어날 때까지 사람들은 무엇을 하고 있었는가?
(독서광) 인간이 초대한 대형 참사 - 대형 참사가 일어날 때까지 사람들은 무엇을 하고 있었는가?
 
실험 설계의 평가 방법: Custom Design을 중심으로 반응인자 최적화 및 Criteria 해석
실험 설계의 평가 방법: Custom Design을 중심으로 반응인자 최적화 및 Criteria 해석실험 설계의 평가 방법: Custom Design을 중심으로 반응인자 최적화 및 Criteria 해석
실험 설계의 평가 방법: Custom Design을 중심으로 반응인자 최적화 및 Criteria 해석
 
JMP를 활용한 전자/반도체 산업 Yield Enhancement Methodology
JMP를 활용한 전자/반도체 산업 Yield Enhancement MethodologyJMP를 활용한 전자/반도체 산업 Yield Enhancement Methodology
JMP를 활용한 전자/반도체 산업 Yield Enhancement Methodology
 
JMP를 활용한 가속열화 분석 사례
JMP를 활용한 가속열화 분석 사례JMP를 활용한 가속열화 분석 사례
JMP를 활용한 가속열화 분석 사례
 
데이터 분석 문제 해결을 위한 나의 JMP 활용법
데이터 분석 문제 해결을 위한 나의 JMP 활용법데이터 분석 문제 해결을 위한 나의 JMP 활용법
데이터 분석 문제 해결을 위한 나의 JMP 활용법
 
공학 관점에서 바라본 JMP 머신러닝 최적화
공학 관점에서 바라본 JMP 머신러닝 최적화공학 관점에서 바라본 JMP 머신러닝 최적화
공학 관점에서 바라본 JMP 머신러닝 최적화
 

To quickly implementing RNN

  • 2. Contents Intro Many to One Many to Many Seq2Seq QnA 2
  • 3. Intro 진행하기전에..... 슬라이드의 모든 code snippets은 아래의 링크로 다운 받 거나, 아래의 사이트에서 보시면 됩니다. Download : http://tagme.to/aisolab/To_quickly_implementin g_RNN Click : To quickly implementing RNN.ipynb 3
  • 4. Intro 먼저 Recurrent Neural Networks의 이론은 알고 있다 고 가정, api를 사용하는 법만 살펴봄 모든 상황은 variable sequence length를 가정, 예를 들 면 아래와 같이.. # 문장의 단어를 RNN에 하나하나씩 넣는다고 하면? # RNN은 아래처럼 각 문장 별로 단어의 개수만큼 sequence를 처리해야한다. sentences = [['I', 'feel', 'hungry'], ['tensorflow', 'is', 'very', 'difficult'], ['tensorflow', 'is', 'a', 'framework', 'for','deep','learning'], ['tensorflow', 'is', 'very', 'fast', 'changing']] 4
  • 5. Intro : Padding tensor ow에서 variable sequence length를 다루기 위해서는 일단 적당한 길이로 padding을 해야함 왜냐하면 eager mode를 활용하지않는 이상 tensor ow 는 정적인 framework이기 때문 padding을 위한 tensor ow graph를 정의하거나, python 함수를 정의하여 활용 padding시 적당한 최대 길이를 정해줄 것 5
  • 6. Intro : Padding # word dic word_list = [] for elm in sentences: word_list += elm word_list = list(set(word_list)) word_list.sort() # '<pad>'라는 의미없는 token 추가 word_list = ['<pad>'] + word_list word_dic = {word : idx for idx, word in enumerate(word_list)} 6
  • 7. Intro : Padding # max_len의 길이에 못미치는 문장은 <pad>로 max_len만큼 padding def pad_seq(sequences, max_len, dic): seq_len, seq_indices = [], [] for seq in sequences: seq_len.append(len(seq)) seq_idx = [dic.get(char) for char in seq] # 0 is idx of meaningless token "<pad>" seq_idx += (max_len - len(seq_idx)) * [dic.get('<pad>')] seq_indices.append(seq_idx) return seq_len, seq_indices 7
  • 8. Intro : Padding max_length = 8 sen_len, sen_indices = pad_seq(sequences = sentences, max_len = max_length, dic = word_dic) [3, 4, 7, 5] [[1, 7, 10, 0, 0, 0, 0, 0], [13, 11, 14, 5, 0, 0, 0, 0], [13, 11, 2, 9, 8, 4, 12, 0], [13, 11, 14, 6, 3, 0, 0, 0]] 8
  • 9. Intro : Look up variable sequence를 가지는 input을 RNN의 input으 로 넣을 수 있도록 잘 padding 했는 데... padding 한 것을 그대로 RNN의 input으로 넣는 게 맞나? idx 별 뭔가 dense vector (eg. word2vec) 등을 사용해 야함, tf.nn.embedding_lookup을 활용하자! tf.nn.embedding_lookup( params, ids, partition_strategy='mod', name=None, validate_indices=True, max_norm=None) 9
  • 10. Intro : Look up # tf.nn.embedding_lookup의 params, ids arg에 전달하기위한 # placeholder 선언 seq_len = tf.placeholder(dtype = tf.int32, shape = [None]) seq_indices = tf.placeholder(dtype = tf.int32, shape = [None, max_length]) one_hot = np.eye(len(word_dic)) # 단어 별 one-hot encoding # embedding vector는 training 안할 것이므로 one_hot = tf.get_variable(name='one_hot', initializer = one_hot, trainable = False) seq_batch = tf.nn.embedding_lookup(params = one_hot, ids = seq_indices) 10
  • 11. Intro : Look up with tf.Session() as sess: sess.run(tf.global_variables_initializer()) tmp = sess.run(seq_batch, feed_dict = {seq_indices : sen_indices}) print(np.shape(sen_indices)) print(np.shape(tmp)) (4, 8) (4, 8, 15) # tf.nn.dynamic_rnn, tf.contrib.seq2seq.TrainingHelper 등에 # 이 shape을 유지하면서 전달되어야함 11
  • 12. Many to One eg. 영어 문장의 긍/부정을 평가하는 RNN (with GRU)
  • 13. Example data sentences = [['I', 'feel', 'hungry'], ['tensorflow', 'is', 'very', 'difficult'], ['tensorflow', 'is', 'a', 'framework', 'for', 'deep', 'learning'], ['tensorflow', 'is', 'very', 'fast', 'changing']] label = [[0.,1.], [0.,1.], [1.,0.], [1.,0.]] 13
  • 14. Example data sentences의 word들의 idx를 가지고 있는 dictionary 생성 # word dic word_list = [] for elm in sentences: word_list += elm word_list = list(set(word_list)) word_list.sort() # '<pad>'라는 의미없는 token 추가 word_list = ['<pad>'] + word_list word_dic = {word : idx for idx, word in enumerate(word_list)} 14
  • 15. Example data dictionary를 이용하여 다음과 같이 전처리 [3, 4, 7, 5] [[1, 7, 10, 0, 0, 0, 0, 0], [13, 11, 14, 5, 0, 0, 0, 0], [13, 11, 2, 9, 8, 4, 12, 0], [13, 11, 14, 6, 3, 0, 0, 0]] max_length = 8 sen_len, sen_indices = pad_seq(sequences = sentences, max_len = dic = word_dic) pprint(sen_len) pprint(sen_indices) 15
  • 16. Simple tf.nn.dynamic_rnn cell을 돌릴 때 활용, return 값 중 state만을 활용 sequence_length에 padding 하기전 문장의 길이를 넣어주면 알아서 원 문장 의 sequence만큼 처리 tf.losses.softmax_cross_entropy 일반적인 NN의 loss와 동일 tf.nn.dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None) 16
  • 17. Stacked tf.contrib.rnn.MultiRNNCell Stacking을 위해 활용 tf.contrib.rnn.DropoutWrapper layer가 깊어지므로, Over tting 방지를 위해 활용 tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True) 17
  • 18. Bi-directional tf.nn.bidirectional_dynamic_rnn fw_cell과 bw_cell을 돌릴 때 활용, return 값 중 output_states만을 활용, output_states는 fw_cell과 bw_cell의 nal state 값을 갖고 있어서, loss 계산 시 둘을 concatenate해서 활용 tf.nn.bidirectional_dynamic_rnn(cell_fw, cell_bw, inputs, sequence_length=None, initial_state_fw=None, initial_state_bw=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None) 18
  • 19. Stacked Bi-directional tf.contrib.rnn.stack_bidirectional_dynamic_rnn 각각의 fw_cells, bw_cells (list 형태)를 돌릴 때 활용 return 값 중 output_state_fw, output_state_bw를 concatenate해서 활 용 tf.contrib.rnn.stack_bidirectional_dynamic_rnn( cells_fw, cells_bw, inputs, initial_states_fw=None, initial_states_bw=None, dtype=None, sequence_length=None, parallel_iterations=None, time_major=False, scope=None) 19
  • 20. Many to Many eg. 형태소 분석을 하는 RNN (with GRU)
  • 21. Example data sentences = [['I', 'feel', 'hungry'], ['tensorflow', 'is', 'very', 'difficult'], ['tensorflow', 'is', 'a', 'framework', 'for', 'deep', 'learning'], ['tensorflow', 'is', 'very', 'fast', 'changing']] pos = [['pronoun', 'verb', 'adjective'], ['noun', 'verb', 'adverb', 'adjective'], ['noun', 'verb', 'determiner', 'noun', 'preposition', 'adjective', 'noun'], ['noun', 'verb', 'adverb', 'adjective', 'verb']] 21
  • 22. Example data sentences의word들의idx를가지고있는dictionary 생성 pos의 token들의 idx를 가지고 있는 dictionary 생성 # word dic word_list = [] for elm in sentences: word_list += elm word_list = list(set(word_list)) word_list.sort() word_list = ['<pad>'] + word_list word_dic = {word : idx for idx, word in enumerate(word_list)} 22
  • 23. Example data sentences의 word들의 idx를 가지고 있는 dictionary 생성 pos의token들의idx를가지고있는dictionary 생성 # pos dic pos_list = [] for elm in pos: pos_list += elm pos_list = list(set(pos_list)) pos_list.sort() pos_list = ['<pad>'] + pos_list pos_dic = {pos : idx for idx, pos in enumerate(pos_list)} 23
  • 24. Example data dictionary를 이용하여 다음과 같이 전처리 sen_len, sen_indices = pad_seq(sequences = sentences, max_len = max_length, dic = word_dic) _, pos_indices = pad_seq(sequences = pos, max_len = max_length, dic = pos_dic) 24
  • 25. Example data dictionary를 이용하여 다음과 같이 전처리 pprint(sen_len) pprint(sen_indices) [3, 4, 7, 5] [[1, 7, 10, 0, 0, 0, 0, 0], [13, 11, 14, 5, 0, 0, 0, 0], [13, 11, 2, 9, 8, 4, 12, 0], [13, 11, 14, 6, 3, 0, 0, 0]] 25
  • 26. Example data dictionary를 이용하여 다음과 같이 전처리 pprint(pos_indices) [[6, 7, 1, 0, 0, 0, 0, 0], [4, 7, 2, 1, 0, 0, 0, 0], [4, 7, 3, 4, 5, 1, 4, 0], [4, 7, 2, 1, 7, 0, 0, 0]] 26
  • 27. Simple Cell을 사용하는 방식은 Many to One 위 Case와 동일 단 tf.nn.dynamic_rnn의 return 값중 outputs을 활용 tf.contrib.rnn.OutputProjectionWrapper step마다 classify를 하기위해 활용 tf.sequence_mask 원래 sequence에 대해서만 loss를 계산하기위해 활용 tf.contrib.seq2seq.sequence_loss tf.sequence_mask의 output을 weights arg에 전달 받음 targets arg에 [None, sequence_length]의 label 전달 27
  • 28. Stacked Cell을 사용하는 방식은 Many to One 위 Case와 동일 단 tf.nn.dynamic_rnn의 return 값중 outputs을 활용 tf.contrib.rnn.OutputProjectionWrapper step마다 classify를 하기위해 활용 tf.sequence_mask 원래 sequence에 대해서만 loss를 계산하기위해 활용 tf.contrib.seq2seq.sequence_loss tf.sequence_mask의 output을 weights arg에 전달 받음 targets arg에 [None, sequence_length]의 label 전달 28
  • 29. Bi-directional Cell을 사용하는 방식은 Many to One 위 Case와 동일 단 tf.nn.bidirectional_dynamic_rnn의 return 값중 outputs을 활용 tf.map_fn step마다 classify를 하기위해 활용 tf.sequence_mask 원래 sequence에 대해서만 loss를 계산하기위해 활용 tf.contrib.seq2seq.sequence_loss tf.sequence_mask의 output을 weights arg에 전달 받음 targets arg에 [None, sequence_length]의 label 전달 29
  • 30. Stacked Bi-directional Cell을 사용하는 방식은 Many to One 위 Case와 동일 단 tf.contrib.rnn.stack_bidirectional_dynamic_rnn의 return 값중 outputs을 활용 tf.map_fn step마다 classify를 하기위해 활용 tf.sequence_mask 원래 sequence에 대해서만 loss를 계산하기위해 활용 tf.contrib.seq2seq.sequence_loss tf.sequence_mask의 output을 weights arg에 전달 받음 targets arg에 [None, sequence_length]의 label 전달 30
  • 32. Example data targets = [['나는', '배가', '고프다'], ['텐서플로우는', '매우', '어렵다'], ['텐서플로우는', '딥러닝을', '위한', '프레임워크이다'], ['텐서플로우는', '매우', '빠르게', '변화한다']] sources = [['I', 'feel', 'hungry'], ['tensorflow', 'is', 'very', 'difficult'], ['tensorflow', 'is', 'a', 'framework', 'for', 'deep', ['tensorflow', 'is', 'very', 'fast', 'changing']] 32
  • 33. Example data sources의word들의idx를가지고있는dictionary 생 성 targets의 word들의 idx를 가지고 있는 dictionary 생성 # word dic for sentences source_words = [] for elm in sources: source_words += elm source_words = list(set(source_words)) source_words.sort() source_words = ['<pad>'] + source_words source_dic = {word : idx for idx, word in enumerate(source_words)} 33
  • 34. Example data sources의 word들의 idx를 가지고 있는 dictionary 생성 targets의word들의idx를가지고있는dictionary 생 성 # word dic for translations target_words = [] for elm in targets: target_words += elm target_words = list(set(target_words)) target_words.sort() # 번역문의 시작과 끝을 알리는 'start', 'end' token 추가 target_words = ['<pad>']+ ['<start>'] + ['<end>'] + target_words target_dic = {word : idx for idx, word in enumerate(target_words)} 34
  • 36. QnA
  • 38. 들어주셔서감사합니다.   Github : github.com/aisolab   Blog : aisolab.github.io   E-mail : bsk0130@gmail.com