๐ข callback ํจ์ ์ค checkpoint ์ early stopping ์ ๋ํ ํ์ด์ง์ ๋๋ค.
# ๋ชจ๋ธ ์ ์ฅ
# ๊ฒฝ๋ก ์ค์
model_path = './data/num_model/model_{epoch:02d}_{val_accuracy:0.3f}.keras'
mc = ModelCheckpoint(filepath=model_path,
verbose = 1, # log ์ถ๋ ฅ
save_best_only = True, # ๋ชจ๋ธ์ด ์ต๊ณ ์ฑ๋ฅ์ ๊ฐฑ์ ํ ๋๋ง ์ ์ฅ (False: ๋ชจ๋ epoch ์ ์ฅ)
monitor = 'val_accuracy' # ๋ชจ๋ธ์ ์ฑ๋ฅํ์ธ ๊ธฐ์ค ์งํ
)
# ์กฐ๊ธฐํ์ต ์ค๋จ
es = EarlyStopping(monitor='val_accuracy',
verbose = 1,
patience = 10) # ๋ชจ๋ธ์ ์ฑ๋ฅ๊ฐ์ ์ ๊ธฐ๋ค๋ ค์ฃผ๋ ํ์ (๋ง์ฝ ์ฑ๋ฅ ๊ฐ์ ์ด ๋๋๋ค๋ฉด, ํ์ ๋ ๋๋ฆฌ๊ธฐ!)
model1 = Sequential()
model1.add(Input(shape=(28,28)))
model1.add(Flatten())
model1.add(Dense(units=64, activation='sigmoid'))
model1.add(Dense(units=128, activation='sigmoid'))
model1.add(Dense(units=256, activation='sigmoid'))
model1.add(Dense(units=128, activation='sigmoid'))
model1.add(Dense(units=64, activation='sigmoid'))
model1.add(Dense(units=10, activation='softmax'))
model1.compile(loss='sparse_categorical_crossentropy',
optimizer=SGD(),
metrics=['accuracy'])
m1 = model1.fit(X_train, y_train, epochs=200, validation_split=0.2,
callbacks = [mc,es]) # <- ์ด ๋ถ๋ถ์์ ์ ์ฉ !!!!!
model1.evaluate(X_test, y_test)
# best ๋ชจ๋ธ ๋ถ๋ฌ์ค๊ธฐ
from tensorflow.keras.models import load_model
best_model = load_model('./data/num_model/model_97_0.890.keras') # <- ์ด ๋ถ๋ถ !!!!
# ์ด๋ฏธ์ง ๋ถ๋ฌ์ค๊ธฐ
import PIL.Image as pimg
img = pimg.open('./data/5.png')
# shape ํ์ธ
np.array(img) # ํ์ฌ ์ปฌ๋ฌ(RGB) ๋ก ๋์ด ์์ด์, ํ๋ฐฑ์ผ๋ก ๋ฐ๊ฟ์ผํจ~!
# ์ปฌ๋ฌ์ด๋ฏธ์ง ํ๋ฐฑ์ผ๋ก ๋ณํ
img_b = img.convert('L')
img_np = np.array(img_b)
# shape ๋ณ๊ฒฝ
img_np = img_np.reshape(1,28,28)
# ์์ธก
best_model.predict(img_np)
# ๊ฐ class ์ ๋ํ ํ๋ฅ ๊ฐ
# array([[0.0084987 , 0.01119939, 0.23745966, 0.03384652, 0.00381436,
# 0.0770776 , 0.00616608, 0.00652381, 0.59920114, 0.01621275]],
# dtype=float32)
# ํ๋ฅ ๊ฐ์ ๊ธฐ๋ฐ์ผ๋ก ์ต๋๊ฐ๋ง ์ถ๋ ฅ
best_model.predict(img_np).argmax() # argmax: ์ต๋๊ฐ์ ์ธ๋ฑ์ค ์ถ๋ ฅ
# np.int64(8)
1500/1500 โโโโโโโโโโโโโโโโโโโโ 7s 5ms/step - accuracy: 0.9015 - loss: 0.3550 - val_accuracy: 0.8924 - val_loss: 0.3776
Epoch 119: early stopping1490/1500 โโโโโโโโโโโโโโโโโโโโ 0s 3ms/step - accuracy: 0.8893 - loss: 0.3978
Epoch 109: val_accuracy improved from 0.89583 to 0.89875, saving model to ./data/num_model/model_109_0.899.keras