코딩헤딩

Deep learning[딥러닝] 모델 생성 함수 및 손실률/정확도 시각화 본문

머신러닝 | 딥러닝

Deep learning[딥러닝] 모델 생성 함수 및 손실률/정확도 시각화

멈머이 2024. 1. 5. 00:27
728x90

  - 패션MNIST 데이터 읽어들이기(훈련 및 테스트데이터)

(train_input, train_target), (test_input, test_target) = keras.datasets.fashion_mnist.load_data()

print(train_input.shape, train_target.shape)
print(test_input.shape, test_target.shape)

결과 : 

(60000, 28, 28) (60000,)
(10000, 28, 28) (10000,)

 

*데이터 전처리 생략

 

  * 인공신경망(Artificial Neural Network, ANN)
     -> 계층이 1개인 경우 또는 은닉계층이 없는 경우
  * 심층신경망(Deep Neureal Network, DNN)
     -> 은닉계층을 가지고 있는 경우

 

모델 생성부터 훈련까지 함수로 만들어보겠다.

  - 함수 이름 : model_fn
     --> 매개변수 : a_layer
         => 은닉계층이 있는 경우 계층자체를 매개변수로 받아서 아래에서 추가 
  - 모델생성
  - 입력층(1차원 전처리 계층) 추가
  - 100개의 출력을 담당하는 은닉계층 추가, 활성화 함수 relu
  - 추가할 은닉계층이 있으면 추가, 없으면(None) 건너뛰기
  - 출력층
  - 모델 반환

def model_fn(a_layer=None):
    model = keras.Sequential()

    model.add(keras.layers.Flatten(input_shape = (28, 28)))
    model.add(keras.layers.Dense(100, activation="relu"))

    """추가할 은닉계층이 있는경우만 실행"""
    if a_layer:
        model.add(a_layer)
    
    model.add(keras.layers.Dense(10, activation="softmax"))

    return model

 

* 모델 생성 계층 확인하기

models.summary()

 

 


param = (입력크기 * 출력크기) + 출력크기
78500 = (784 * 100) + 100
1100 = (100 * 10) + 10

 

 

 

 

 

* 모델 설정하기(compile)

models.compile(loss = "sparse_categorical_crossentropy",
               metrics = "accuracy")

 

* 훈련하기(fit)

models.fit(train_scaled, train_target, epochs=5)

 

* 훈련 출력방법 지정

history = models.fit(train_scaled, train_target, epochs=5, verbose=1)
print("훈련끝>>>>>>>")

 

- verbose : 출력방법
     : 0은 아무것도 안 나옴
     : 1은 프로그래스바와 함께 loss와 accuracy
     : 2는 loss와 accuracy만 출력(프로그래스바 안 나옴)
            : 기본값은 1

 

history.epoch

결과 : [0, 1, 2, 3, 4]   => epoch가 5였기 때문에 0~4

 

history.history

결과 :

{'loss': [0.307718962430954,
  0.2965776026248932,
  0.2887006998062134,
  0.28036344051361084,
  0.27207207679748535],
 'accuracy': [0.8912291526794434,
  0.8948749899864197,
  0.8979374766349792,
  0.9012708067893982,
  0.9027708172798157]}

 

* 손실률 시각화 하기

import matplotlib.pyplot as plt

plt. title("Epochs - Loss")
plt.plot(history.epoch, history.history["loss"])
plt.xlabel("epoch")
plt.ylabel("loss")
plt.grid()

plt.savefig("./saveFig/Epochs-Loss.png")
plt.show

* 정확도 시각화 하기

plt. title("Epochs - accuracy")
plt.plot(history.epoch, history.history["accuracy"])
plt.xlabel("epoch")
plt.ylabel("accuracy")
plt.grid()

plt.savefig("./saveFig/Epochs-Accuracy.png")
plt.show

728x90