TensorFlow预测报错:expected min_ndim=2, found ndim=1
解决Keras模型预测时输入维度不兼容的问题
问题核心
你的模型训练时接收的是二维输入(形状(3145, 11),对应3145个样本,每个样本11个特征),但预测时传入的是一维数据(形状(11,)),不符合模型对输入维度的要求,因此报错。
解决方案
给待预测数据增加一个batch维度,将形状从(11,)转换为(1, 11),让模型识别这是1个带11个特征的样本。
具体实现代码
以下几种方式都可以实现维度扩展:
- 使用
numpy.expand_dims:
import numpy as np to_be_predicted = np.expand_dims(to_be_predicted, axis=0) output = model.predict(x=to_be_predicted)
- 使用Python索引语法快速扩展:
# 两种写法等价 to_be_predicted = to_be_predicted[np.newaxis, :] # 或者 to_be_predicted = to_be_predicted[None, :] output = model.predict(x=to_be_predicted)
- 如果是TensorFlow张量,使用
tf.expand_dims:
import tensorflow as tf to_be_predicted = tf.expand_dims(to_be_predicted, axis=0) output = model.predict(x=to_be_predicted)
补充说明
你之前添加model.add(tf.keras.layers.Input(shape=(11,)))的操作是正确的,这个层定义的是单个样本的特征形状,而模型实际接收的输入需要是(batch_size, 11)的二维张量——即使只有一个样本,也必须保留batch维度(即(1, 11)),否则模型会无法正确解析输入结构。
内容的提问来源于stack exchange,提问作者welchs
相关产品推荐
相关产品推荐

