Keras自定义损失功能:访问当前输入模式 [英] Keras custom loss function: Accessing current input pattern
问题描述
在Keras(具有Tensorflow后端)中,当前输入模式可用于我的自定义损失函数吗?
In Keras (with Tensorflow backend), is the current input pattern available to my custom loss function?
当前输入模式定义为用于产生预测的输入向量.例如,考虑以下内容:X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42, shuffle=False)
.然后,当前输入模式是与y_train相关联的当前X_train向量(在损失函数中称为y_true).
The current input pattern is defined as the input vector used to produce the prediction. For example, consider the following: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42, shuffle=False)
. Then the current input pattern is the current X_train vector associated with the y_train (which is termed y_true in the loss function).
在设计自定义损失函数时,我打算优化/最小化一个需要访问当前输入模式而不只是当前预测的值.
When designing a custom loss function, I intend to optimize/minimize a value that requires access to the current input pattern, not just the current prediction.
我已经浏览过 https://github.com /fchollet/keras/blob/master/keras/losses.py
我还查看了"不仅是y_pred,y_true的成本函数?"
我还熟悉前面的示例,以生成自定义的损失函数:
I am also familiar with previous examples to produce a customized loss function:
import keras.backend as K
def customLoss(y_true,y_pred):
return K.sum(K.log(y_true) - K.log(y_pred))
大概(y_true,y_pred)
在其他地方定义.我查看了源代码,但没有成功,我想知道我是否需要自己定义当前的输入模式,或者我的损失函数是否已经可以访问此输入模式.
Presumably (y_true,y_pred)
are defined elsewhere. I've taken a look through the source code without success and I'm wondering whether I need to define the current input pattern myself or whether this is already accessible to my loss function.
推荐答案
您可以将loss函数包装为内部函数,并将输入张量传递给它(如将其他参数传递给loss函数时通常这样做).>
You can wrap the loss function as a inner function and pass your input tensor to it (as commonly done when passing additional arguments to the loss function).
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_loss
input_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
传递给模型而改变.
You can verify that input_tensor
and the loss value (mostly, the K.mean(input_tensor)
part) will change as different X
is passed to the model.
X = np.random.rand(1000, 10)
y = np.random.randint(2, size=1000)
model.test_on_batch(X, y) # => 1.1974642
X *= 1000
model.test_on_batch(X, y) # => 511.15466
这篇关于Keras自定义损失功能:访问当前输入模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!