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

Keras Scaled-Dot Attention模型输入维度不匹配ValueError求助

问题分析与解决

错误原因

报错ValueError: Input 0 is incompatible with layer model_1: expected shape=(None, 500, 3), found shape=(500, 3)的核心是数据维度与模型输入不匹配:

  • 模型定义的输入是3D张量:(batch_size, 500, 3),其中500是时间步长,3是每个时间步的特征数;
  • 你用make_classification生成的X是2D张量(500, 3),仅包含500个样本的3个特征,缺少时间步维度;
  • 同时标签y的格式也不符合要求:模型输出是(None, 500, 2)的序列标签,而make_classification生成的是1D分类标签,与categorical_crossentropy损失函数的要求不匹配。

修正方案

1. 生成符合要求的输入数据

替换当前的make_classification代码,直接生成3D时间序列数据:

import numpy as np
from tensorflow.keras.utils import to_categorical

# 生成64个样本,每个样本是500步、3特征的时间序列
X = np.random.rand(64, 500, 3)
# 生成对应标签:64个样本,每个时间步输出2类独热编码
y = np.random.randint(0, 2, size=(64, 500))
y = to_categorical(y, num_classes=2)

如果一定要基于make_classification生成的数据构造时间序列,可以将每个样本重复500次作为时间步:

from sklearn.datasets import make_classification
from tensorflow.keras.utils import to_categorical
import numpy as np

# 生成500个样本的2D数据
X_2d, y_2d = make_classification(n_samples=500, n_features=3, n_redundant=0, n_repeated=0, n_informative=3,
                           n_classes=2, random_state=1)
# 转换为3D时间序列:每个样本重复500次作为时间步
X = np.repeat(X_2d[:, np.newaxis, :], 500, axis=1)
# 转换标签为3D独热编码
y = to_categorical(y_2d, num_classes=2)
y = np.repeat(y[:, np.newaxis, :], 500, axis=1)

2. 验证数据维度

运行print(X.shape, y.shape),应该输出类似(64, 500, 3) (64, 500, 2)的结果,确保与模型输入输出维度匹配。

3. 重新训练模型

使用修正后的数据执行训练:

model.fit(X, y, batch_size=32, epochs=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:35:21