Один из вариантов - использовать справочную таблицу для различных комбинаций.Это позволит вам затем определить вес любой используемой потери (например, кросс-энтропии) на основе дискретизированного прогноза (поскольку эта операция поиска не дифференцируема).
import tensorflow as tf
# This example is using eager execution, but the same code will work with graph
# building if you run it in a Session.
tf.enable_eager_execution()
penalties = tf.constant([
# Predicted 0
0., # Label 0
100., # Label 1
# Predicted 1
1., # Label 0
0. # Label 1
])
def compute_loss_weight(predicted, label):
sparse_predicted = tf.argmax(predicted, axis=-1)
sparse_label = tf.argmax(label, axis=-1)
offset = sparse_predicted * tf.shape(label, out_type=tf.int64)[-1] + sparse_label
return tf.gather(params=penalties, indices=offset)
print(compute_loss_weight(predicted=[1, 0], label=[0, 1])) # 100.
print(compute_loss_weight(predicted=[0, 1], label=[1, 0])) # 1.
# Also works on batches
print(compute_loss_weight(predicted=[[1, 0], [1, 0], [0, 1], [0, 1]],
label= [[0, 1], [1, 0], [0, 1], [1, 0]]))
# Prints [100. 0. 0. 1.]