복습 : 케라스 창시자에게 배우는 딥러닝

DeepLearning101_07_케라스완전정복_Code : 사용자 정의 '지표' 만들기

Aloha oe AI 2024. 9. 4. 22:16

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, 28
28)).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)
'''