首页 > 解决方案 > tensorflow 2.0 模型预测和调用方法不一致。调用方法因 InvalidArgumentError 而失败

问题描述

为什么模型预测工作但模型(数据)在 tf 2.0 中对于以下代码失败?

from tensorflow.keras import layers,Input
import tensorflow as tf
input_layer = Input(1)
d1 = layers.Dense(64, activation='relu')(input_layer)
d2 = layers.Dense(3, activation='relu')(d1)
model = tf.keras.Model(inputs=[input_layer], outputs=d2)
data = [[1.0]]
print(model.predict(data)) # Works
print(model(data)) # fails with  tensorflow.python.framework.errors_impl.InvalidArgumentError: In[0] is not a matrix. Instead it has shape [] [Op:MatMul]

标签: pythontensorflowtensorflow2.0tf.keras

解决方案


TensorFlow 模型仅在急切执行期间调用时接受张量,如其 GitHub 存储库中所示。这是您执行时提出的行之一model(data)

# Eager execution on data tensors.
        with backend.name_scope(self._name_scope()):
          self._maybe_build(inputs)
          cast_inputs = self._maybe_cast_inputs(inputs)
          with base_layer_utils.autocast_context_manager(
              self._compute_dtype):
            outputs = self.call(cast_inputs, *args, **kwargs)  # <<< ERROR HERE
          self._handle_activity_regularization(inputs, outputs)
          self._set_mask_metadata(inputs, outputs, input_masks)

我将您用于预测的Data 变量转换为Tensor Variable

请看下面修改后的代码:

from tensorflow.keras import layers, Input
import tensorflow as tf

input_layer = Input(1)
d1 = layers.Dense(64, activation='relu')(input_layer)
d2 = layers.Dense(3, activation='relu')(d1)
model = tf.keras.Model(inputs=[input_layer], outputs=d2)
data = [[1.0]]
print(model.predict(data)) # [[0.02674201 0.         0.        ]]
print(model(tf.Variable(data))) # tf.Tensor([[0.02674201 0.         0.        ]], shape=(1, 3), dtype=float32)

您可以在 TensorFlow Github中查看源代码


推荐阅读