自定义损失函数在使用TensorFlow后端的Keras中遇到问题

我试图为一个三类分类问题定义一个损失函数,如下所示:

def func_loss(y_true, y_pred):    return -K.mean(K.prod(K.cast(K.argmax(y_pred, axis=1), K.floatx()) - 1.0, K.cast(K.argmax(y_true, axis=1), K.floatx()) - 1.0))

我的y看起来像这样:[[1,0,0], [0,1,0], [1,0,0], [0,0,1], ...]

直观上,我的三类标签是对类别”-1″、”0″和”+1″的一热编码。我希望最大化正确标记”+/-1″,最小化错误标记”+/-1″,并忽略所有”0″标签,无论它们是否正确。

当我使用这个损失函数编译模型时,我得到了以下结果:

Traceback (most recent call last):File "", line 1, in File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 547, in compile**kwargs)File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 622, in compilesample_weight, mask)File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 324, in weightedscore_array = fn(y_true, y_pred)File "", line 2, in func_lossFile "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 464, in prodaxis = _normalize_axis(axis, ndim(x))File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 435, in _normalize_axisif axis is not None and axis < 0:File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 547, in nonzeroraise TypeError("Using a tf.Tensor as a Python bool is not allowed. "TypeError: Using a tf.Tensor as a Python bool is not allowed. Use if t is not None: instead of if t: to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

我尝试对这个损失函数进行了一些小的调整,但每次编译模型时都会出现一些错误。我认为我可能对这个工作原理有一些基本的误解。有人能帮帮我吗?


编辑:新的损失函数:

def func_loss(y_true, y_pred):    return -K.mean((K.cast(K.argmax(y_pred, axis=1), K.floatx()) - 1.0 )* (K.cast(K.argmax(y_true, axis=1), K.floatx()) - 1.0))

回答:

我也在TensorFlow的GitHub上回复了你。

你已经编辑了损失函数,但现在你实际上得到了一个稍微不同的错误。

之前,错误发生在K.mean

File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 490, in meanaxis = _normalize_axis(axis, ndim(x))

现在,如你所见,错误发生在K.prod

File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 464, in prodaxis = _normalize_axis(axis, ndim(x))

然而,原因仍然是相同的:K.meanK.prod各接受一个张量,因此你传递的第二个Tensor被视为axis参数。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注