python - 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 模型仅在急切执行期间调用时接受张量,如其 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中查看源代码。
推荐阅读
- c++ - 惰性初始化 VkObjects 的 Vulkan 用例
- azure-data-factory-2 - 获取数据工厂中单个管道执行的成本
- javascript - 使用 xpath 解析属性页 URL
- mongodb - Robomongo 查询以返回 id 列表
- javascript - 显示一个盒子,只要鼠标在它上面就不会褪色
- python - 当用户未分配给应用程序的角色时捕获 oauthlib.oauth2.rfc6749.errors.CustomOAuth2Error
- wordpress - 向黑客透露 wp-config.php 是否是一个问题?
- python - 在 Mac 上更改 python tkinter 按钮颜色会使按钮单击不可见?
- sql - 加入组 PySpark - SQL 到 Pysaprk
- c# - c# Generic Type System - 自引用泛型类型