【问题标题】:Inconsistency in tensorflow 2.0 Model predict and call methods. Call method fails with InvalidArgumentErrortensorflow 2.0 模型预测和调用方法不一致。调用方法因 InvalidArgumentError 而失败
【发布时间】:2020-03-02 19:41:08
【问题描述】:

为什么模型预测工作但模型(数据)在 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]

【问题讨论】:

    标签: python tensorflow tensorflow2.0 tf.keras


    【解决方案1】:

    TensorFlow 模型 仅在 Eager Execution 期间调用时接受张量,如其 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)
    

    我把你用来预测的数据变量转换成了张量变量

    见下面修改后的代码:

    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 中查看源代码

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 1970-01-01
      • 2018-07-06
      • 2023-02-09
      • 1970-01-01
      • 2018-11-27
      • 2013-07-03
      • 2020-04-05
      • 1970-01-01
      相关资源
      最近更新 更多