22.01.23 모델 학습 / 모델 서비스하
2022. 1. 23. 16:51ㆍ카테고리 없음
딥러닝 라이브러리 종류
텐서플로우 1.x
텐서플로우 2.x
현재 텐서플로우 2.7
과적합
1 epoch = 전체 1회독
과적합 막기 위한 방법
fit함수
epoch, batch
epoch : 한번전체1회독
batch : 한 줌 ( 가급적 큰 batch_size가 좋다)
verbose
검증 데이터 validation_data
shuffle - 학습데이터만 섞고, 검증데이터는 섞지 않음.
검증과정의 epoch, batch
데이터 불균형(고양이50장 개100장)을 위한 가중치
데이터 병렬 처리
콜백함수의 리스트
콜백함수 : 다른 코드에 의해 필요하면 실행되는 함수
실습1 fit함수 작성
import tensorflow as tf
import numpy as np
from tensorflow.keras import layers
np.random.seed(100)
def generate_data(batch_size, n_steps):
freq1, freq2, offsets1, offsets2 = np.random.rand(4,batch_size,1)
time = np.linspace(0, 1, n_steps)
series = 0.5 * np.sin((time - offsets1)*(freq1 * 10 + 10))
series += 0.1 * np.sin((time - offsets2)*(freq2 * 10 + 10))
series += 0.1 * (np.random.rand(batch_size,n_steps) - 0.5)
return series[...,np.newaxis].astype(np.float32)
def make_model(n_step):
model = tf.keras.models.Sequential()
model.add(layers.Flatten(input_shape= [n_step,]))
model.add(layers.Dense(1))
model.compile(optimizer = 'adam', loss = 'mse')
return model
n_step = 50
series = generate_data(10000, n_step +1)
x_train, y_train = series[:7000, :n_step],series[:7000,-1]
x_val, y_val = series[7000:9000, :n_step],series[7000:9000,-1]
x_test, y_test = series[9000:, :n_step],series[9000:,-1]
# 모델 구성
fcl_model = make_model(n_step)
# TODO: 지시사항을 보고 fit 함수의 매개변수를 설정하세요
hist=fcl_model.fit(
x=x_train, y=y_train, batch_size=100, epochs=20, verbose=2,shuffle=False,
validation_data=(x_val,y_val), initial_epoch=11,
validation_steps=10, validation_batch_size=50, validation_freq=5) # epochs=마지막세대, initial_epoch=첫세대
콜백함수
keras.callbacks.Callback클래스를 상속받아서 클래스 정의
내장콜백함수
EarlyStopping
EarlyStopping은 Loss나 Accuracy를 감시하고 있다가 더 이상 좋아지지 않으면 학습 종료
EarlyStopping 사용법
ModelCheckpoint
일정 주기마다 모델이나 모델의 가중치를 자동저장
TensorBoard 텐서보드
TensorBoard 사용하는 이유
TensorBoard 사용방법
실습2 사용자 정의 콜백함수
import tensorflow as tf
import numpy as np
from tensorflow.keras import layers
np.random.seed(100)
def generate_data(batch_size, n_steps):
freq1, freq2, offsets1, offsets2 = np.random.rand(4,batch_size,1)
time = np.linspace(0, 1, n_steps)
series = 0.5 * np.sin((time - offsets1)*(freq1 * 10 + 10))
series += 0.1 * np.sin((time - offsets2)*(freq2 * 10 + 10))
series += 0.1 * (np.random.rand(batch_size,n_steps) - 0.5)
return series[...,np.newaxis].astype(np.float32)
def make_model(n_step):
model = tf.keras.models.Sequential()
model.add(layers.SimpleRNN(20, return_sequences = True, input_shape = [None, 1]))
model.add(layers.SimpleRNN(20))
model.add(layers.Dense(1))
model.compile(optimizer = 'adam', loss = 'mse')
return model
n_step = 50
series = generate_data(10000, n_step +1)
x_train, y_train = series[:7000, :n_step],series[:7000,-1]
x_val, y_val = series[7000:9000, :n_step],series[7000:9000,-1]
x_test, y_test = series[9000:, :n_step],series[9000:,-1]
e = 20 # 채점을 위한 구성입니다. 변경하지 마세요
# TODO: 지시사항을 참고하여 콜백함수를 정의하세요
class MyCallback(tf.keras.callbacks.Callback):
def on_train_begin(self,logs=None):
print("Train begin")
def on_epoch_begin(self,epoch,logs=None):
print("%depoch begin" %(epoch))
def on_epoch_end(self,epoch,logs=None):
print("%depoch end" %(epoch))
def main():
deep_rnn = make_model(n_step)
myclass = MyCallback() # TODO: 정의한 콜백함수 클래스의 인스턴스를 만드세요
hist=deep_rnn.fit(
x=x_train, y=y_train, epochs=e,verbose=0,
validation_data=(x_val, y_val),validation_freq=2,callbacks=[myclass]) # TODO: 정의한 콜백함수를 리스트로 묶어 전달하세요
if __name__ == "__main__":
main()
실습3 내장 콜백함수
import os
import tensorflow as tf
from tensorflow.keras import layers, Sequential, Input
from tensorflow.keras.optimizers import Adam
import numpy as np
import matplotlib.pyplot as plt
SEED = 2021
def load_cifar10_dataset():
train_X = np.load("./dataset/cifar10_train_X.npy")
train_y = np.load("./dataset/cifar10_train_y.npy")
test_X = np.load("./dataset/cifar10_test_X.npy")
test_y = np.load("./dataset/cifar10_test_y.npy")
train_X, test_X = train_X / 255.0, test_X / 255.0
return train_X, train_y, test_X, test_y
def build_mlp_model(img_shape, num_classes=10):
model = Sequential()
model.add(Input(shape=img_shape))
model.add(layers.Flatten())
model.add(layers.Dense(2048, activation="relu"))
model.add(layers.Dense(1024, activation="relu"))
model.add(layers.Dense(256, activation="relu"))
model.add(layers.Dense(64, activation="relu"))
model.add(layers.Dense(num_classes, activation="softmax"))
return model
# EarlyStopping 콜백함수의 인스턴스를 cb_earlystop에 저장합니다.
# TODO: 지시사항 1을 참고하여 매개변수를 설정하세요
cb_earlystop = tf.keras.callbacks.EarlyStopping( monitor = 'val_loss' ,
mode = 'auto',
verbose = 1,
patience = 2 )
# ModelCheckpoint 콜백함수의 인스턴스를 cb_chkpnt 저장합니다.
# TODO: 지시사항 2을 참고하여 매개변수를 설정하세요
cb_chkpnt = tf.keras.callbacks.ModelCheckpoint( filepath = "./chkpnt/{epoch:04d}.ckpt",
monitor = 'val_loss',
mode = 'auto',
verbose = 1,
save_best_only = True,
save_weights_only = False,
save_freq = 'epoch' )
def main(epochs=10):
tf.random.set_seed(SEED)
np.random.seed(SEED)
train_X, train_y, test_X, test_y = load_cifar10_dataset()
img_shape = train_X[0].shape
print(img_shape)
optimizer = Adam(learning_rate=1e-3)
mlp_model = build_mlp_model(img_shape)
mlp_model.compile(optimizer=optimizer, loss="sparse_categorical_crossentropy", metrics=["accuracy"])
hist = mlp_model.fit(train_X, train_y, epochs=epochs, batch_size=64, validation_split=0.2, shuffle=True, verbose=1, callbacks=[cb_earlystop, cb_chkpnt])
# TODO: cb_earlystop와 cb_chkpnt를 리스트로 묶어 fit 함수의 callbacks 매개변수로 전달하세요.
return optimizer, hist
if __name__ == "__main__":
main()
실습4 텐서보드 사용하기
import tensorflow as tf
import numpy as np
from tensorflow.keras import layers
np.random.seed(100)
def generate_data(batch_size, n_steps):
freq1, freq2, offsets1, offsets2 = np.random.rand(4,batch_size,1)
time = np.linspace(0, 1, n_steps)
series = 0.5 * np.sin((time - offsets1)*(freq1 * 10 + 10))
series += 0.1 * np.sin((time - offsets2)*(freq2 * 10 + 10))
series += 0.1 * (np.random.rand(batch_size,n_steps) - 0.5)
return series[...,np.newaxis].astype(np.float32)
def make_model(n_step):
model = tf.keras.models.Sequential()
model.add(layers.SimpleRNN(20, return_sequences = True, input_shape = [None, 1]))
model.add(layers.SimpleRNN(20))
model.add(layers.Dense(1))
model.compile(optimizer = 'adam', loss = 'mse')
return model
n_step = 50
series = generate_data(10000, n_step +1)
x_train, y_train = series[:7000, :n_step],series[:7000,-1]
x_val, y_val = series[7000:9000, :n_step],series[7000:9000,-1]
x_test, y_test = series[9000:, :n_step],series[9000:,-1]
# TODO: 텐서보드 콜백함수를 정의하여 tb에 저장하세요
tb = tf.keras.callbacks.TensorBoard(log_dir="logs")
e = 20 #제거 혹은 변경 금지
def main():
deep_rnn = make_model(n_step)
hist=deep_rnn.fit(
x=x_train, y=y_train, epochs=e,
validation_data=(x_val, y_val),validation_freq=2,callbacks=[tb]) # TODO: 정의한 콜백함수를 리스트로 묶어 전달하세요
if __name__ == "__main__":
main()