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

Keras TimeDistributed层输入形状不匹配问题求助

问题原因与解决方法

错误原因

你用的LSTM层默认return_sequences=False,只会输出最后一个时间步的特征,输出形状是(None, 16)(2维),但TimeDistributed层要求输入必须是至少3维的张量(批量大小,时间步,特征数)——它的作用是对每个时间步单独应用Dense层,所以2维输入直接触发了报错。

解决步骤

  1. 修改LSTM层参数:给LSTM加上return_sequences=True,让它返回每个时间步的输出,此时LSTM的输出形状变成(None, 10, 16)(3维),刚好满足TimeDistributed的要求。
  2. 调整Dense层输出维度:你的标签形状是(100,10,1),最后一层Dense的输出单元数应该设为1,而不是10,否则会出现输出与标签形状不匹配的新错误。

修正后的代码

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, TimeDistributed, Dense
import numpy as np

data = np.random.random((100, 10, 32))
labels = np.random.randint(2, size=(100, 10, 1))

model = Sequential()
# 加入return_sequences=True,返回所有时间步的输出
model.add(LSTM(16, input_shape=(10, 32), return_sequences=True))
# Dense输出单元改为1,匹配标签形状
model.add(TimeDistributed(Dense(1, activation='sigmoid')))

model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(data, labels, epochs=10, batch_size=32)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:05:35