在使用Tensorflow后端的Keras中,我的自定义损失函数是否可以访问当前的输入模式?
当前输入模式被定义为用于生成预测的输入向量。例如,考虑以下代码:X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42, shuffle=False)
。那么当前输入模式就是与y_train(在损失函数中称为y_true)相关联的当前X_train向量。
在设计自定义损失函数时,我打算优化/最小化一个需要访问当前输入模式的值,而不仅仅是当前预测。
我已经查看了https://github.com/fchollet/keras/blob/master/keras/losses.py
我还查看了“不仅仅是y_pred, y_true的成本函数?”
我还熟悉之前用于生成自定义损失函数的示例:
import keras.backend as Kdef customLoss(y_true,y_pred): return K.sum(K.log(y_true) - K.log(y_pred))
假设(y_true,y_pred)
是在其他地方定义的。我查看了源代码但没有找到答案,我想知道我是否需要自己定义当前输入模式,或者它是否已经可以被我的损失函数访问。
回答:
您可以将损失函数包装为内部函数,并将您的输入张量传递给它(这通常是在向损失函数传递额外参数时使用的做法)。
def custom_loss_wrapper(input_tensor): def custom_loss(y_true, y_pred): return K.binary_crossentropy(y_true, y_pred) + K.mean(input_tensor) return custom_lossinput_tensor = Input(shape=(10,))hidden = Dense(100, activation='relu')(input_tensor)out = Dense(1, activation='sigmoid')(hidden)model = Model(input_tensor, out)model.compile(loss=custom_loss_wrapper(input_tensor), optimizer='adam')
您可以验证input_tensor
和损失值(主要是K.mean(input_tensor)
部分)会随着不同的X
传递给模型而变化。
X = np.random.rand(1000, 10)y = np.random.randint(2, size=1000)model.test_on_batch(X, y) # => 1.1974642X *= 1000model.test_on_batch(X, y) # => 511.15466