Keras、Tensorflow:评估时如何在自定义层中设置断点(调试)?

Mr *_*les 11 python pycharm keras tensorflow

我只想在自定义图层内进行一些数字验证。

假设我们有一个非常简单的自定义层:

class test_layer(keras.layers.Layer):
    def __init__(self, **kwargs):
        super(test_layer, self).__init__(**kwargs)

    def build(self, input_shape):
        self.w = K.variable(1.)
        self._trainable_weights.append(self.w)
        super(test_layer, self).build(input_shape)

    def call(self, x, **kwargs):
        m = x * x            # Set break point here
        n = self.w * K.sqrt(x)
        return m + n
Run Code Online (Sandbox Code Playgroud)

和主程序:

import tensorflow as tf
import keras
import keras.backend as K

input = keras.layers.Input((100,1))
y = test_layer()(input)

model = keras.Model(input,y)
model.predict(np.ones((100,1)))
Run Code Online (Sandbox Code Playgroud)

如果我在该行设置断点调试m = x * x,程序在执行时会在此处暂停y = test_layer()(input),这是因为图形已构建,call()方法被调用。

但是当我model.predict()用来赋予它真正的价值,并且想看看它是否正常工作时,它不会在该行停顿m = x * x

我的问题是:

  1. 是否call()仅在构建计算图时调用方法?(喂实值时不会被调用?)

  2. 如何在图层内调试(或插入断点的位置)以在给它实际值输入时查看变量的值?

gol*_*enk 13

在 TensorFlow 2 中,您现在可以向 TensorFlow Keras 模型/层添加断点,包括在使用拟合、评估和预测方法时。但是,您必须model.run_eagerly = True 调用model.compile()断点处的调试器中可用的张量值之后添加。例如,

import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.keras.losses import BinaryCrossentropy
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam


class SimpleModel(Model):

    def __init__(self):
        super().__init__()
        self.dense0 = Dense(2)
        self.dense1 = Dense(1)

    def call(self, inputs):
        z = self.dense0(inputs)
        z = self.dense1(z)  # Breakpoint in IDE here. =====
        return z

x = tf.convert_to_tensor([[1, 2, 3], [4, 5, 6]], dtype=tf.float32)

model0 = SimpleModel()
y0 = model0.call(x)  # Values of z shown at breakpoint. =====

model1 = SimpleModel()
model1.run_eagerly = True
model1.compile(optimizer=Adam(), loss=BinaryCrossentropy())
y1 = model1.predict(x)  # Values of z *not* shown at breakpoint. =====

model2 = SimpleModel()
model2.compile(optimizer=Adam(), loss=BinaryCrossentropy())
model2.run_eagerly = True
y2 = model2.predict(x)  # Values of z shown at breakpoint. =====
Run Code Online (Sandbox Code Playgroud)

注意:这是在 TensorFlow 中测试的2.0.0-rc0


Nat*_*ion 3

  1. 是的。该call()方法仅用于构建计算图。

  2. 至于调试。我更喜欢使用TFDBG,这是推荐的tensorflow调试工具,尽管它不提供断点功能。

对于 Keras,您可以将这些行添加到脚本中以使用 TFDBG

import tf.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)
Run Code Online (Sandbox Code Playgroud)