首页 > 解决方案 > Estimator.predict() TypeError: 期望任何非张量类型,取而代之的是张量

问题描述

我尝试使用 VGG 神经网络从视频中通过唇读来预测单词,tensorflow.compat.v1.version但我无法从估计器中获得预测。该模型是定制的,我在培训或评估方面没有任何问题。

这是代码:

# Create the classifier
print("Creating classifier from {}".format(checkpoint_path))
classifier = tf.estimator.Estimator(
    model_fn=vgg_model_fn,
    params=params,
    model_dir=checkpoint_path,
)

print("Computing predictions")
predictions = classifier.predict(
    input_fn=tf.estimator.inputs.numpy_input_fn(
        {"x": video},
        batch_size=1,
        shuffle=False,
    )
)

# Print predictions
predictions = list(predictions)
predicted_class = predictions["classes"]
top_k_classes = (-predictions["probabilities"]).argsort()[:int(k)]

线路predictions = list(predictions)抛出TypeError: Expected any non-tensor type, got a tensor instead.,我找不到任何替代方案。 next(generator)也不行。

完整的错误日志:

INFO:tensorflow:Calling model_fn.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_util.py in _AssertCompatible(values, dtype)
    329   try:
--> 330     fn(values)
    331   except ValueError as e:

15 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_util.py in _check_not_tensor(values)
    281 def _check_not_tensor(values):
--> 282   _ = [_check_failed(v) for v in nest.flatten(values)
    283        if isinstance(v, ops.Tensor)]

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_util.py in <listcomp>(.0)
    282   _ = [_check_failed(v) for v in nest.flatten(values)
--> 283        if isinstance(v, ops.Tensor)]
    284 # pylint: enable=invalid-name

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_util.py in _check_failed(v)
    249   # it is safe to use here.
--> 250   raise ValueError(v)
    251 

ValueError: Tensor("fifo_queue_DequeueUpTo:1", shape=(?, 64, 64, 29), dtype=float64, device=/device:CPU:0)

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-21-f9ab355166d2> in <module>()
     78 
     79 print("######################\n\n")
---> 80 predictions = list(predictions)
     81 
     82 predicted_class = predictions["classes"]

/usr/local/lib/python3.7/dist-packages/tensorflow_estimator/python/estimator/estimator.py in predict(self, input_fn, predict_keys, hooks, checkpoint_path, yield_single_examples)
    611             input_fn, ModeKeys.PREDICT)
    612         estimator_spec = self._call_model_fn(features, None, ModeKeys.PREDICT,
--> 613                                              self.config)
    614 
    615         # Call to warm_start has to be after model_fn is called.

/usr/local/lib/python3.7/dist-packages/tensorflow_estimator/python/estimator/estimator.py in _call_model_fn(self, features, labels, mode, config)
   1161 
   1162     logging.info('Calling model_fn.')
-> 1163     model_fn_results = self._model_fn(features=features, **kwargs)
   1164     logging.info('Done calling model_fn.')
   1165 

<ipython-input-7-9d657a95e832> in vgg_model_fn(features, labels, mode, params)
     12     """
     13     # Useful variables
---> 14     tf.dtypes.cast(features, tf.float64)
     15     num_classes = params["num_classes"]
     16     if (mode == tf.estimator.ModeKeys.TRAIN):

/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py in wrapper(*args, **kwargs)
    199     """Call target, and fall back on dispatchers if there is a TypeError."""
    200     try:
--> 201       return target(*args, **kwargs)
    202     except (TypeError, ValueError):
    203       # Note: convert_to_eager_tensor currently raises a ValueError, not a

/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/math_ops.py in cast(x, dtype, name)
    962       # allows some conversions that cast() can't do, e.g. casting numbers to
    963       # strings.
--> 964       x = ops.convert_to_tensor(x, name="x")
    965       if x.dtype.base_dtype != base_type:
    966         x = gen_math_ops.cast(x, base_type, name=name)

/usr/local/lib/python3.7/dist-packages/tensorflow/python/profiler/trace.py in wrapped(*args, **kwargs)
    161         with Trace(trace_name, **trace_kwargs):
    162           return func(*args, **kwargs)
--> 163       return func(*args, **kwargs)
    164 
    165     return wrapped

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py in convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, dtype_hint, ctx, accepted_result_types)
   1538 
   1539     if ret is None:
-> 1540       ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
   1541 
   1542     if ret is NotImplemented:

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref)
    337                                          as_ref=False):
    338   _ = as_ref
--> 339   return constant(v, dtype=dtype, name=name)
    340 
    341 

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/constant_op.py in constant(value, dtype, shape, name)
    263   """
    264   return _constant_impl(value, dtype, shape, name, verify_shape=False,
--> 265                         allow_broadcast=True)
    266 
    267 

/usr/local/lib/python3.7/dist-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   attrs = {"value": tensor_value, "dtype": dtype_value}

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape, allow_broadcast)
    455       nparray = np.empty(shape, dtype=np_dt)
    456     else:
--> 457       _AssertCompatible(values, dtype)
    458       nparray = np.array(values, dtype=np_dt)
    459       # check to them.

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_util.py in _AssertCompatible(values, dtype)
    332     [mismatch] = e.args
    333     if dtype is None:
--> 334       raise TypeError("Expected any non-tensor type, got a tensor instead.")
    335     else:
    336       raise TypeError("Expected %s, got %s of type '%s' instead." %

TypeError: Expected any non-tensor type, got a tensor instead.

有人遇到过这种问题吗?

标签: pythonpython-3.xtensorflowmachine-learning

解决方案


我改为:

predictions = classifier.predict(
    input_fn=tf.estimator.inputs.numpy_input_fn(
        x=video,
        y=None,
        shuffle=False
    )
)

不是我有一个非常不同类型的错误。

InvalidArgumentError: 2 root error(s) found.
  (0) Invalid argument: tensor_name = bn_conv1/beta; expected dtype double does not equal original dtype float
tensor_name = bn_conv1/gamma; expected dtype double does not equal original dtype float
...
  File "/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py", line 1990, in __init__
    self._traceback = tf_stack.extract_stack()


During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/training/saver.py in restore(self, sess, save_path)
   1332       # We add a more reasonable error message here to help users (b/110263146)
   1333       raise _wrap_restore_error_with_msg(
-> 1334           err, "a mismatch between the current graph and the graph")
   1335 
   1336   @staticmethod

InvalidArgumentError: Restoring from checkpoint failed. This is most likely due to a mismatch between the current graph and the graph from the checkpoint. Please ensure that you have not altered the graph expected based on the checkpoint. Original error:

2 root error(s) found.
  (0) Invalid argument: tensor_name = bn_conv1/beta; expected dtype double does not equal original dtype float
tensor_name = bn_conv1/gamma; expected dtype double does not equal original dtype float
...


推荐阅读