【问题标题】:ValueError: None values not supported Keras Custom Loss Function in TensorflowValueError:无值不支持 Tensorflow 中的 Keras 自定义损失函数
【发布时间】:2017-01-23 20:29:31
【问题描述】:

我在使用 TensorFlow 编写的自定义目标函数的 Keras 顺序模型的拟合阶段遇到以下错误。

File "basicCNN.py", line 110, in <module>
callbacks=[TensorBoard(log_dir="./logs/{}".format(now))])
File "/home/garethjones/.local/lib/python2.7/site-packages/keras/models.py", line 664, in fit
sample_weight=sample_weight)
File "/home/garethjones/.local/lib/python2.7/site-packages/keras/engine/training.py", line 1115, in fit
self._make_train_function()
File "/home/garethjones/.local/lib/python2.7/site-packages/keras/engine/training.py", line 713, in _make_train_function
self.total_loss)
File "/home/garethjones/.local/lib/python2.7/site-packages/keras/optimizers.py", line 391, in get_updates
m_t = (self.beta_1 * m) + (1. - self.beta_1) * g
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 813, in binary_op_wrapper
y = ops.convert_to_tensor(y, dtype=x.dtype.base_dtype, name="y")
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 669, in convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/constant_op.py", line 176, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/constant_op.py", line 165, in constant
tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape))
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_util.py", line 360, in make_tensor_proto
raise ValueError("None values not supported.")

我的自定义函数是这个

def PAI(y_true, y_pred, k):
    '''
    Args:
        y_true (tensor): (batch x numCells)
        y_pred (tensor): (batch x numCells)
        k: The optimal number of hotspots
        area: 
    Returns:
        cfsRatio (tensor): The inverse of the percentage of crimes in hotspots per observation
    '''
    # Compute total crime for each obs
    totalCFS =  tf.reduce_sum(y_true,  axis=1)  # batch x 1
    # Flatten for gather
    flatTruth = tf.reshape(y_true, [-1])  # 1 x batch * numCells
    # Select top candidate cells
    _, predHS = tf.nn.top_k(y_true, k)
    # Convert indices for gather
    predHSFlat = tf.range(0, tf.shape(y_true)[0]) * tf.shape(y_true)[1] + predHS)
    # Map hotspot predictions to crimes
    hsCFS = tf.gather(flatTruth, predHSFlat)
    # Number of crimes commited in hotspots
    hsCFSsum = tf.reduce_sum(hsCFS, axis=1) # batch x 1
    # Ratio of crimes committed in hotspots and inverted for minimization
    cfsRatio = tf.truediv(1.0, tf.truediv(hsCFSsum, totalCFS))

    return cfsRatio

当我有一个交互式会话时,我可以运行它。该函数主要依赖于来自这个 Tensorflow 问题 https://github.com/tensorflow/tensorflow/issues/206 的代码。

【问题讨论】:

  • 我遇到了类似的问题。你找到解决办法了吗?

标签: python tensorflow neural-network keras


【解决方案1】:

自定义拟合函数失败的原因有很多。能够单步调试您的 TensorFlow 代码不仅是查找此错误的最快方法,而且是您将来可能遇到的任意数量的错误。

== 编辑 ==

这是 3 年前写的。 TensorFlow 只是在编写时才进行懒惰评估。然后,它可以作为任何类似问题的通用解决方案。

== 原创 ==

Keras 中的自定义损失函数仅在调用时构建图(如果使用 TensorFlow 作为后端)。正如您所注意到的,在调用 fit() 之前,TensorFlow 代码实际上并未运行(图表未执行)。

因此您不能使用典型的调试器来单步调试代码并找到有问题的行,或者查看数据。

一些调试技巧:

  • 将张量值打印到控制台

使用 tf.Print 用控制台输出包装执行,例如:

total = tf.Print(total, [total], 'total', summarize=10)

打印张量total的前10个值。

  • 删除计算依赖项

请注意,第一个值是计算中使用的值(分配给方程的 LHS)。第二个参数是打印的。

所以要测试 TF 计算并查看输出,请将它们作为第二个参数传递,这样它们就不会在调试期间影响输出。

从返回的值中消除变量,以找到有问题的计算。例如:

knownGoodValue = K.sum(tf.square(y_true - y_pred))  # any expr known to work
printExpr = tf.reshape(y_true, [-1])  # 1 x batch * numCells
knownGoodValue = tf.Print(knownGoodValue, [printExpr], 'flatTruth', summarize=10)

return knownGoodValue

这会打印并返回一些您知道有效的表达式,同时允许通过包装测试表达式来测试/打印任何 TF expr,而无需实际使用其结果。

  • 使用 TF 调试器

https://github.com/tensorflow/tensorflow/tree/master/tensorflow/python/debug

可以通过在 fit 函数之前添加以下代码来调用 TensorFlow 调试器:

import keras.backend as K
from tensorflow.python import debug as tf_debug
sess = K.get_session()
sess = tf_debug.LocalCLIDebugWrapperSession(sess)
K.set_session(sess)

然后它会在调用 fit() 时呈现一个类似 GDB 的命令行界面。

【讨论】:

    猜你喜欢
    • 2018-10-28
    • 2017-12-29
    • 2020-12-24
    • 2022-06-13
    • 2020-10-14
    • 2020-10-21
    • 1970-01-01
    • 2020-12-19
    • 2017-12-18
    相关资源
    最近更新 更多