在使用 keras 构建简单的序列模型后,我在使用 .compile() 时遇到问题。
我得到的错误类型:
TypeError: 'str' 对象不可调用
顺便说一下,我在 Colab 上运行了代码并且它工作正常。问题是代码在我的系统上不起作用,而我使用的是 anaconda Jupyter notebook。
代码:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential(
[
layers.Dense(2, activation="relu", name ="layer1"),
layers.Dense(3, activation="relu", name ="layer2"),
layers.Dense(4, name="layer3")
])
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/array_ops.py in zeros(shape, dtype, name)
2725 # Go through tensor shapes to get int64-if-needed semantics
-> 2726 shape = constant_op._tensor_shape_tensor_conversion_function(
2727 tensor_shape.TensorShape(shape))
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py in _tensor_shape_tensor_conversion_function(s, dtype, name, as_ref)
356 name = "shape_as_tensor"
--> 357 return constant(s_list, dtype=dtype, name=name)
358
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py in constant(value, dtype, shape, name)
261 """
--> 262 return _constant_impl(value, dtype, shape, name, verify_shape=False,
263 allow_broadcast=True)
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py in _constant_impl(value, dtype, shape, name, verify_shape, allow_broadcast)
270 if ctx.executing_eagerly():
--> 271 t = convert_to_eager_tensor(value, ctx, dtype)
272 if shape is None:
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py in convert_to_eager_tensor(value, ctx, dtype)
96
---> 97 return ops.EagerTensor(value, ctx.device_name(), dtype)
98
TypeError: 'str' object is not callable
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-107-3bc1e703d8ff> in <module>
----> 1 model.compile(loss=loss, optimizer=optim, metrics=metrics)
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, **kwargs)
327
328 self.optimizer = self._get_optimizer(optimizer)
--> 329 self.compiled_loss = compile_utils.LossesContainer(
330 loss, loss_weights, output_names=self.output_names)
331 self.compiled_metrics = compile_utils.MetricsContainer(
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/keras/engine/compile_utils.py in __init__(self, losses, loss_weights, output_names)
118 self._loss_weights = loss_weights
119 self._per_output_metrics = None # Per-output losses become metrics.
--> 120 self._loss_metric = metrics_mod.Mean(name='loss') # Total loss.
121 self._built = False
122
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/keras/metrics.py in __init__(self, name, dtype)
468 dtype: (Optional) data type of the metric result.
469 """
--> 470 super(Mean, self).__init__(
471 reduction=metrics_utils.Reduction.WEIGHTED_MEAN, name=name, dtype=dtype)
472
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/keras/metrics.py in __init__(self, reduction, name, dtype)
305 self.reduction = reduction
306 with ops.init_scope():
--> 307 self.total = self.add_weight(
308 'total', initializer=init_ops.zeros_initializer)
309 if reduction in [metrics_utils.Reduction.SUM_OVER_BATCH_SIZE,
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/keras/metrics.py in add_weight(self, name, shape, aggregation, synchronization, initializer, dtype)
274 synchronization = tf_variables.VariableSynchronization.ON_WRITE
275
--> 276 return super(Metric, self).add_weight(
277 name=name,
278 shape=shape,
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/keras/engine/base_layer.py in add_weight(self, name, shape, dtype, initializer, regularizer, trainable, constraint, partitioner, use_resource, synchronization, aggregation, **kwargs)
558 caching_device = None
559
--> 560 variable = self._add_variable_with_custom_getter(
561 name=name,
562 shape=shape,
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/training/tracking/base.py in _add_variable_with_custom_getter(self, name, shape, dtype, initializer, getter, overwrite, **kwargs_for_getter)
736 initializer = checkpoint_initializer
737 shape = None
--> 738 new_variable = getter(
739 name=name,
740 shape=shape,
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/keras/engine/base_layer_utils.py in make_variable(name, shape, dtype, initializer, trainable, caching_device, validate_shape, constraint, use_resource, collections, synchronization, aggregation, partitioner)
127 # can remove the V1.
128 variable_shape = tensor_shape.TensorShape(shape)
--> 129 return tf_variables.VariableV1(
130 initial_value=init_val,
131 name=name,
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/variables.py in __call__(cls, *args, **kwargs)
257 def __call__(cls, *args, **kwargs):
258 if cls is VariableV1:
--> 259 return cls._variable_v1_call(*args, **kwargs)
260 elif cls is Variable:
261 return cls._variable_v2_call(*args, **kwargs)
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/variables.py in _variable_v1_call(cls, initial_value, trainable, collections, validate_shape, caching_device, name, variable_def, dtype, expected_shape, import_scope, constraint, use_resource, synchronization, aggregation, shape)
203 if aggregation is None:
204 aggregation = VariableAggregation.NONE
--> 205 return previous_getter(
206 initial_value=initial_value,
207 trainable=trainable,
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/variables.py in getter(**kwargs)
64
65 def getter(**kwargs):
---> 66 return captured_getter(captured_previous, **kwargs)
67
68 return getter
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/distribute/distribute_lib.py in creator(next_creator, **kwargs)
2560 def creator(next_creator, **kwargs):
2561 _require_strategy_scope_strategy(strategy)
-> 2562 return next_creator(**kwargs)
2563
2564 self._var_creator_scope = variable_scope.variable_creator_scope(creator)
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/variables.py in <lambda>(**kwargs)
196 shape=None):
197 """Call on Variable class. Useful to force the signature."""
--> 198 previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs)
199 for _, getter in ops.get_default_graph()._variable_creator_stack: # pylint: disable=protected-access
200 previous_getter = _make_getter(getter, previous_getter)
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/variable_scope.py in default_variable_creator(next_creator, **kwargs)
2582 if use_resource:
2583 distribute_strategy = kwargs.get("distribute_strategy", None)
-> 2584 return resource_variable_ops.ResourceVariable(
2585 initial_value=initial_value,
2586 trainable=trainable,
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/variables.py in __call__(cls, *args, **kwargs)
261 return cls._variable_v2_call(*args, **kwargs)
262 else:
--> 263 return super(VariableMetaclass, cls).__call__(*args, **kwargs)
264
265
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/resource_variable_ops.py in __init__(self, initial_value, trainable, collections, validate_shape, caching_device, name, dtype, variable_def, import_scope, constraint, distribute_strategy, synchronization, aggregation, shape)
1421 self._init_from_proto(variable_def, import_scope=import_scope)
1422 else:
-> 1423 self._init_from_args(
1424 initial_value=initial_value,
1425 trainable=trainable,
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/resource_variable_ops.py in _init_from_args(self, initial_value, trainable, collections, caching_device, name, dtype, constraint, synchronization, aggregation, distribute_strategy, shape)
1565 with ops.name_scope("Initializer"), device_context_manager(None):
1566 initial_value = ops.convert_to_tensor(
-> 1567 initial_value() if init_from_fn else initial_value,
1568 name="initial_value", dtype=dtype)
1569 if shape is not None:
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/keras/engine/base_layer_utils.py in <lambda>()
119 (type(init_ops.Initializer), type(init_ops_v2.Initializer))):
120 initializer = initializer()
--> 121 init_val = lambda: initializer(shape, dtype=dtype)
122 variable_dtype = dtype.base_dtype
123 if use_resource is None:
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/init_ops.py in __call__(self, shape, dtype, partition_info)
112 if dtype is None:
113 dtype = self.dtype
--> 114 return array_ops.zeros(shape, dtype)
115
116 def get_config(self):
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/array_ops.py in wrapped(*args, **kwargs)
2675
2676 def wrapped(*args, **kwargs):
-> 2677 tensor = fun(*args, **kwargs)
2678 tensor._is_zeros_tensor = True
2679 return tensor
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/ops/array_ops.py in zeros(shape, dtype, name)
2728 except (TypeError, ValueError):
2729 # Happens when shape is a list with tensor elements
-> 2730 shape = ops.convert_to_tensor(shape, dtype=dtypes.int32)
2731 if not shape._shape_tuple():
2732 shape = reshape(shape, [-1]) # Ensure it's a vector
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/framework/ops.py in convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, dtype_hint, ctx, accepted_result_types)
1339
1340 if ret is None:
-> 1341 ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
1342
1343 if ret is NotImplemented:
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref)
320 as_ref=False):
321 _ = as_ref
--> 322 return constant(v, dtype=dtype, name=name)
323
324
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py in constant(value, dtype, shape, name)
260 ValueError: if called on a symbolic tensor.
261 """
--> 262 return _constant_impl(value, dtype, shape, name, verify_shape=False,
263 allow_broadcast=True)
264
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py in _constant_impl(value, dtype, shape, name, verify_shape, allow_broadcast)
269 ctx = context.context()
270 if ctx.executing_eagerly():
--> 271 t = convert_to_eager_tensor(value, ctx, dtype)
272 if shape is None:
273 return t
~/anaconda3/envs/tf-gpu/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py in convert_to_eager_tensor(value, ctx, dtype)
95 ctx.ensure_initialized()
96
---> 97 return ops.EagerTensor(value, ctx.device_name(), dtype)
98
99
TypeError: 'str' object is not callable