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]

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

最新更新