ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Tensorflow - 히든레이어와 인공신경망
    생활코딩/머신러닝야학 2020. 8. 19. 14:14

    [강의 출처] opentutorials.org/module/4966/28988

     

    네번째 딥러닝 - 신경망의 완성:히든레이어 - Tensorflow 1

    수업소개 히든레이어와 멀티레이어의 구조를 이해하고, 히든레이어를 추가한 멀티레이어 인공신경망 모델을 완성해 봅니다.  강의  멀티레이어 신경망 실습  소스코드 colab |  backend.ai 보스

    opentutorials.org


    히든레이어(Hidden Layer)

    -보다 깊은 신경망을 만들기 위해 입력(Input Layer)과 출력(Outpter Layer) 사이에 추가된 퍼셉트론들

    -히든레이어로 각각의 모델들을 연속적으로 연결해서 하나의 거대한 신경망을 만듦

    -아래 그림의 Node는 5개

    보스턴 집 가격

    # 1.과거의 데이터를 준비합니다.
    파일경로 = 'https://raw.githubusercontent.com/blackdew/tensorflow1/master/csv/boston.csv'
    보스턴 = pd.read_csv(파일경로)
    
    # 종속변수, 독립변수
    독립 = 보스턴[['crim', 'zn', 'indus', 'chas', 'nox', 
                'rm', 'age', 'dis', 'rad', 'tax',
                'ptratio', 'b', 'lstat']]
    종속 = 보스턴[['medv']]
    print(독립.shape, 종속.shape) # (506, 13) (506, 1)
    
    
    # 2. 모델의 구조를 만듭니다
    X = tf.keras.layers.Input(shape=[13])
    H = tf.keras.layers.Dense(5, activation='swish')(X) # 필요에 따라 히든레이어를 여러개 쌓아도 OK
    # H = tf.keras.layers.Dense(3, activation='swish')
    # H = tf.keras.layers.Dense(3, activation='swish') # 활성화함수 swish
    Y = tf.keras.layers.Dense(1)(H) # X 대신 마지막 히든레이어에서 만들어진 H를 입력해야함
    model = tf.keras.models.Model(X, Y)
    model.compile(loss='mse')
    
    
    # 모델 구조 확인
    model.summary() # 모델이 잘 만들어졌는지
    """
    Model: "functional_1"
    _________________________________________________________________
    Layer (type)                 Output Shape              Param #    # Param = 가중치
    ================================================================= # 13개 입력층
    input_1 (InputLayer)         [(None, 13)]              0          
    _________________________________________________________________ # 10개의 아웃풋
    dense (Dense)                (None, 10)                140        # 수식항 140 = (13+1(bias)) * 10
    _________________________________________________________________ # 1개의 아웃풋
    dense_1 (Dense)              (None, 1)                 11         # 수식항 11: (10+1(bias)) * 1
    ================================================================= 
    Total params: 151
    Trainable params: 151
    Non-trainable params: 0
    """
    
    
    # 3.데이터로 모델을 학습(FIT)합니다.
    model.fit(독립, 종속, epochs=1000,  verbose=0)
    model.fit(독립, 종속, epochs=10)
    # 히든레이어 없이 돌렸을 때는 loss가 20 초반이었는데 히든레이어 추가하니 loss가 10대로 떨어짐
    
    
    # 4. 모델을 이용합니다
    print(model.predict(독립[:5]))
    print(종속[:5])
    """
    [[29.1588  ]
     [26.645525]
     [33.00533 ]
     [32.906254]
     [33.95064 ]]
       medv
    0  24.0
    1  21.6
    2  34.7
    3  33.4
    4  36.2
    """
    

     

    아이리스

    # 라이브러리 사용
    import tensorflow as tf
    import pandas as pd
    
    
    # 1.과거의 데이터를 준비합니다.
    파일경로 = 'https://raw.githubusercontent.com/blackdew/tensorflow1/master/csv/iris.csv'
    아이리스 = pd.read_csv(파일경로)
    
    # 원핫인코딩
    아이리스 = pd.get_dummies(아이리스)
    
    # 종속변수, 독립변수
    독립 = 아이리스[['꽃잎길이', '꽃잎폭', '꽃받침길이', '꽃받침폭']]
    종속 = 아이리스[['품종_setosa', '품종_versicolor', '품종_virginica']]
    print(독립.shape, 종속.shape) # (150, 4) (150, 3)
    
    
    # 2. 모델의 구조를 만듭니다
    X = tf.keras.layers.Input(shape=[4])
    H = tf.keras.layers.Dense(8, activation="swish")(X) # 히든레이어1
    H = tf.keras.layers.Dense(8, activation="swish")(H) # 히든레이어2
    H = tf.keras.layers.Dense(8, activation="swish")(H) # 히든레이어3
    Y = tf.keras.layers.Dense(3, activation='softmax')(H)
    model = tf.keras.models.Model(X, Y)
    model.compile(loss='categorical_crossentropy',
                  metrics='accuracy')
    """
    Model: "functional_5"
    _________________________________________________________________
    Layer (type)                 Output Shape              Param #   
    =================================================================
    input_3 (InputLayer)         [(None, 4)]               0         
    _________________________________________________________________
    dense_6 (Dense)              (None, 8)                 40        
    _________________________________________________________________
    dense_7 (Dense)              (None, 8)                 72        
    _________________________________________________________________
    dense_8 (Dense)              (None, 8)                 72        
    _________________________________________________________________
    dense_9 (Dense)              (None, 3)                 27        
    =================================================================
    Total params: 211
    Trainable params: 211
    Non-trainable params: 0
    _________________________________________________________________
    
    """
    
    # 3.데이터로 모델을 학습(FIT)합니다.
    model.fit(독립, 종속, epochs=100)
    """
    ...
    Epoch 99/100
    5/5 [==============================] - 0s 3ms/step - loss: 0.1640 - accuracy: 0.9667
    Epoch 100/100
    5/5 [==============================] - 0s 2ms/step - loss: 0.1628 - accuracy: 0.9733
    
    # 히든레이어가 없었을 때는 100번 학습시 loss: 0.5723 - accuracy: 0.5400 정도의 결과를 보였음
    # 히든레이어없이 400번 정도 학습했을 때 loss: 0.3121 - accuracy: 0.9800
    # 이후 추가로 학습시켰을 때 loss: 0.0610 - accuracy: 0.9800 정도 수준에서 멈춤
    # 히든레이어를 끝까지 학습시켰을 때 loss: 0.0468 - accuracy: 0.9800 수준
    # 정확도면에서는 차이가 별로 없지만, 학습 소요시간이 거의 1/10 수준이었다는 점에서 히든레이어가 굉장히 유리함을 알 수 있음
    """
    
    # 4. 모델을 이용합니다
    print(model.predict(독립[0:5]))
    print(종속[0:5])
    """
    [[9.9999666e-01 3.0568333e-06 2.5192719e-07]
     [9.9999857e-01 1.3014619e-06 1.0592617e-07]
     [9.9999249e-01 6.8496206e-06 7.3619435e-07]
     [9.9999809e-01 1.7481435e-06 1.4425528e-07]
     [9.9999428e-01 5.2722507e-06 4.6033318e-07]]
       품종_setosa  품종_versicolor  품종_virginica
    0          1              0             0
    1          1              0             0
    2          1              0             0
    3          1              0             0
    4          1              0             0
    """

    댓글

Designed by Tistory.