考虑以下神经网络的“ hello world”:
(X_train, y_train),(X_test, y_test) = keras.datasets.mnist.load_data()
X_train, X_test = X_train / 255.0, X_test / 255.0
net = keras.models.Sequential([
keras.layers.Flatten(),
keras.layers.Dense(512, activation=tf.nn.relu),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
net.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
net.fit(X_train, y_train, epochs=5, verbose=True)
调用fit方法会导致以下异常。
版本:
keras: 2.2.4
tensorflow: 1.13.1
我用Anaconda重新安装了keras和tensorflow:
conda install -c conda-forge keras tensorflow
以下警告似乎可疑,但解决方案尚不清楚:
关于模块导入:
Using TensorFlow backend.
/Users/cls/anaconda3/lib/python3.7/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.6 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.7
return f(*args, **kwds)
编译时:
WARNING:tensorflow:From /Users/cls/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
stdout中的某处:
2019-05-14 16:40:10.628107: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
错误消息:
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<timed eval> in <module>
~/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
950 sample_weight=sample_weight,
951 class_weight=class_weight,
--> 952 batch_size=batch_size)
953 # Prepare validation data.
954 do_validation = False
~/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
675 # to match the value shapes.
676 if not self.inputs:
--> 677 self._set_inputs(x)
678
679 if y is not None:
~/anaconda3/lib/python3.7/site-packages/keras/engine/training.py in _set_inputs(self, inputs, outputs, training)
587 assert len(inputs) == 1
588 inputs = inputs[0]
--> 589 self.build(input_shape=(None,) + inputs.shape[1:])
590 return
591
~/anaconda3/lib/python3.7/site-packages/keras/engine/sequential.py in build(self, input_shape)
219 self.inputs = [x]
220 for layer in self._layers:
--> 221 x = layer(x)
222 self.outputs = [x]
223 self._build_input_shape = input_shape
~/anaconda3/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/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/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/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/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/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/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/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/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/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/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/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/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
答案 0 :(得分:1)
从Tensorflow 1.14开始,官方软件包分发支持python 3.4及更高版本。不确定每个版本的python是否有单独的轮子,但是好的主意是通过pip install
以推荐的方式安装tensorflow。
尝试解决此问题的命令:
pip install --upgrade --force-reinstall tensorflow
# pip install --upgrade --force-reinstall tensorflow-gpu
更新:Tensorflow 1.13不支持python 3.7