본문 바로가기

DeepLearning Specialization(Andrew Ng)/Sequence Models

[Week 1] Quiz & Programming Assignments

728x90

# Quiz

1. You are training an RNN, and find that your weights and activations are all taking on the value of NaN (“Not a Number”). Which of these is the most likely cause of this problem? Gradient Exploding

 

2. 다시 되새기자면, language model을 통한 random sampling sentences 에서 다음 step으로 넘기는 y_hat을 결정하는건 무작정 제일 높은 확률을 가진 단어를 선택하는 것이 아니라 그 확률대로 랜덤하게 뽑는 것. 즉 높은 확률이면 높은 확률로 뽑히겠지? 밑에 문제는 답이 4번. 

 

# Programming Assignment 1

 

1. LSTM 에서 도식을 쉽게 기억하는 방법은, 지난걸(c<t-1>) 기억할지 말지는 forget으로, 미래의 것(c_hat<t>)을 기억할지 말지는 update로 결정한다고 생각.

 

2. BPTT

 강의에서 BPTT에 대한 이해가 부족했는데, 밑의 블로그를 보며 완치됐다. 

 

  • BPTT(Back Propagation Through Time) 을 할 때, timestep 별 error을 모두 더해서 cost를 정의했었다. 이 때 각 timestep의 error에 대한 weight들의 편미분값을 모두 더해서 전체 error에 대한 W의 미분값을 정의한다. 
  • 즉, (timestep 1에서 Loss(y1, yhat1)에 W가 영향을 끼치는 정도) + (timestep 2 에서 Loss(y2, yhat2)에 W가 영향을 끼치는 정도) + ... 를 모두 더하는 것. 생각해보면 지극히 정상적인 것이며 이것이 일반적인 Gradient Descent와 다른 BPTT의 핵심적인 특징이다. 자세한건 밑의 블로그를 참조하면 단박에 이해할 것. 
  • 참고로 W는 모든 timestep에서 동일한 것이다(Wax, Waa, Wya, ba).

jackiechansbigdata.tistory.com/29

 

[Week 1] 1. Recurrent Neural Networks

Recurrent Neural Networks 1. Why sequence models? 2. Notation 3. Recurrent Neural Networks 4. Backpropagation through time 5. Different types of RNNs 6. Language model and sequence generation 7. Sam..

jackiechansbigdata.tistory.com

 

3. Clipping for gradient exploding

  • exploding의 단적인 예가 위의 그림이다. 이때 clipping이라는 좋은 방법으로 해결할 수 있다. 
  • 범위를 설정해서 그 안으로만 gradient가 움직일 수 있도록 설정한 것. 그림 상으로는 화살표의 길이가 짦아지게 하는 효과가 있다. 
  • forward => cost compute => backward => clip => update 순으로

4. 1D와 2D의 연산

 요약하자면, 1D랑 2D를 내적하면 1D array 가 산출된다. 우리는 모든 행렬을 2D로 만들어 줌으로써 행렬간의 연산에 일관성을 부여해준다.

 

5. Keras for RNN

 

 케라스 사용법에 대해 간략히 설명해준다.

1) Forward P

n_values = 78 # number of music values
reshapor = Reshape((1, n_values))                        # Used in Step 2.B of djmodel(), below
LSTM_cell = LSTM(n_a, return_state = True)         # Used in Step 2.C
densor = Dense(n_values, activation='softmax')     # Used in Step 2.D
  • reshapor, LSTM_cell and densor are globally defined layer objects, that you'll use to implement djmodel().
  • In order to propagate a Keras tensor object X through one of these layers, use layer_object().
    • For one input, use layer_object(X)
    • For more than one input, put the inputs in a list: layer_object([X1,X2])

이처럼 layer를 만들고 layer_object()를 통해 forward propagation 해준다.

ex) reshapor(x), LSTM_cell([x1,x2])

 

2) Input()

Exercise: Implement djmodel().

Inputs (given)

  • The Input() layer is used for defining the input X as well as the initial hidden state 'a0' and cell state c0.
  • The shape parameter takes a tuple that does not include the batch dimension (m).
    • For example,X = Input(shape=(Tx, n_values))
    • # X has 3 dimensions and not 2: (m, Tx, n_values) Step 1: Outputs (TODO)
  • Create an empty list "outputs" to save the outputs of the LSTM Cell at every time step.

이처럼  shape에는 batch size를 빼고 넣어준다. m은 나중에 적용하면 되는 듯.

 

3) 오류

 

"Output tensors to a Model must be Keras tensors" 라는 오류를 맞이했다.

=> 알고보니 내 오타긴 했지만, 중요한 시사점을 제시한다. Keras를 이용해 모델을 만들 때에는 꼭 Keras Layer를 통해서 layer를 정의해야한다는 것. 어떤 연산을 하고 싶으면 Lambda(함수)(tensor)를 통해서 수행해야한다. 이 떄 Lambda는 Keras layer를 해당함수를 통해 만들어주는 역할을 한다.

 

qinyuns.wordpress.com/2019/05/31/output-tensors-to-a-model-must-be-keras-tensors/

 

Output tensors to a Model must be Keras tensors

When I build one model using tensorflow, I got this error message. The reason of this error is that, the layers should be followed one by one. If there is a parameter or operation that could not ge…

qinyuns.wordpress.com

 

728x90