2024.02.15
VGG 모델 실습2
* 지난 일차에 이어서 진행
데이터 증강 적용
60,000장의 데이터를 50% 증강한 90,000장 적용
import tensorflow as tf
fahion_mnist = tf.keras.datasets.fashion_mnist
(train_X, train_y), (test_X, test_y) = fahion_mnist.load_data()
print(train_X.shape)
print(train_y.shape)
print(test_X.shape)
print(test_y.shape)
# 전처리
train_X = train_X/ 255.0
test_X = test_X /255.0
train_X = train_X.reshape(-1,28,28,1) # 3d --> 4d
test_X = test_X.reshape(-1, 28,28,1)
image_gen = tf.keras.preprocessing.image.ImageDataGenerator(
# 필요 옵션을 상황에 맞게 적용
rotation_range=10,
zoom_range=0.10,
horizontal_flip=True,
vertical_flip=False,
)
augument_size = 30000
randidx = np.random.randint( train_X.shape[0], size= augument_size)
x_augumented = train_X[randidx].copy()
y_augumented = train_y[randidx].copy()
x_augumented = image_gen.flow(x_augumented, np.zeros(augugment_size),
batch_size = augument_size, shuffle = False).next()[0]
# 증강 데이터 추가
train_X = np.concatenate((train_X, x_augumented))
train_y = np.concatenate((train_y, y_augumented))
# 지난 일차 코드 그대로 적용
# 지난 일차 코드 참고
from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten, Dense, Dropout
model_vgg_fshion= tf.keras.Sequential([
# 생략
])
model_vgg_fshion.summary()
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
)
'ASAC 빅데이터전문가과정 > DL' 카테고리의 다른 글
ASAC 55일차_딥러닝 9일차 (0) | 2024.09.04 |
---|---|
ASAC 54일차_딥러닝 8일차 (0) | 2024.09.04 |
ASAC 51일차_딥러닝 6일차 (0) | 2024.09.02 |
ASAC 50일차_딥러닝 5일차 (0) | 2024.09.02 |
ASAC 49일차_딥러닝 4일차 (1) | 2024.09.02 |