You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Keras model.predict()时“输入形状不兼容”错误的解决方法

解决Keras模型输入形状不兼容问题

错误根源

你的模型定义时,输入层要求每个样本是48维向量,Keras模型默认接收批量输入,即输入形状为(batch_size, 48)(None代表任意批量大小)。你当前的输入要么是单个标量(如np.array([48]),形状(1,)),要么是单个48维向量但缺少批量维度(如tf.ones((48,)),形状(48,)),导致形状不匹配。

具体解决方案

1. 输入单个48维样本

确保输入是48个元素的向量,然后增加批量维度(让形状变为(1, 48)),有几种实现方式:

  • 使用NumPy:
    # 先创建48维的输入向量(示例用全1向量,实际替换为你的数据)
    test_input = np.ones((48,))
    # 增加批量维度
    test_input_batch = test_input[np.newaxis, :]
    # 执行预测
    result = model1.predict(test_input_batch)[0]
    
  • 使用TensorFlow:
    test_input = tf.ones((48,))
    test_input_batch = tf.expand_dims(test_input, axis=0)
    result = model1(test_input_batch)[0]
    

2. 输入多个48维样本

直接构造形状为(batch_size, 48)的输入,比如批量大小为5:

# 生成5个48维样本
batch_input = np.random.rand(5, 48)
# 执行预测,输出形状为(5,4)
results = model1.predict(batch_input)

注意事项

  • 不要用np.array([48])作为输入:这是仅含单个元素的数组,形状(1,),完全不符合模型要求的48维输入。你需要的是包含48个数值的向量,比如np.array([1,2,...,48])(48个元素)。
  • 输入数据类型要匹配:模型默认接收float32类型,如果你的输入是int32,可以通过test_input = test_input.astype(np.float32)转换。

内容的提问来源于stack exchange,提问作者Tiziano GIANNELLI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:45:22