사용자 정의 손실 함수

Python으로 배우는 금융 분야 Machine Learning

Nathan George

Data Science Professor

방향 불일치

Python으로 배우는 금융 분야 Machine Learning

방향 페널티를 포함한 MSE

예측과 실제값의 방향이 일치하는 경우:

  • $ \sum(y - \hat{y})^2$

불일치하는 경우:

  • $\sum (y - \hat{y})^2 * \text{penalty} $
Python으로 배우는 금융 분야 Machine Learning

사용자 정의 손실 함수 구현

import tensorflow as tf
Python으로 배우는 금융 분야 Machine Learning

함수 생성

import tensorflow as tf

# create loss function def mean_squared_error(y_true, y_pred):
Python으로 배우는 금융 분야 Machine Learning

평균 제곱 오차 손실

import tensorflow as tf

# create loss function
def mean_squared_error(y_true, y_pred):

loss = tf.square(y_true - y_pred) return tf.reduce_mean(loss, axis=-1)
Python으로 배우는 금융 분야 Machine Learning

Keras에 사용자 정의 손실 추가

import tensorflow as tf

# create loss function
def mean_squared_error(y_true, y_pred):
    loss = tf.square(y_true - y_pred)
    return tf.reduce_mean(loss, axis=-1)

# enable use of loss with keras import keras.losses keras.losses.mean_squared_error = mean_squared_error
# fit the model with our mse loss function
model.compile(optimizer='adam', loss=mean_squared_error)
history = model.fit(scaled_train_features, train_targets, epochs=50)
Python으로 배우는 금융 분야 Machine Learning

올바른 방향 확인

tf.less(y_true * y_pred, 0)

올바른 방향:

  • 음수 * 음수 = 양수
  • 양수 * 양수 = 양수

잘못된 방향:

  • 음수 * 양수 = 음수
  • 양수 * 음수 = 음수
Python으로 배우는 금융 분야 Machine Learning

tf.where() 사용

# create loss function
def sign_penalty(y_true, y_pred):
    penalty = 10.
    loss = tf.where(tf.less(y_true * y_pred, 0), 
                    penalty * tf.square(y_true - y_pred), 
                    tf.square(y_true - y_pred))
Python으로 배우는 금융 분야 Machine Learning

전체 코드 통합

# create loss function
def sign_penalty(y_true, y_pred):
    penalty = 100.
    loss = tf.where(tf.less(y_true * y_pred, 0),
                    penalty * tf.square(y_true - y_pred), 
                    tf.square(y_true - y_pred))

    return tf.reduce_mean(loss, axis=-1)

# enable use of loss with keras keras.losses.sign_penalty = sign_penalty
Python으로 배우는 금융 분야 Machine Learning

사용자 정의 손실 적용

# create the model
model = Sequential()
model.add(Dense(50,
                input_dim=scaled_train_features.shape[1],
                activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(1, activation='linear'))
# fit the model with our custom 'sign_penalty' loss function
model.compile(optimizer='adam', loss=sign_penalty)
history = model.fit(scaled_train_features, train_targets, epochs=50)
Python으로 배우는 금융 분야 Machine Learning

나비넥타이 형태

train_preds = model.predict(scaled_train_features)
# scatter the predictions vs actual
plt.scatter(train_preds, train_targets)
plt.xlabel('predictions')
plt.ylabel('actual')
plt.show()

나비넥타이 플롯

Python으로 배우는 금융 분야 Machine Learning

손실 함수를 직접 만들어 보세요!

Python으로 배우는 금융 분야 Machine Learning

Preparing Video For Download...