带有附加参数的自定义度量函数

custom metric function with additional parameter

def custom_metric(y_prem):
   def score_func(y_true, y_pred):
      diff = y_pred - y_true
      return tf.reduce_sum(diff[y_prem>=y_pred])
   return score_func

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(32, input_shape=[len(X_train[0, :])], activation='tanh'),
    tf.keras.layers.Dense(8, input_shape=[len(X_train[0, :])], activation='linear'),
    tf.keras.layers.Dense(4, input_shape=[len(X_train[0, :])], activation='tanh'),
    tf.keras.layers.Dense(1, activation='relu'),
])
model.compile(optimizer='adam', loss='mean_squared_error', metrics=[custom_metric(y_prem)])
model.summary()
model.fit(X_train_minmax, y_train, epochs=30, batch_size=len(y_train))

y_prem 和 y_train 大小相同(50646)

我尝试定义此自定义度量函数,其中 y_prem 是预测大小的向量。我只想在 pred 低于 y_prem 的索引上对 pred 和 true 之间的差异求和,但是当我训练模型时,我收到一条错误消息:

File "C:/Users/zehavi kelman/PycharmProjects/Accident_predicting/simpego_test.py", line 61, in score_func  *
        return K.sum(diff[y_prem>=y_pred])

    ValueError: Shapes (50646, 1) and (50646, 50646) are incompatible

我该如何解决?

我不确定你想做什么,但我实现了一个不输出错误消息的可重现示例(注意 xy 形状):

import tensorflow as tf

x = tf.random.uniform(shape=[50646, 5], minval=0, maxval=1)
y = tf.random.uniform(shape=[50646, 1], minval=0, maxval=1)
y_prem = tf.random.uniform(shape=[50646, 1], minval=0, maxval=1)


def custom_metric(y_prem):
    def score_func(y_true, y_pred):
        diff = y_pred - y_true
        return tf.reduce_sum(diff[y_prem>=y_pred])
    return score_func

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(32, input_shape=[len(x[0, :])], activation='tanh'),
    tf.keras.layers.Dense(8, activation='linear'),
    tf.keras.layers.Dense(4, activation='tanh'),
    tf.keras.layers.Dense(1, activation='relu'),
])
model.compile(optimizer='adam', loss='mean_squared_error', metrics=[custom_metric(y_prem)])
model.summary()
model.fit(x, y, epochs=30, batch_size=len(y))