【问题标题】:Debug into a custom metrics function in Keras/Tensorflow (in Pycharm)?在 Keras/Tensorflow(在 Pycharm 中)中调试自定义指标函数?
【发布时间】:2021-09-09 17:50:34
【问题描述】:

我创建了一个简单的 ConfusionMatrix 自定义指标,但在张量转换中遇到了问题。如果我可以设置断点,它将加快修复速度。但是 PyCharm 不遵守断点。

这里是代码

def multiConfusion(expectsIn, actsIn):
  expects = tf.keras.backend.eval(expectsIn)  # Error occurs here
  acts = tf.keras.backend.eval(actsIn)
  classes = sorted(list(set(expects).union(set(acts))))
  
  from collections import defaultdict
  mx = defaultdict(lambda: defaultdict(int))
  for e,a in list(zip(expects,acts)):
    mx[e][a] += 1
  hdr = "Exp/Act" + ''.join([ f'\t\t{lab}' for lab in classes])
  ll = '\n'.join([
                  '\t\t\t' + '\t\t'.join([ str(mx[e][a]) for k,a in list(mx[e].items())])
                  for e in classes
                 ])
  mat =  f"{hdr}\n{ll}"
  print(mat)
  return mat

def confusionMat(x,y,num_classes=NClasses):
      from tensorflow import math as tfmath
      cmat = None
      if NClasses == 2:
        cmat = binaryConfusion(x,y)
      else:
        cmat = multiConfusion(x,y) # Breakpoint set here but gets skipped
      print(repr(cmat))
      return cmat

model.compile(loss="categorical_crossentropy", optimizer=opt, 
              metrics=[confusionMat,"accuracy"])

我对尝试重新启用调试器的一些想法:

  • 设置单线程模式

tf.config.threading.set_inter_op_parallelism_threads(1)

  • 设置急切执行模式

vgg_model.run_eagerly = True

但仍然不遵守断点。有什么想法吗?

更新我已经测试/更新/扩展了上面的代码。它确实会正确生成混淆矩阵

当直接使用常量 Tensorflow Tensor 调用时,调试代码可以正常工作。

但是当代码通过 Tensorflow model 训练中的 metrics 机制调用时,我无法做任何事情来激活调试器。 (通过 model.fit())

【问题讨论】:

  • @bad_coder Thx - 我现在尝试了许多不同的转换(使用或不使用 keras):在 TF 训练循环的上下文中进行调试只是不想发生。仅针对 tensorflow 张量运行相同的代码(但在训练时不是)

标签: python tensorflow keras pycharm


【解决方案1】:

为了让您的断点受到尊重,请在开头添加以下行:

tf.config.run_functions_eagerly(True)

它将使 tensorflow 几乎所有东西都急切地运行,除了tf.data 转换管道。

【讨论】:

  • 这听起来很有希望——谢谢!将立即投票并检查它是否真的很快解决
  • 似乎没有做这项工作:断点仍然没有得到尊重。但是我会留下赞成票,因为您的提示可能对其他人/其他情况很有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-28
  • 2017-12-29
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多