评估TF操作中的TF模型会引发错误

时间:2019-06-16 02:10:26

标签: tensorflow google-colaboratory

我正在使用TensorFlow2。我正在尝试优化一个功能,该功能使用了训练有素的张量流模型(毒药)。

@tf.function
def totalloss(x):
    xt = tf.multiply(x, (1.0 - m)) + tf.multiply(m, d)
    label = targetlabel*np.ones(xt.shape[0])
    loss1 = poison.evaluate(xt, label, steps=1)
    loss2 = tf.linalg.norm(m, 1)
    return loss1 + loss2

我无法执行此功能,但是,当我注释@ tf.function行时,该功能有效!

我需要将此函数用作张量流op,以便优化“ m”和“ d”。

  

值错误:未知图形。正在中止。

这就是我定义模型和变量的方式:

# mask
m = tf.Variable(tf.zeros(shape=(1, 784)), name="m")
d = tf.Variable(tf.zeros(shape=(1, 784)), name="d")
# target
targetlabel = 6
poison = fcn()
poison.load_weights("MNISTP.h5")
adam = tf.keras.optimizers.Adam(lr=.002, decay=1e-6)
poison.compile(optimizer=adam, loss=tf.losses.sparse_categorical_crossentropy)

这是我稍后调用该函数的方式:(执行此行会导致下面列出的错误。但是,如果我在@ tf.function行中注释掉,则此命令有效!)

loss = totalloss(ptestdata)

这是整个回溯调用:

ValueError: in converted code:

    <ipython-input-52-4841ad87022f>:5 totalloss  *
        loss1 = poison.evaluate(xt, label, steps=1)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:746 evaluate
        use_multiprocessing=use_multiprocessing)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training_arrays.py:693 evaluate
        callbacks=callbacks)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training_arrays.py:187 model_iteration
        f = _make_execution_function(model, mode)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training_arrays.py:555 _make_execution_function
        return model._make_execution_function(mode)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:2034 _make_execution_function
        self._make_test_function()
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:2010 _make_test_function
        **self._function_kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/backend.py:3544 function
        return EagerExecutionFunction(inputs, outputs, updates=updates, name=name)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/backend.py:3429 __init__
        raise ValueError('Unknown graph. Aborting.')

    ValueError: Unknown graph. Aborting. 

1 个答案:

答案 0 :(得分:2)

@tf.function装饰器的目的是将用Python编写的Tensorflow操作转换为Tensorflow图,以实现更好的性能。当您尝试对序列化图形使用预训练模型时,可能会出现错误。因此,装饰器无法进行图形到图形的转换。

我在这里报告了此错误:https://github.com/tensorflow/tensorflow/issues/33997

(临时)解决方案是将损失函数分成两个小函数。装饰器仅应在不包含预训练模型的功能中使用。这样,您仍然可以在其他操作中获得更好的性能,但不能使用部分预训练模型。

例如:

@tf.function
def _other_ops(x):
    xt = tf.multiply(x, (1.0 - m)) + tf.multiply(m, d)
    label = targetlabel * np.ones(xt.shape[0])
    loss2 = tf.linalg.norm(m, 1)

    return xt, label, loss2

def total_loss(x):
    xt, label, loss2 = _other_ops(x)
    loss1 = poison.evaluate(xt, label, steps=1)

    return loss1 + loss2