首页 > 解决方案 > AttributeError:“模型”对象没有属性“目标”

问题描述

当我运行以下代码时,出现错误。

def __init__(self, model, sess, loss_fn=None):
    """
    To generate the White-box Attack Agent.
    :param model: the target model which should have the input tensor, the target tensor and the loss tensor.
    :param sess: the tensorflow session.
    :param loss_fn: None if using original loss of the model.
          
    """
    self.model = model
    self.input_tensor = model.inputs[0]
    self.output_tensor = model.outputs[0]
    self.target_tensor = model.targets[0]
    self._sample_weights = model.sample_weights[0]
    if loss_fn is None:
        self.loss_tensor = model.total_loss
        self.gradient_tensor = K.gradients(self.loss_tensor, self.input_tensor)[0]
    else:
        self.set_loss_function(loss_fn)
    self.sess = sess

错误:

self.target_tensor = model.targets[0]  ,   AttributeError: 'Model' object has no attribute 'targets'

我正在使用 Tensorflow 1.14.0、keras 2.2.4-tf 和 python 3.6.13。我该如何解决这个问题?

谢谢

标签: tensorflowtf.keras

解决方案


您的函数使用的model参数显然是在谈论一个不属于默认 Keras 或 Tensorflow 的独特类。您需要确保model传递给函数的对象是相应类的实例。或者,或者,您可以通过执行以下操作来临时装配它:


# whatever code instantiates the `model` would be here
...
...

model.targets = [ "targets of an appropriate structure and type go here" ]

然后,当您将该model对象传递给函数时,它将具有targets要访问的属性。但最好一开始就使用正确的对象。

或者,第三个选项:只需注释掉有问题的行,并希望它实际上没有在任何地方使用(如果它被设置,它可能在某个地方或其他地方使用过)。

def __init__(self, model, sess, loss_fn=None):
    """
    To generate the White-box Attack Agent.
    :param model: the target model which should have the input tensor, the target tensor and the loss tensor.
    :param sess: the tensorflow session.
    :param loss_fn: None if using original loss of the model.
          
    """
    self.model = model
    self.input_tensor = model.inputs[0]
    self.output_tensor = model.outputs[0]
    #self.target_tensor = model.targets[0]
    self._sample_weights = model.sample_weights[0]
    if loss_fn is None:
        self.loss_tensor = model.total_loss
        self.gradient_tensor = K.gradients(self.loss_tensor, self.input_tensor)[0]
    else:
        self.set_loss_function(loss_fn)
    self.sess = sess

推荐阅读