Recreating code 7-18 from book "Deep Learning with Python" by François Chollet
CODE 7-18 : Metric 클래스 상속하여 사용자 정의 지표 구하기
Import Tools
'''python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist
'''
Define Functions
'''python
defining_model
def get_mnist_model():
inputs = keras.Input(shape=(28*28,))
features = layers.Dense(512, activation="relu")(inputs)
features = layers.Dropout(0.5)(features)
outputs = layers.Dense(10, activation="softmax")(features)
model = keras.Model(inputs, outputs)
return model
defining_metrics
class RootMeanSquaredError(keras.metrics.Metric): # metric클래스를 상속합니다
def init(self, name="", *kwargs):
super().init(name=name, *kwargs)
self.mse_sum = self.add_weight(name="mse_sum", initializer="zeros")
self.total_samples = self.add_weight(
name="total_samples", initializer="zeros", dtype="int32")
# 생성자에서 상태 변수를 정의합니다. 층과 마찬가지로 add_weight()매서드를 사용합니다
def update_state(self, y_true, y_pred, sample_weight=None):
y_true = tf.one_hot(y_true, depth=tf.shape(y_pred)[1])
mse = tf.reduce_sum(tf.square(y_true - y_pred))
self.mse_sum.assign_add(mse)
num_samples = tf.shape(y_pred)[0]
self.total_samples.assign_add(num_samples)
def result(self):
return tf.sqrt(self.mse_sum / tf.cast(self.total_samples, tf.float32))
def reset_state(self):
self.mse_sum.assign(0.)
self.total_samples.assign(0)
# 객체 다시 생성하지 않고 상태 초기화하는 방법 제공!
# 왜 ? 초기화 해야 지표 객체 1개로 서로 다른 훈련 반복, 평가 등 모두 사용 할 수 있음
# 근데 : 초기화 하지 않으면 이 클래스에 이전 데이터 영향을 주나? 클래스의 메모리란 뭐지?
'''
Let's See How it Works!
'''python
데이터 불러오기
(images, labels),(test_images, test_labels) = mnist.load_data()
데이터 전처리
images = images.reshape((60000, 2828)).astype("float32") / 255
test_images = test_images.reshape((10000, 2828)).astype("float32") / 255
train 과 validation 데이터 나누기
train_images, val_images = images[10000:], images[:10000]
train_labels, val_labels = labels[10000:], labels[:10000]
shape check
print(f" 훈련_X : {train_images.shape}")
print(f" 검증_X : {val_images.shape}")
print(f" 텟트_X : {test_images.shape}")
print(f" 훈련_y : {train_labels.shape}")
print(f" 검증_y : {val_labels.shape}")
print(f" 텟트_y : {test_labels.shape}")
'''
Set Model, Train, Validate, Evaluate
'''python
model = get_mnist_model()
model.compile(optimizer="rmsprop",
loss="sparse_categorical_crossentropy",
metrics=["accuracy",RootMeanSquaredError])
# 상위 사용자 정의 '지표'(RootMeanSquaredError), 표준위크플로 모델설계 'metric(지표)'부분에 추가함
model.fit(train_images, train_labels,
epochs=3,
validation_data=(val_images,val_labels))
test_metrics = model.evaluate(test_images, test_labels)
'''
'복습 : 케라스 창시자에게 배우는 딥러닝' 카테고리의 다른 글
[NLP] 자연어처리와 친해지기 : 머신러닝과 딥러닝 모델은 코드적으로 어떻게 다를까? (feat. 네이버 영화 리뷰 데이터(nsmc) 감성 분석) (2) | 2024.10.16 |
---|---|
DeepLearning101_07_케라스완전정복_워크플로우란? (0) | 2024.09.03 |
DeepLearning101_06_일반적이 머신러닝 워크플로우 (4) | 2024.09.02 |