UnboundLocalError:分配前引用的局部变量“class_name”

Posted

技术标签:

【中文标题】UnboundLocalError:分配前引用的局部变量“class_name”【英文标题】:UnboundLocalError: local variable 'class_name' referenced before assignment 【发布时间】:2017-08-10 19:29:21 【问题描述】:

我是 Keras 和 Theano 的新手,现在尝试在 Keras 上实现我自己的损失函数。但是出现了这个错误。我认为问题在于我自己的损失函数,但我现在知道如何解决它。有人可以帮我解决这个问题吗?

import theano
import theano.tensor as T
def cost_estimation(y_true, y_pred):
    for k in range(10):
        d=T.log(1+T.exp((int(bool(y_true[k]==min(y_true)))*2-1)*(y_pred[k]-y_true[k])))
        cost=cost+d
    return  d  

keras 层:

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='relu'))

#loss=keras.losses.categorical_crossentropy,
model.compile(loss='cost_estimation',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs,
          verbose=1, validation_data=(x_test, y_test))

这是错误:

    ---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-6-d63101c47c94> in <module>()
    130 model.compile(loss='cost_estimation',
    131               optimizer='adam',
--> 132               metrics=['accuracy'])
    133 
    134 model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs,

/usr/local/lib/python2.7/dist-packages/keras/models.pyc in compile(self, optimizer, loss, metrics, sample_weight_mode, **kwargs)
    764                            metrics=metrics,
    765                            sample_weight_mode=sample_weight_mode,
--> 766                            **kwargs)
    767         self.optimizer = self.model.optimizer
    768         self.loss = self.model.loss

/usr/local/lib/python2.7/dist-packages/keras/engine/training.pyc in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, **kwargs)
    738             loss_functions = [losses.get(l) for l in loss]
    739         else:
--> 740             loss_function = losses.get(loss)
    741             loss_functions = [loss_function for _ in range(len(self.outputs))]
    742         self.loss_functions = loss_functions

/usr/local/lib/python2.7/dist-packages/keras/losses.pyc in get(identifier)
     88     if isinstance(identifier, six.string_types):
     89         identifier = str(identifier)
---> 90         return deserialize(identifier)
     91     elif callable(identifier):
     92         return identifier

/usr/local/lib/python2.7/dist-packages/keras/losses.pyc in deserialize(name, custom_objects)
     80                                     module_objects=globals(),
     81                                     custom_objects=custom_objects,
---> 82                                     printable_module_name='loss function')
     83 
     84 

/usr/local/lib/python2.7/dist-packages/keras/utils/generic_utils.pyc in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    155             if fn is None:
    156                 raise ValueError('Unknown ' + printable_module_name,
--> 157                                  ':' + class_name)
    158         return fn
    159     else:

UnboundLocalError: local variable 'class_name' referenced before assignment

【问题讨论】:

错误实际上在 Keras 代码中,而不是你的;它发生在试图显示您的错误时,我认为这是使用optimizer='adam'(在model.optimize()) - 它应该是'Adam' 【参考方案1】:

这似乎是 keras 代码库中的一个问题。似乎如果将 a 字符串传递给 loss 参数,则会出现此错误。要解决此问题,请通过 cost_estimation 自己丢失,这样你就可以避开那个代码分支。

model.compile(optimizer='rmsprop',
                  loss=cost_estimation, # not 'cost_estimation'
                  metrics=['accuracy'])

【讨论】:

以上是关于UnboundLocalError:分配前引用的局部变量“class_name”的主要内容,如果未能解决你的问题,请参考以下文章

UnboundLocalError:分配前引用的局部变量“公会”

分配前引用的 /blog/search/ 局部变量 'cd' 处的 UnboundLocalError

机器人框架:UnboundLocalError:分配前引用的局部变量“cellValue”

Django:UnboundLocalError:分配前引用的局部变量“公司”

UnboundLocalError:分配前引用的局部变量“class_name”

Q:'UnboundLocalError':分配前引用了局部变量'exitErr'