본문 바로가기
파이썬/딥러닝

파이썬 딥러닝 - Dense만 사용해서 이미지 분류하기 (tensorflow.keras

by 큰고양2 2023. 10. 8.

import

#통계
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

#데이터 전처리
from sklearn.metrics import *
from sklearn.preprocessing import StandardScaler, MinMaxScaler


#딥러닝
from keras.models import Sequential
from keras.layers import Dense
from keras.backend import clear_session
from keras.optimizers import Adam

#사용할 데이터 셋
from keras.datasets import mnist

필요한 라이브러리는 다음과 같다

여기서 마지막줄의 mnist는 keras 에서 제공되는 이미지 학습 데이터셋이다

 

필요한 데이터 로딩

(x_train, y_train), (x_val, y_val) = mnist.load_data()

다음 코드로 mnist 이미지 데이터를 바로 불러올 수 있다

train_test_split으로 분리하지 않아도 된다

 

데이터를 로딩해서 형태를 확인해보면 다음과 같다

여기서 60000은 data의 수를 의미하며 28, 28은 픽셀 수를 의미한다

말하자면 28x28 픽셀의 데이터가 60000개 있다는 의미다

y데이터에는 해당 이미지가 어떤 것을 의미하는지 적혀있다

 

+

plt.imshow(x_train[0] , cmap=plt.cm.binary)
plt.show()

mnist의 0번 데이터는 다음과 같이 생겼다

 

 

데이터 전처리

 

데이터 펼치기

딥러닝 학습을 시키기 위해서는 데이터를 전처리 할 필요가 있다

먼저 (60000, 28, 28) 형태로 되어있는 3차원 xtrain을 2차원 형태로 바꿔주어야한다

 

x_train = x_train.reshape(60000, -1)
x_val = x_val.reshape(10000, -1)

다음과 같은 코드로 60000개의 행과 , 28x28 개의 컬럼을 가진 데이터로 바꾸어 줄 수 있다

28x28을 계산해서 적어주어도 되지만, -1을 넣어주면 알아서 계산해서 넣어준다

 

데이터 스케일링

x_train = x_train / 255.
x_val = x_val / 255.

각각의 데이터를 255로 나누어준다

255로 나누는 이유는 이미지의 색을 표현하는 수가 0~255로 이루어져 있기 때문이다

 

모델링

#입력 레이어의 컬럼 수
nfeatures = x_train.shape[1]

#메모리 초기화
clear_session()

#모델 선언
model = Sequential(Dense( 10  , input_shape = (nfeatures,), activation = 'softmax' ))

#모델 선언 , 히든레이어 3개 추가
model = Sequential( [ Dense ( 1000 , input_shape = (nfeatures ,) , activation = 'relu'),
                     Dense(500 , activation= 'relu'),
                     Dense(50 , activation= 'relu'),
                     Dense(10 , activation= 'softmax')
                    ])

#컴파일
model.compile(optimizer=Adam(learning_rate=0.001), loss= 'sparse_categorical_crossentropy' )

#학습, 히스토리 저장
history = model.fit(x_train, y_train, epochs = 20, validation_split=0.2).history

모델링 코드는 다중 분류 코드와 동일하다

10이 들어가는 이유는 m_nist데이터는 숫자 0~9까지의 데이터가 있기 때문이고

값이 모두 정수로 적혀있기 때문에 loss = 'sparse_categorical_crossentropy' 를 사용한다

히든레이어의 활성화 함수는 'relu'를 사용해주자

나머지는 원하는대로 수정해도 된다

 

예측 및 평가

pred = model.predict(x_val)
pred = pred.argmax(axis=1)

predict를 사용해 예측을 해주고 결과값을 argmax로 정리해주자

print(confusion_matrix(y_val, pred_1))
print(classification_report(y_val, pred_1))

평가는 분류이기 때문에 컨퓨전 매트릭스와 , classification_report을 사용해주면 된다

 

히스토리 확인하기
def history_plot(history):
    plt.figure(figsize=(10,6))
    plt.plot(history['loss'], label='train_err')
    plt.plot(history['val_loss'], label='val_err')

    plt.ylabel('Loss')
    plt.xlabel('Epoch')
    plt.legend()
    plt.grid()
    plt.show()
    
history_plot(history)

다음 코드로 학습 히스토리를 그래프로 확인 할 수 있다