Вот как вы можете определить свою ошибку:
import tensorflow as tf
def custom_binary_error(y_true, y_pred):
y_true = tf.cast(y_true, tf.bool)
y_pred = tf.cast(y_pred, tf.bool)
xored = tf.logical_xor(y_true, y_pred)
notxored = tf.logical_not(xored)
sum_xored = tf.reduce_sum(tf.cast(xored, tf.float32))
sum_notxored = tf.reduce_sum(tf.cast(notxored, tf.float32))
return sum_xored / (sum_xored + sum_notxored)
Тестирование с двумя метками размером 6:
import tensorflow as tf
y_train_size = 6
y_train = [[1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]]
y_pred = tf.convert_to_tensor([[1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 1, 0]])
y = tf.placeholder(tf.int32, shape=(None, y_train_size))
error = custom_binary_error(y, y_pred)
with tf.Session() as sess:
res = sess.run(error, feed_dict={y:y_train})
print(res) # 0.25
Использование в Keras
:
import tensorflow as tf
import numpy as np
y_train_size = 6
def custom_binary_error(y_true, y_pred):
y_true = tf.cast(y_true, tf.bool)
y_pred = tf.cast(y_pred, tf.bool)
xored = tf.logical_xor(y_true, y_pred)
notxored = tf.logical_not(xored)
sum_xored = tf.reduce_sum(tf.cast(xored, tf.float32))
sum_notxored = tf.reduce_sum(tf.cast(notxored, tf.float32))
return sum_xored / (sum_xored + sum_notxored)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(y_train_size))
model.compile(optimizer=tf.keras.optimizers.SGD(0.01),
loss=[tf.keras.losses.MeanAbsoluteError()],
metrics=[custom_binary_error])
y_train = np.array([[1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]])
x_train = np.random.normal(size=(2, 2))
model.fit(x_train, y_train, epochs=2)
приведет к:
Epoch 1/2
2/2 [==============================] - 0s 23ms/sample - loss: 1.4097 - custom_binary_error: 0.5000
Epoch 2/2
2/2 [==============================] - 0s 328us/sample - loss: 1.4017 - custom_binary_error: 0.5000
Примечание
Если вы хотите точность вместо ошибка функция custom_binary_error()
должна вернуть
sum_notxored / (sum_xored + sum_notxored)