Data Analysis/Machine learning
모두를 위한 딥러닝 - RNN 실습(1)
노는게제일좋아!
2019. 8. 7. 12:37
반응형
모두를 위한 딥러닝 ML lab12-1: RNN - Basics 강의 정리&코드
전체 코드: https://github.com/hunkim/DeepLearningZeroToAll/blob/master/lab-12-0-rnn_basics.ipynb
1. 데이터
# One hot encoding
h = [1, 0, 0, 0]
e = [0, 1, 0, 0]
l = [0, 0, 1, 0]
o = [0, 0, 0, 1]
# input dimension -> 4 (0,0,0,0)
입력 데이터의 dimension이 뭐든 상관없이 출력의 dimension은 우리가 설정한 hidden_size를 따름
2. cell 만들기
with tf.variable_scope('one_cell') as scope:
hidden_size = 2 # 출력 개수
# cell 만들기
cell =tf.keras.layers.SimpleRNNCell(units=hidden_size) #hidden_size= 출력의 크기
# cell = tf.contrib.rnn.BasicRNNCell(num_units=hidden_size)
# cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_size)
# 이 중 잘 작동하는거 골라서 쓰면됨
print(cell.output_size, cell.state_size)
x_data = np.array([[h]],dtype=np.float32) # x_data = [[[1,0,0,0]]] -> shape=(1,1,4)
pp.pprint(x_data)
#우리가 만든 cell과 입력 값인 x_data를 인자로 넘겨주고
#해당 스텝의 output과 다음 스테이트로 넘어가는 출력 _state를 만든다
outputs, _states = tf.nn.dynamic_rnn(cell, x_data, dtype=tf.float32)
sess.run(tf.global_variables_initializer())
pp.pprint(outputs.eval())
<마지막 출력>
hidden_size를 2로 둬서 값 2개가 나옴
0.531.... : 초기값 랜덤하게 줘서 나온 값
3. Unfolding to n sequences
sequence_length: cell을 몇 번 펼칠 건가
-> [ [h, e, l, l, o] ]이므로 seq=5
with tf.variable_scope('two_sequences') as scope:
#One cell RNN input_dim (4) -> output_dim (2), sequence: 5
hidden_size=2
cell = tf.keras.layers.SimpleRNNCell(units=hidden_size)
x_data = np.array([[h,e,l,l,o]],dtype=np.float32)
print(x_data.shape)
pp.pprint(x_data)
outputs, x_states=tf.nn.dynamic_rnn(cell,x_data,dtype=tf.float32)
sess.run(tf.global_variables_initializer())
pp.pprint(outputs.eval())
4. batch
데이터를 여러개 줌 -> batch size
shape = (batch_size, sequence_length, hidden_size)
입력 데이터를 shape=(3,5,4)로 주면 됨
with tf.variable_scope('3_batches') as scope:
# One cell RNN input_dim (4) -> output_dim (2). sequence: 5, batch 3
# 3 batches 'hello', 'eolll', 'lleel'
x_data = np.array([[h, e, l, l, o],
[e, o, l, l, l],
[l, l, e, e, l]], dtype=np.float32)
pp.pprint(x_data)
hidden_size = 2
cell = tf.nn.rnn_cell.LSTMCell(num_units=hidden_size, state_is_tuple=True)
outputs, _states = tf.nn.dynamic_rnn(
cell, x_data, dtype=tf.float32)
sess.run(tf.global_variables_initializer())
pp.pprint(outputs.eval())
반응형