カスタム損失関数

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...