실습
- Fashion_mnist 데이터를 기반으로 분류 학습을 수행 해라
데이터 로드
'''
라이브러리들을 불러오자.
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random as rd
from sklearn.metrics import accuracy_score
import tensorflow as tf
from tensorflow import keras
(train_x, train_y), (test_x, test_y) = keras.datasets.fashion_mnist.load_data()
Scaling
max_n , min_n = train_x.max() , train_x.min()
train_x = (train_x - max_n) / (max_n - min_n)
test_x = (test_x - max_n) / (max_n - min_n)
reshape
train_x = train_x.reshape(train_x.shape[0] ,h,w,1)
test_x = test_x.reshape(test_x.shape[0],h,w,1)
print(train_x.shape , train_y.shape , test_x.shape , test_y.shape)
one-hot-encoding
from tensorflow.keras.utils import to_categorical
class_n = len(np.unique(train_y))
class_n
train_y = to_categorical(train_y , class_n)
test_y = to_categorical(test_y , class_n)
model
from tensorflow.keras.backend import clear_session
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Flatten, Conv2D, MaxPool2D
from tensorflow.keras.callbacks import EarlyStopping
from keras.src.engine.training import optimizer
clear_session()
il = Input(shape =(28,28,1))
hl = Conv2D(
filters = 32,
kernel_size = (3,3),
strides= (1,1),
padding = 'same',
activation = 'relu'
)(il)
hl = keras.layers.BatchNormalization()(hl)
hl = Conv2D(
filters = 32,
kernel_size = (3,3),
strides= (1,1),
padding = 'same',
activation = 'relu'
)(hl)
hl = keras.layers.BatchNormalization()(hl)
hl = MaxPool2D(pool_size = (2,2),strides = (2,2))(hl)
hl = keras.layers.Dropout(0.25)(hl)
hl = Conv2D(filters = 64,
kernel_size = (3,3),
strides= (1,1),
padding = 'same',
activation = 'relu'
)(hl)
hl = keras.layers.BatchNormalization()(hl)
hl = Conv2D(filters = 64,
kernel_size = (3,3),
strides= (1,1),
padding = 'same',
activation = 'relu')(hl)
hl = keras.layers.BatchNormalization()(hl)
hl = MaxPool2D(pool_size = (2,2) , strides=(3,3))(hl)
hl = keras.layers.Dropout(0.25)(hl)
hl = Flatten()(hl)
hl = Dense(512 , activation = 'relu')(hl)
hl = keras.layers.BatchNormalization()(hl)
ol = Dense(10 , activation = 'softmax')(hl)
model = Model(il , ol)
model.compile(optimizer = 'adam' , loss = 'categorical_crossentropy' , metrics = ['accuracy'])
model setting
es = EarlyStopping(monitor = 'val_loss',
min_delta = 0,
patience = 3,
verbose = 1,
restore_best_weights = True)
hist = model.fit(train_x , train_y , validation_split=0.2 , epochs = 10000 , verbose = 1 ,callbacks = [es])
시각화
plt.figure(figsize=(10, 5))
plt.plot(hist.history['accuracy'])
plt.plot(hist.history['val_accuracy'])
plt.title('Accuracy : Training vs Validation')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Training', 'Validation'], loc=0)
plt.show()
plt.figure(figsize=(10, 5))
plt.plot(hist.history['loss'])
plt.plot(hist.history['val_loss'])
plt.title('Loss : Training vs Validation')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Training', 'Validation'], loc=0)
plt.show()