keras 中的自定义损失(tf 后端)需要张量操作
custom loss in keras (tf backend) requiring tensor manipulation
我的目标是预测2个点的坐标:[x1, x2]。 (2个点的y坐标是固定的)。
除了均方误差 (xtrue - xpred)**2
之外,我还想最小化斜率的误差:大约 (1/(x2true - x1true) - 1/(x2pred - x1pred))**2
.
这是我的实现,它引发了以下错误:
Shape must be rank 2 but is rank 1 for 'concat_1' (op: 'ConcatV2')
with input shapes: [?,?], [?], [].
--
自定义损失
def combo_mse():
def combo_loss(y_true, y_pred):
slope_true = 1/( y_true[:, 1] - y_true[:, 0] )
combo_true = K.concatenate([y_true, slope_true])
slope_pred = 1/( y_pred[:, 1] - y_pred[:, 0] )
combo_pred = K.concatenate([y_pred, slope_pred])
se = K.square( combo_pred - combo_true)
loss = K.mean(se, axis=-1)
return loss
return combo_loss
如何将输出张量 y_true
和 y_pred
、运行 一些操作切片并使用 K.concatenate()
创建新的张量以生成新的自定义损失函数?
您必须在串联之前更改 slope_true 和 slope_pred 的形状。下面的代码应该可以工作。原因是您的 slope tensors
是一维的,而您的 y_true
和 y_pred
张量是二维的。相同维度张量之间允许进行串联操作。
def combo_mse():
def combo_loss(y_true, y_pred):
slope_true = 1/( y_true[:, 1] - y_true[:, 0] )
slope_true = tf.reshape(slope_true, (-1, 1))
combo_true = K.concatenate([y_true, slope_true])
slope_pred = 1/( y_pred[:, 1] - y_pred[:, 0] )
slope_pred = tf.reshape(slope_pred, (-1, 1))
combo_pred = K.concatenate([y_pred, slope_pred])
mse = K.square( combo_pred - combo_true)
loss = K.mean(mse, axis=-1)
return loss
return combo_loss
我的目标是预测2个点的坐标:[x1, x2]。 (2个点的y坐标是固定的)。
除了均方误差 (xtrue - xpred)**2
之外,我还想最小化斜率的误差:大约 (1/(x2true - x1true) - 1/(x2pred - x1pred))**2
.
这是我的实现,它引发了以下错误:
Shape must be rank 2 but is rank 1 for 'concat_1' (op: 'ConcatV2')
with input shapes: [?,?], [?], [].
--
自定义损失
def combo_mse():
def combo_loss(y_true, y_pred):
slope_true = 1/( y_true[:, 1] - y_true[:, 0] )
combo_true = K.concatenate([y_true, slope_true])
slope_pred = 1/( y_pred[:, 1] - y_pred[:, 0] )
combo_pred = K.concatenate([y_pred, slope_pred])
se = K.square( combo_pred - combo_true)
loss = K.mean(se, axis=-1)
return loss
return combo_loss
如何将输出张量 y_true
和 y_pred
、运行 一些操作切片并使用 K.concatenate()
创建新的张量以生成新的自定义损失函数?
您必须在串联之前更改 slope_true 和 slope_pred 的形状。下面的代码应该可以工作。原因是您的 slope tensors
是一维的,而您的 y_true
和 y_pred
张量是二维的。相同维度张量之间允许进行串联操作。
def combo_mse():
def combo_loss(y_true, y_pred):
slope_true = 1/( y_true[:, 1] - y_true[:, 0] )
slope_true = tf.reshape(slope_true, (-1, 1))
combo_true = K.concatenate([y_true, slope_true])
slope_pred = 1/( y_pred[:, 1] - y_pred[:, 0] )
slope_pred = tf.reshape(slope_pred, (-1, 1))
combo_pred = K.concatenate([y_pred, slope_pred])
mse = K.square( combo_pred - combo_true)
loss = K.mean(mse, axis=-1)
return loss
return combo_loss