我正在尝试创建一个简单的加权损失函数。
比如说,我的输入尺寸为 100 * 5,输出尺寸也是 100 * 5。我还有一个相同尺寸的权重矩阵。
类似于以下内容:
import numpy as np
train_X = np.random.randn(100, 5)
train_Y = np.random.randn(100, 5)*0.01 + train_X
weights = np.random.randn(*train_X.shape)
定义自定义损失函数
def custom_loss_1(y_true, y_pred):
return K.mean(K.abs(y_true-y_pred)*weights)
定义模型
from keras.layers import Dense, Input
from keras import Model
import keras.backend as K
input_layer = Input(shape=(5,))
out = Dense(5)(input_layer)
model = Model(input_layer, out)
使用现有指标进行测试可以正常工作
model.compile('adam','mean_absolute_error')
model.fit(train_X, train_Y, epochs=1)
使用我们的自定义损失函数进行测试不起作用
model.compile('adam',custom_loss_1)
model.fit(train_X, train_Y, epochs=10)
它提供了以下堆栈跟踪:
InvalidArgumentError (see above for traceback): Incompatible shapes: [32,5] vs. [100,5]
[[Node: loss_9/dense_8_loss/mul = Mul[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](loss_9/dense_8_loss/Abs, loss_9/dense_8_loss/mul/y)]]
数字 32 是从哪里来的?
使用权重作为 Keras 张量测试损失函数
def custom_loss_2(y_true, y_pred):
return K.mean(K.abs(y_true-y_pred)*K.ones_like(y_true))
这个功能似乎可以完成这项工作。因此,可能表明 Keras 张量作为权重矩阵会起作用。因此,我创建了另一个版本的损失函数。
损失函数尝试3
from functools import partial
def custom_loss_3(y_true, y_pred, weights):
return K.mean(K.abs(y_true-y_pred)*K.variable(weights, dtype=y_true.dtype))
cl3 = partial(custom_loss_3, weights=weights)
使用 cl3 拟合数据会产生与上述相同的错误。
InvalidArgumentError (see above for traceback): Incompatible shapes: [32,5] vs. [100,5]
[[Node: loss_11/dense_8_loss/mul = Mul[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](loss_11/dense_8_loss/Abs, loss_11/dense_8_loss/Variable/read)]]
我想知道我错过了什么!我本可以在 Keras 中使用 sample_weight 的概念;但后来我不得不将我的输入重塑为 3d 矢量。
我认为这个自定义损失函数真的应该是微不足道的。