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

Keras模型输入形状兼容却报错:Siamese分支形状不匹配求助

问题诊断与解决

核心问题

你的模型输入要求带批量维度(Batch Dimension),但当前传入的样本缺少这个维度:

  • 模型期望输入形状:(None, 40000, 1)(None代表任意批量大小)
  • 实际传入样本形状:(40000, 1)

当输入没有批量维度时,TensorFlow会错误地将40000识别为批量大小,1识别为特征维度,经过Siamese分支处理后形状被压缩为(32,1),最终与层的期望形状不匹配,触发报错。

解决方案

给每个输入样本增加批量维度,将形状从(40000,1)转换为(1,40000,1),可以通过numpy.expand_dims实现:

修改后的测试代码:

import os
import keras
import numpy as np
import tensorflow as tf
from main_copy import path_to_fft

model = keras.models.load_model(os.path.join(os.getcwd(), "model.keras"))

model.summary()
model.summary(expand_nested=True)

first_sample = path_to_fft(os.path.join(os.getcwd(), 'Sounds', 'Thomas', 'thomas_original.wav'))
second_sample = path_to_fft(os.path.join(os.getcwd(), 'Sounds', 'Thomas', 'thomas_original.wav'))

# 增加批量维度
first_sample = np.expand_dims(first_sample, axis=0)
second_sample = np.expand_dims(second_sample, axis=0)

print("First: ", first_sample.shape)  # 输出应为(1, 40000, 1)
print("Second: ", second_sample.shape)

prediction = model.predict([first_sample, second_sample])
print(prediction)

补充说明

  • 批量维度是Keras/TensorFlow模型的标准要求,即使只预测单样本,也需要显式添加该维度。
  • 你日志中看到的TensorSpec(shape=(32,), dtype=tf.int64)是TensorFlow内部追踪函数时生成的临时参数,与你的输入问题无关,无需关注。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:50:06