ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • TensorFlow keras를 이용한 선형회귀
    Machine Learning/기본개념 2023. 5. 19. 02:56
    반응형

    제목처럼 tf.keras를 사용해서 선형회귀를 간단하게 익혀보자

     

    import pandas as pd
    import tensorflow as tf
    from matplotlib import pyplot as plt

    여기서 사용할 tensorflow와 pandas, pyplot을 불러오자

    pyplot은 데이터 시각화에 유용한 툴이다. 우리가 가진 데이터값을 도표나 그래프를 이용해 효과적으로 나타내준다.

     

    이제 우리는 모델을 빌드하고 학습을 시키는게 이 과정의 핵심이다.

    #모델 구축
    def build_model(my_learning_rate):
      #대부분 tf.keras는 순차적으로 시행되며 여기에 하나 이상의 레이어가 포함됩니다.
      model = tf.keras.models.Sequential()
    
      #여기서 dense는 신경망을 만드는 함수이다
      #unit은 출력값의 크기를 의미한다.
      #input_shape는 입력인데 우리는 입력과 출력이 각각 한 개인
      #단일 계층의 신경망을 구성함을 의미한다.
      model.add(tf.keras.layers.Dense(units=1, 
                                      input_shape=(1,)))
    
      #모델을 컴파일하는 과정인데 RMSprop으로 최적화를 진행한다는 의미이다.
      #RMSprop은 경사(gradient)의 크기를 지수 이동 평균(exponential moving average)을 사용하여
      #조절하며, 경사의 크기에 따라 각각의 파라미터를 업데이트합니다.(위키트리)
      model.compile(optimizer=tf.keras.optimizers.experimental.RMSprop(learning_rate=my_learning_rate),
                    loss="mean_squared_error",
                    metrics=[tf.keras.metrics.RootMeanSquaredError()])
      #모델 반환
      return model           
    
    #모델 학습
    def train_model(model, feature, label, epochs, batch_size):
      #데이터를 공급함으로써 모델을 학습시킵니다.
    
      #feature값과 label값을 모델에 공급합니다.
      #모델은 feature값에 따른 lable값이 어떻게 결정되는지 학습합니다
      #batch_size는 몇 개의 샘플로 가중치를 결정할 것인 지를 의미하며
      #epochs는 학습 반복 횟수를 의미합니다.
      #즉 batch_size가 10이면 10개의 해답을 풀 때마다 가중치 갱신이 일어납니다.
      #epochs는 전체 문제를 몇 번 풀어볼 것인지 정하는 것인데 같은 문제를 반복해서
      #풀면서 학습이 된다고 이해하면 쉽다.
      history = model.fit(x=feature,
                          y=label,
                          batch_size=batch_size,
                          epochs=epochs)
    
      # 모델의 가중치와 편향을 수집합니다.
      trained_weight = model.get_weights()[0]
      trained_bias = model.get_weights()[1]
    
      #epochs값을 history에 할당
      epochs = history.epoch
      
      #모델학습한 history를 내용으로 하는 dataframe을 생성합니다.
      hist = pd.DataFrame(history.history)
    
      #오차도 함께 수집해줍니다.
      rmse = hist["root_mean_squared_error"]
    
      return trained_weight, trained_bias, epochs, rmse

     

    이렇게 모델 정의 함수와 학습함수까지 정의를 마쳤으니 이제 시각화에 사용할 maplot함수를 정의해보자.

     

    # 모델 그리기 함수
    def plot_the_model(trained_weight, trained_bias, feature, label):
      """Plot the trained model against the training feature and label."""
    
      # 모델 축 설정
      plt.xlabel("feature")
      plt.ylabel("label")
    
      # scatter라는 산포 그래프를 쓸 것이며 feature값과 label값을 사용한다는 의미이다.
      # 산포그래프는 점으로 이루어진 그래프를 의미한다.
      plt.scatter(feature, label)
    
      # 모형을 나타내는 축을 만든다.
      # 이 축은 x0,y0으로 시작해서x1,y1으로 끝난다.
      x0 = 0
      y0 = trained_bias
      x1 = feature[-1]
      y1 = trained_bias + (trained_weight * x1)
      #plot함수는 x축과 y축을 의미한다. c는 컬러
      plt.plot([x0, x1], [y0, y1], c='r')
    
      # Render the scatter plot and the red line.
      plt.show()
    
    def plot_the_loss_curve(epochs, rmse):
     #손실 그래프
    
      # figure은 새로운 그림을 의미한다.
      # x는 epoch값 y는 에러값이다.
      plt.figure()
      plt.xlabel("Epoch")
      plt.ylabel("Root Mean Squared Error")
    
      plt.plot(epochs, rmse, label="Loss")
      #legend는 범례를 의미한다.
      plt.legend()
      plt.ylim([rmse.min()*0.97, rmse.max()])
      plt.show()
    
    print("Defined the plot_the_model and plot_the_loss_curve functions.")

     

    실제 선형회귀를 동작시켜보자

     

    my_feature = ([1.0, 2.0,  3.0,  4.0,  5.0,  6.0,  7.0,  8.0,  9.0, 10.0, 11.0, 12.0])
    my_label   = ([5.0, 8.8,  9.6, 14.2, 18.8, 19.5, 21.4, 26.8, 28.9, 32.0, 33.8, 38.2])
    
    learning_rate=0.01 #학습률
    epochs=10 #학습횟수
    my_batch_size=12 #feature&label 크기
    
    my_model = build_model(learning_rate)
    trained_weight, trained_bias, epochs, rmse = train_model(my_model, my_feature, 
                                                             my_label, epochs,
                                                             my_batch_size)
    plot_the_model(trained_weight, trained_bias, my_feature, my_label)
    plot_the_loss_curve(epochs, rmse)

    이렇게 데이터를 넣고 돌려보면

    이런 개떡같은 그림을 얻을 수 있다..ㅎㅎㅎ

    훈련 손실에 대한 값이 형편없음을 우리는 여기서 알 수 있다.

    그럼 우리는 epoch값을 대폭 늘려서 학습량을 조절하면 어떻게 될까?

    epoch를 450으로 늘려서 학습량을 대폭 늘렸더니 만족스러운 결과가 나왔다

    그러나 이렇게 하면 학습시키는 시간이 너무 오래 걸릴 수 있다. 

    그러면 다른 방법인 학습률을 고쳐보자

     

    learning_rate= 0.2 
    epochs= 10   
    my_model = build_model(learning_rate)
    trained_weight, trained_bias, epochs, rmse = train_model(my_model, my_feature, 
                                                             my_label, epochs,
                                                             my_batch_size)
    plot_the_model(trained_weight, trained_bias, my_feature, my_label)
    plot_the_loss_curve(epochs, rmse)

    epochs는 10으로 그대로 둔 상태에서 rate만 0.2로 끌어올렸더니

    훨씬 적은 학습량을 가지고 만족스러운 결과를 얻었다.

    이를 통해 적절한 epochs와 rate가 학습 속도에 엄청난 영향을 끼침을 우리는 배울 수 있다.

     

    우리가 만든 시스템은 모델의 손실값을 다시 계산하고 반복하여 모델의 가중치와 편향치를 조정합니다.

    예를 들어, 배치 크기가 6이면 시스템은 모형의 손실 값을 다시 계산하고 6개의 예제마다 각각 처리한 후의 가중치와

    편향을 조정합니다.

     

    우리가 만든 데이터 세트는 충분히 여러번 반복할 수 있는 데이터세트 길이이다. 즉 12개의 데이터세트이지만 12개를 전부 계산하고 각각 예제마다 처리한 후에 가중치와 편향을 조정할 필요가 없다.epoch는 반복을 의미하는데 우리가 batch길이를 6으로 지정하면 데이터세트의 모든 예제를 처리하는데 우리는 2번의 해답을 제시할 수 있음을 의미한다.

    그렇다면 12개의 모든 데이터를 처리하고 해답을 놓는 것 보다 좀 더 빠르게 올바른 해답을 얻는 게 우리의 목표이므로

    단일 선형 회귀 모형에서 1개의 데이터를 예제로 사용할 때마다 해답을 놓는다면 더욱 빠르게 원하는 모델을 얻을 수 있지 않을까?

     

    이에 대한 해답이 아래에 있다

    learning_rate=0.05
    epochs=100
    my_batch_size= 1  # Replace ? with an integer.
    
    my_model = build_model(learning_rate)
    trained_weight, trained_bias, epochs, rmse = train_model(my_model, my_feature, 
                                                            my_label, epochs,
                                                            my_batch_size)
    plot_the_model(trained_weight, trained_bias, my_feature, my_label)
    plot_the_loss_curve(epochs, rmse)

    우리는 1개의 데이터를 읽을때마다 해답을 내며 100회의 epoch내에서 적절한 선형회귀 모델 결과값을 얻어냈다.

    우리가 가진 data의 형태와 적절한 학습률, epoch를 활용하면 빠르게 강력한 모델을 얻을 수 있음을 배웠다.

    반응형

    'Machine Learning > 기본개념' 카테고리의 다른 글

    정규화와 로지스틱 회귀  (0) 2023.05.22
    특성교차  (0) 2023.05.22
    모델 학습 및 검증에 관하여  (1) 2023.05.20
    Numpy 기본 개념 익히기  (0) 2023.05.19
    머신러닝, 선형회귀에 대해 알아보자  (0) 2023.05.18

    댓글

Designed by Tistory.