我自己也遇到过这个问题。您想针对 x 中的信息对指标执行 groupby 操作,但该信息不在 y 或 y_hat 中。
度量就像损失一样,它们只能看到 y_true 和 y_hat。由于有关 U 和 I 的信息未提供给损失/指标,因此您没有足够的信息来构建执行此分组的自定义指标。
解决此问题的一个困难方法是围绕您的真实模型构建一个模型,该模型序列化 y_hat、U 和 I。然后您的自定义指标可以反序列化 y_hat、U 和 I,并以分组方式存储信息。如果将每个项目的 AUC 定义为每次交互的 AUC 的平均值,那么它就足够紧凑,可以存储在内存中。如果没有,那么您可能需要在自定义指标中将信息存储到磁盘。我建议使用 gdbm,它在 python 中有一个简单的界面。
def serialize(u, i, y):
return tf.concat(
[tf.reshape(u, [-1]),
tf.reshape(i, [-1]),
tf.reshape(y, [-1])])
def deserialize(s):
u = tf.reshape(s[:xyz], [..., ..., ...])
i = tf.reshape(s[xyz, abc], [..., ..., ...])
y = tf.reshape(s[abc:], [..., ..., ...])
return u, i, y
def AUCPerItem(tf.keras.metrics.Metric):
def __init__(self):
self.auc_per_item = {}
def update(y_true, y_pred):
for serialized_example in y_pred:
u, i, y = deserialize(serialized_example)
# do calcualtions and store in self.auc_per_item
# Model takes U and I as inputs, and outputs y_hat.
model = get_and_train_model()
input_u = tf.keras.Input(...)
input_i = tf.keras.Input(...)
y_hat = model(input_u, input_i)
output = serialize(input_u, input_i, y_hat)
wrapper = tf.keras.Model([input_u, input_i], output)