ABOUT ME

초보 개발자의 코딩 노트( 코딩탕탕)

Today
Yesterday
Total
  • TensorFlow 기초 37 - RNN(Recurrent Neural Network)
    TensorFlow 2022. 12. 13. 17:01

     

    RNN(Recurrent Neural Network)은 히든 노드가 방향을 가진 엣지로 연결되어 순환구조를 이루는(directed cycle) 인공신경망의 한 종류입니다.
    음성, 문자 등 순차적으로 등장하는 데이터 처리에 적합한 모델로 알려져 있다.
    Convolutional Neural Networks(CNN)과 더불어 최근 들어 각광받고 있는 알고리즘이다.
    활용 : 텍스트 분류, 품사 태깅, 문서 요약, 문서 작성, 기계 번역, 이미지 캡션... 등 사용

    RNN은 sequence data : 입력값에 대해 현재의 state가 다음의 state에 영향을 준다.

     

     

    # RNN(Recurrent Neural Network)은 히든 노드가 방향을 가진 엣지로 연결되어 순환구조를 이루는(directed cycle) 인공신경망의 한 종류입니다.
    # 음성, 문자 등 순차적으로 등장하는 데이터 처리에 적합한 모델로 알려져 있다.
    # Convolutional Neural Networks(CNN)과 더불어 최근 들어 각광받고 있는 알고리즘이다.
    # 활용 : 텍스트 분류, 품사 태깅, 문서 요약, 문서 작성, 기계 번역, 이미지 캡션... 등 사용
    # RNN은 sequence data : 입력값에 대해 현재의 state가 다음의 state에 영향을 준다.
    
    from keras.models import Sequential
    from keras.layers import SimpleRNN, LSTM, GRU, Dense
    
    model = Sequential()
    # model.add(SimpleRNN(units=3, input_shape=(2, 10)))
    # model.add(SimpleRNN(3, input_length=2, input_dim=10)) # 위와 동일
    model.add(LSTM(units=3, input_shape=(2, 10))) # Long Short-Term Memory units
    print(model.summary())
    
    model = Sequential()
    model.add(LSTM(units=3, batch_input_shape=(8, 2, 10))) # batch_size=8, input_length=2, input_dim=10
    print(model.summary())
    
    model = Sequential()
    model.add(LSTM(units=3, batch_input_shape=(8, 2, 10), return_sequences=True)) # 다음 층으로 모든 은닉상태를 전달
    print(model.summary())
    
    # LSTM으로 다음 숫자 예측하기
    from numpy import array
    
    x = array([[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7],[10,20,30],[20,30,40],[30,40,50]])
    y = array([4,5,6,7,8,40,50,60])
    print(x, x.shape) # (8, 3)
    print(y, y.shape) # (8,)
    
    print(x, x.shape) # (8, 3, 1)
    
    # 모델 구성
    model = Sequential()
    model.add(LSTM(10, activation='tanh', input_shape=(3, 1)))
    # model.add(LSTM(10, activation='tanh', input_shape=(3, 1), return_sequences=True)) # many-to-many
    model.add(Dense(5, activation='relu'))
    model.add(Dense(1))
    
    model.compile(optimizer='adam', loss='mse')
    print(model.summary())
    
    from keras.callbacks import EarlyStopping
    es = EarlyStopping(monitor='loss', patience=5, mode='auto')
    model.fit(x, y, epochs=1000, batch_size=1, verbose=0, callbacks=[es])
    
    pred = model.predict(x)
    print('예측값 :', pred.flatten())
    print('실제값 :', y)
    
    x_new = array([[3, 5, 7]])
    new_pred = model.predict(x_new)
    print('새로운 예측값 :', new_pred.flatten())
    
    
    <console>
    2022-12-13 16:29:16.224256: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX AVX2
    To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
    Model: "sequential"
    _________________________________________________________________
     Layer (type)                Output Shape              Param #   
    =================================================================
     lstm (LSTM)                 (None, 3)                 168       
                                                                     
    =================================================================
    Total params: 168
    Trainable params: 168
    Non-trainable params: 0
    _________________________________________________________________
    None
    Model: "sequential_1"
    _________________________________________________________________
     Layer (type)                Output Shape              Param #   
    =================================================================
     lstm_1 (LSTM)               (8, 3)                    168       
                                                                     
    =================================================================
    Total params: 168
    Trainable params: 168
    Non-trainable params: 0
    _________________________________________________________________
    None
    Model: "sequential_2"
    _________________________________________________________________
     Layer (type)                Output Shape              Param #   
    =================================================================
     lstm_2 (LSTM)               (8, 2, 3)                 168       
                                                                     
    =================================================================
    Total params: 168
    Trainable params: 168
    Non-trainable params: 0
    _________________________________________________________________
    None
    [[ 1  2  3]
     [ 2  3  4]
     [ 3  4  5]
     [ 4  5  6]
     [ 5  6  7]
     [10 20 30]
     [20 30 40]
     [30 40 50]] (8, 3)
    [ 4  5  6  7  8 40 50 60] (8,)
    [[ 1  2  3]
     [ 2  3  4]
     [ 3  4  5]
     [ 4  5  6]
     [ 5  6  7]
     [10 20 30]
     [20 30 40]
     [30 40 50]] (8, 3)
    Model: "sequential_3"
    _________________________________________________________________
     Layer (type)                Output Shape              Param #   
    =================================================================
     lstm_3 (LSTM)               (None, 10)                480       
                                                                     
     dense (Dense)               (None, 5)                 55        
                                                                     
     dense_1 (Dense)             (None, 1)                 6         
                                                                     
    =================================================================
    Total params: 541
    Trainable params: 541
    Non-trainable params: 0
    _________________________________________________________________
    None
    
    1/1 [==============================] - ETA: 0s
    1/1 [==============================] - 0s 236ms/step
    예측값 : [ 4.0012474  4.9936314  5.99559    6.952085   8.063006  39.780865
     49.39792   56.75779  ]
    실제값 : [ 4  5  6  7  8 40 50 60]
    
    1/1 [==============================] - ETA: 0s
    1/1 [==============================] - 0s 8ms/step
    새로운 예측값 : [9.879905]

    댓글

Designed by Tistory.