⚙️ VGG Model
📌 데이터 준비
import tensorflow as tf
fahion_mnist = tf.keras.datasets.fashion_mnist
(train_X, train_y), (test_X, test_y) = fahion_mnist.load_data()
train_X = train_X / 255.0
test_X = test_X / 255.0
train_X = train_X.reshape(-1,28,28,1)
test_X = test_X.reshape(-1,28,28,1)
📌 데이터 펌핑하기
import numpy as np
augment_size = 30000
randidx = np.random.randint(train_X.shape[0], size=augment_size)
# 학습 데이터를 랜덤으로 가져와서 펌핑하기
x_augmented = train_X[randidx].copy()
y_augmented = train_y[randidx].copy()
x_augmented = image_gen.flow(x_augmented,
np.zeros(augment_size),
batch_size = augment_size,
shuffle = False).next()[0]
# 펌핑된 데이터를 전체 데이터에 추가
train_X = np.concatenate((train_X, x_augmented))
train_y = np.concatenate((train_y, y_augmented))
📌 VGG 모델 만들기
model_vgg_fshion= tf.keras.Sequential([
Conv2D(input_shape = (28,28,1), kernel_size = (3,3), filters = 64, padding = "same", activation = "relu"),
Conv2D(kernel_size = (3,3), filters = 64, padding = "same", activation = "relu"),
MaxPool2D(pool_size = (2,2), strides = (2,2)),
Conv2D(kernel_size = (3,3), filters = 128, padding = "same", activation = "relu"),
Conv2D(kernel_size = (3,3), filters = 128, padding = "same", activation = "relu"),
MaxPool2D(pool_size = (2,2), strides = (2,2)),
Conv2D(kernel_size = (3,3), filters = 256, padding = "same", activation = "relu"),
Conv2D(kernel_size = (3,3), filters = 256, padding = "same", activation = "relu"),
Conv2D(kernel_size = (3,3), filters = 256, padding = "same", activation = "relu"),
MaxPool2D(pool_size = (2,2), strides = (2,2)),
# 분류를 위한 FNN
# 특징에 대한 Flatten 작업
Flatten(),
# 분류용 HL
Dense(units = 512, activation = "relu"),
Dropout(rate = 0.2),
Dense(units = 256, activation = "relu"),
Dropout(rate = 0.2),
# + Layer를 추가를 하거나..
# 출력용
Dense(units = 10, activation = "softmax"),
])
# 모델 저장 및 옵션
import os
cp_path = "training/cp-{epoch:04d}.ckpt"
cp_dir = os.path.dirname(cp_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(
cp_path,
verbose = 1,
save_weights_only = True
)
es_callback = tf.keras.callbacks.EarlyStopping(
monitor = "val_loss",
patience = 10
)
📌 생성해둔 이미지로 학습하기
model_vgg_fshion.compile(
optimizer = tf.keras.optimizers.Adam(),
loss = "sparse_categorical_crossentropy",
metrics = ["accuracy"]
)
model_vgg_fshion.fit(train_X, train_y,
epochs = 100,
validation_split = 0.25,
batch_size = 1024,
callbacks = [cp_callback,es_callback]
)
📌 이미지를 학습시에 생성해서 사용하기
generator= tf.keras.preprocessing.image.ImageDataGenerator(
rotation_range = 10,
zoom_range = 0.10,
horizontal_flip = True,
vertical_flip = False
)
train_batches = generator.flow(train_X, train_y, batch_size = 256)
val_batches = generator.flow(test_X, test_y, batch_size = 256)
history = model_vgg_fshion.fit_generator(
train_batches,
epochs = 20,
validation_data = val_batches,
use_multiprocessing = True
)