python - 使用张量数组作为输入时,TensorFlow 2.4.0 model.predict 错误
问题描述
根据Keras Sequential Model .predict()文档,该模型可以使用多种输入形式,包括:
TensorFlow 张量或张量列表(如果模型有多个输入)。
这正是我想要做的,即使用两个张量的“批次”作为 predict() 的输入,并在以下代码中获得两个预测作为输出:
test_batch = (img_tf1, img_tf2) # two Tensors in list
predictions = model.predict(test_batch)
但是我收到以下错误:
ValueError: Layer sequential expects 1 input(s), but it received 2 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(32, 224, 3) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(32, 224, 3) dtype=float32>]
形状如下:
- 模型输入:
<KerasTensor: shape=(None, 224, 224, 3) dtype=float32
- 测试批次:
(<tf.Tensor: shape=(224, 224, 3), dtype=float32>, <tf.Tensor: shape=(224, 224, 3), dtype=float32>)
有谁知道问题出在哪里?我相信我正确地使用了 API,正如文档中所指定的那样。我的 TensorFlow 版本是 2.4.0,在 conda 环境中安装了 pip。
解决方案
TensorFlow 将它们视为模型的单独输入,因为它们没有堆叠。你可以做两件事:
img1 = tf.expand_dims(img1, axis = 0) # in case you did not add batch dims.
img2 = tf.expand_dims(img2, axis = 0) # in case you did not add batch dims.
test_batch = (img1,img2)
test_batch = tf.experimental.numpy.vstack(test_batch)
preds = last_model.predict(test_batch)
或者你可以创建tf.data.Dataset
,它们稍后会被批处理:
img1 = tf.random.uniform((32,32,3))
img2 = tf.random.uniform((32,32,3))
test_batch = [img1,img2] # store them in a list
test_batch = tf.data.Dataset.from_tensor_slices(test_batch).batch(1)
我们可以看到它们有一个批次维度。
test_batch
<BatchDataset shapes: (None, 32, 32, 3), types: tf.float32>
之后,可以预测:
preds = last_model.predict(test_batch)
推荐阅读
- google-chrome - 在使用 rotractor/Selenium Web 驱动程序/Chrome 浏览器时禁用命令提示符上的 log4net 错误
- reactjs - 如何每 X 秒刷新一次 React-Admin 列表数据?
- reactjs - 反应组件没有收到道具
- swift - 无法使用切换行为来触发 SWIFTUI 中的 .buttonStyle
- javascript - 如果对象值存在于javascript中的对象数组中,则显示alreat消息
- javascript - 如何使这个 Wasm 函数在其母语中易于阅读?
- javascript - Javascript收银机 - 为什么我不能记录面额的总值
- asp.net - PdfSearchTextExtractor - 对象引用未设置为对象的实例
- c++ - 关于封装和继承实践的问题
- javascript - 谷歌图表 setColumns 行为不正确