在Python 3.7中使用Dropout函数(Keras)时,如何解决“ UnboundLocalError”问题

时间:2019-05-09 15:34:19

标签: tensorflow keras python-3.7

每当我尝试在Python 3.7中使用Keras UnboundLocalError: local variable 'a' referenced before assignment函数时,都会收到Dropout。没有Dropout行的相同代码可以正常工作。

有人知道不使用3.6版本如何解决此问题吗?

谢谢!


我正在使用...

macOS 10.14.4
Python 3.7.3
Keras 2.2.4
TensorFlow 1.13.1

更新1:我提供了与该问题相关的代码

def create_model(neurons, learn_rate):
    model = Sequential()
    model.add(Dense(neurons, input_shape=(100,), activation='sigmoid'))
    model.add(Dropout(0.2))
    model.add(Dense(5, activation='softmax'))

    optimizer = SGD(lr=learn_rate)
    model.compile(loss='sparse_categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
    return model

model=create_model(neurons=584, learn_rate=0.035)
model.fit(X_train, y_train, epochs=139);
score = model.evaluate(X_test, y_test);
print(score)

更新2:我包括完整的追溯

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-4-7807c02c4f54> in <module>
      9     return model
     10 
---> 11 model=create_model(neurons=584, learn_rate=0.035)
     12 model.fit(X_train, y_train, epochs=139);
     13 score = model.evaluate(X_test, y_test);

<ipython-input-4-7807c02c4f54> in create_model(neurons, learn_rate)
      2     model = Sequential()
      3     model.add(Dense(neurons, input_shape=(100,), activation='sigmoid'))
----> 4     model.add(Dropout(0.2))
      5     model.add(Dense(5, activation='softmax'))
      6 

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/keras/engine/sequential.py in add(self, layer)
    179                 self.inputs = network.get_source_inputs(self.outputs[0])
    180         elif self.outputs:
--> 181             output_tensor = layer(self.outputs[0])
    182             if isinstance(output_tensor, list):
    183                 raise TypeError('All layers in a Sequential model '

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    455             # Actually call the layer,
    456             # collecting output(s), mask(s), and shape(s).
--> 457             output = self.call(inputs, **kwargs)
    458             output_mask = self.compute_mask(inputs, previous_mask)
    459 

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/keras/layers/core.py in call(self, inputs, training)
    124                                  seed=self.seed)
    125             return K.in_train_phase(dropped_inputs, inputs,
--> 126                                     training=training)
    127         return inputs
    128 

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in in_train_phase(x, alt, training)
   3103     """
   3104     if training is None:
-> 3105         training = learning_phase()
   3106         uses_learning_phase = True
   3107     else:

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py in learning_phase()
    133         phase = tf.placeholder_with_default(False,
    134                                             shape=(),
--> 135                                             name='keras_learning_phase')
    136         _GRAPH_LEARNING_PHASES[graph] = phase
    137     return _GRAPH_LEARNING_PHASES[graph]

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/tensorflow/python/ops/array_ops.py in placeholder_with_default(input, shape, name)
   2091     A `Tensor`. Has the same type as `input`.
   2092   """
-> 2093   return gen_array_ops.placeholder_with_default(input, shape, name)
   2094 
   2095 

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/tensorflow/python/ops/gen_array_ops.py in placeholder_with_default(input, shape, name)
   5923   shape = _execute.make_shape(shape, "shape")
   5924   _, _, _op = _op_def_lib._apply_op_helper(
-> 5925         "PlaceholderWithDefault", input=input, shape=shape, name=name)
   5926   _result = _op.outputs[:]
   5927   _inputs_flat = _op.inputs

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py in _apply_op_helper(self, op_type_name, name, **keywords)
    509                 dtype=dtype,
    510                 as_ref=input_arg.is_ref,
--> 511                 preferred_dtype=default_dtype)
    512           except TypeError as err:
    513             if dtype is None:

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, ctx, accept_symbolic_tensors)
   1173 
   1174     if ret is None:
-> 1175       ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
   1176 
   1177     if ret is NotImplemented:

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref)
    302                                          as_ref=False):
    303   _ = as_ref
--> 304   return constant(v, dtype=dtype, name=name)
    305 
    306 

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py in constant(value, dtype, shape, name)
    243   """
    244   return _constant_impl(value, dtype, shape, name, verify_shape=False,
--> 245                         allow_broadcast=True)
    246 
    247 

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/tensorflow/python/framework/constant_op.py in _constant_impl(value, dtype, shape, name, verify_shape, allow_broadcast)
    281       tensor_util.make_tensor_proto(
    282           value, dtype=dtype, shape=shape, verify_shape=verify_shape,
--> 283           allow_broadcast=allow_broadcast))
    284   dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)
    285   const_tensor = g.create_op(

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape, allow_broadcast)
    571     raise TypeError(
    572         "Element type not supported in TensorProto: %s" % numpy_dtype.name)
--> 573   append_fn(tensor_proto, proto_values)
    574 
    575   return tensor_proto

tensorflow/python/framework/fast_tensor_util.pyx in tensorflow.python.framework.fast_tensor_util.AppendBoolArrayToTensorProto()

~/anaconda3/envs/deep-3.7/lib/python3.7/site-packages/numpy/lib/type_check.py in asscalar(***failed resolving arguments***)
    545     warnings.warn('np.asscalar(a) is deprecated since NumPy v1.16, use '
    546                   'a.item() instead', DeprecationWarning, stacklevel=1)
--> 547     return a.item()
    548 
    549 #-----------------------------------------------------------------------------

UnboundLocalError: local variable 'a' referenced before assignment
``

1 个答案:

答案 0 :(得分:0)

我发现安装pip install tf-nightly可以解决问题。